Java.lang Package Classes

Java Boolean - compare() Method



The java.lang.Boolean.compare() method is used to compare two boolean values. The value returned is identical to what would be returned by: Boolean.valueOf(x).compareTo(Boolean.valueOf(y)).

Syntax

public static int compare(boolean x,
                          boolean y)

Parameters

x Specify the first boolean to compare.
y Specify the second boolean to compare.

Return Value

Returns the value 0 if x == y; a value less than 0 if !x && y; and a value greater than 0 if x && !y.

Exception

NA.

Example:

In the example below, the java.lang.Boolean.compare() method is used to compare given boolean values.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //creating boolean values
    boolean b1 = true;
    boolean b2 = false;

    //comparing boolean values 
    System.out.println("comparing b1 and b1: " + Boolean.compare(b1, b1)); 
    System.out.println("comparing b2 and b2: " + Boolean.compare(b2, b2)); 
    System.out.println("comparing b1 and b2: " + Boolean.compare(b1, b2)); 
    System.out.println("comparing b2 and b1: " + Boolean.compare(b2, b1));    
  }
}

The output of the above code will be:

comparing b1 and b1: 0
comparing b2 and b2: 0
comparing b1 and b2: 1
comparing b2 and b1: -1

❮ Java.lang - Boolean