java.lang.Boolean compareTo(Boolean b)

Description

The compareTo() method of Boolean class is used to compare this Boolean object to the boolean method argument. This is a little bit different to the compare method because in compare method we put two boolean together as method argument, while the compareTo() method uses the current Boolean value to compare to the boolean method argument. However the compareTo() method returns the same value as that of the compare method.

Important Notes:

  • specified by compareTo in interface Comparable

Method Syntax

public int compareTo(Boolean b)

Method Argument

Data Type Parameter Description
Boolean b the Boolean instance to be compared

Method Returns

The compareTo() method of boolean class returns zero if this object represents the same boolean value as the argument; a positive value if this object represents true and the argument represents false; and a negative value if this object represents false and the argument represents true.

Discussion

The compareTo method of Boolean class is specified by Comparable interface. This method is simply another way to compare this two boolean value on this case the Boolean object to the Boolean method argument.

Java Boolean compareTo(Boolean b) Example

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

Basically on the above example, we have declared three boolean values. We then compared all three values with each other and printed the result on the console.

Sample Output

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

java Boolean compareTo() example output

References