Java Boolean compareTo() method
The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result of this method.
Syntax
public int compareTo(Boolean b)
Parameters
The parameter ‘b’ represents the Boolean instance which is compared.
Return Value
This method returns an integer value based on the result.
- It returns zero, if the parameter b is equal to Boolean instance.
- It returns positive 1, if object b represents true and the argument represents false.
- It returns a negative 1, if object b represent false and the argument represent true.
Example 1
public class JavaBooleanCompareToMethodExample1 { public static void main(String[] args) { Boolean aBoolean = new Boolean(false); Boolean bBoolean = true; //compare b1 with b2 and return an integer value int b3 = bBoolean.compareTo(aBoolean); System.out.println("compare To will return: "+b3); if(b3==0){ System.out.println("Both values are equal"); } else if(b3>0){ System.out.println("aBoolean value is true"); } else{ System.out.println("bBoolean value is true"); } } }
Output
compare To will return: 1 aBoolean value is true
Example 2
public class JavaBooleanCompareToMethodExample2 { public static void main(String[] args) { Boolean b1=true; System.out.print("Even number between 1-10 : "); for (int i=1;i<=10;i++){ Boolean b2=true; if(i%2==0){ b2=false; } // compare b1 ana b2 and return an integer value int val=b1.compareTo(b2); if (val>0){ System.out.print(i+" "); } } } }
Output
Even number between 1-10 : 2 4 6 8 10
Example 3
public class JavaBooleanCompareToMethodExample3 { public static void main(String[] args) { Boolean b1=true; boolean b2=false; //boolean b2 is an primitive data type its object cannot be used to call Boolean class methods int value =b2.compareTo(b1); System.out.println("Compare To method will return : "+value); } }
Output
Error:(8, 22) java: boolean cannot be dereferenced