java.lang.Boolean compareTo(Boolean b)
Description
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
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.