What is the Boolean compare() method in Java?

The static compare() method is from class Boolean. We use this method to compare two boolean values and check their equality.

Class Boolean is imported from the java.lang.Boolean package, which impletmets the Serializable and Comparable<Boolean> interfaces.

Syntax


int compare(boolean x, boolean y)

Parameters

  1. boolean x: First argument value of primitive boolean type.
  2. boolean y: Second argument value of primitive boolean type.

Return value

The compare() method returns an integer value:

  • Equal to 0: compare() returns 0 when both x and y are true.
  • Less than 0: compare() returns a negative number when x is false and y is true.
  • Greater than 0: compare() returns a positive number when x is true and y is false.

Code

Below are some examples to illustrate the usage of the compare() method in Java.

  • Case #1: As highlighted, Boolean.compare(x, y) returns 0 because x and y are both true.
  • Case #2: compare() returns -1 because x is false and y is true.
  • Case #3: compare() returns 1 because x is true and y is false.
// Compare() method implementation
// importing base class
import java.lang.Boolean;
class EdPresso {
// main method is starting here
public static void main(String[] args)
{
// declaring and defining
// x, y variables
boolean x = true;
boolean y = true;
// calling compare method
System.out.println(x + " comparing with " + y
+ " = " + Boolean.compare(x, y));
}
}

Free Resources