What is the Boolean.compareTo method in Java?

The compareTo method of the boolean class can be used to compare the current object Boolean value to another Boolean value.

Syntax

public int compareTo(Boolean b);

This method returns:

  • 0 if the current object value and passed argument value are the same.

  • A positive value if the current object value is true and the argument is false.

  • A negative value if the current object value is false and the argument is true.

Code

class BooleanCompareToExample {
public static void main( String args[] ) {
Boolean trueVal = new Boolean(true);
Boolean falseVal = new Boolean(false);
System.out.println("true, true : " + trueVal.compareTo(trueVal));
System.out.println("false, false : " + falseVal.compareTo(falseVal) );
System.out.println("true, false : " + trueVal.compareTo(falseVal));
System.out.println("false, true : " + falseVal.compareTo(trueVal));
}
}

Explanation

In the code above:

  • We created two Boolean objects: one represents a true value and the other represents a false value.

  • Then we used the compareTo method to compare the current object Boolean value with another Boolean value. We tried all combinations of comparisons and printed the return value.

Free Resources