The compare() method of Boolean class is used simply to compare two boolean values. Basically, the compare(boolean x, boolean y) returns the int equivalent of comparing the method argument x and y. All the wrapper class has their own implementation of the compare method which gave us a lot of flexibility in comparing two values regardless of what data type is. It might be argued to use our own comparator instead, but designing a good comparator requires a lot of time and diligence but this method is more robust and will not rely on the inherent behaviour of the compare method of the wrapper classes. Both ways has their pros and cons, it’s up to the java programmer to decide which suits him best.

Important Notes:

  • The method  compare(boolean x, boolean y) will yield the same result as  Boolean.valueOf(x).compareTo(Boolean.valueOf(y))

Method Syntax

public static int compare(boolean x, boolean y)

Method Argument

Data Type Parameter Description
boolean x the first boolean to compare
boolean y the second boolean to compare

Method Returns

The compare() method of boolean class returns the value 0 if x == y; a value less than 0 if !x && y; and a value greater than 0 if x && !y


 To differentiate two boolean value, usually our approach is to make use of if else condition, and base on the results of the evaluation we determine the which one of the two values are greater or if there are equal. The compare method were devised as such that we can test the equality or compare two values without going the trouble of formulating the conditional statements. Well we might still be using the if condition however the conditional statements are more consistent now.

Java Boolean compare(boolean x, boolean y) Example

Below is a simple java example on the usage of compare() method of Boolean class.

Basically on the above example, we just ask for two numbers on the console and then we use the scanner object to get the float inputs. We then determine which of the two numbers were higher using the compare method.

Sample Output

Below is the sample output when you run the above example.

java Boolean compare() example output