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.

package com.javatutorialhq.java.examples;

/*
 * This example source code demonstrates the use of 
 * compareTo(Boolean b) method of Boolean class.
 */

public class BooleanCompareToExample {

	public static void main(String[] args) {

		// initialize 3 boolean primitive
			Boolean firstValue = new Boolean(true);
			Boolean secondValue = false;
			Boolean thirdValue = true;

			// compare the first boolean to the second
			int compareOneTwo = firstValue.compareTo(secondValue);

			// compare the first boolean to the third
			int compareOneThree = firstValue.compareTo(thirdValue);

			// display the comparison result of first
			// and second value
			if (compareOneTwo == 0) {
				System.out.println("First and second value are equal");
			}else if(compareOneTwo > 0){
				System.out.println("First value is greater than second value");
			}else{
				System.out.println("First value is less than second value");
			}
			
			// display the comparison result of first
			// and third value
			if (compareOneThree == 0) {
				System.out.println("First and third value are equal");
			}else if(compareOneTwo > 0){
				System.out.println("First value is greater than third value");
			}else{
				System.out.println("First value is less than third value");
			}
		
	}

}

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