What is the Boolean.compare method in Java?

The static method compare of the Boolean class is used to compare two Boolean values.

Syntax

public static int compare(boolean x, boolean y);

Return value

The compare method returns:

  • 0 if both the values are the same.

  • A value less than 0 if x is false and y is true.

  • A value greater than 0 if x is true and y is false.

Boolean.compare(x,y)

X

Y

Return Value

true

true

0

false

false

0

true

false

> 0

false

true

< 0

Code

class BooleanCompare {
public static void main( String args[] ) {
System.out.println("true, true : " + Boolean.compare(true, true));
System.out.println("false, false : " + Boolean.compare(false, false));
System.out.println("true, false : " + Boolean.compare(true, false));
System.out.println("false, true : " + Boolean.compare(false, true));
}
}

Explanation

In the code above, we use the Boolean.compare method to compare Boolean values and check all the combinations of Boolean values.

Free Resources