What is the Boolean compare() method in Java?
The static compare() method is from class Boolean. We use this method to compare two boolean values and check their equality.
Class Boolean is imported from the
java.lang.Booleanpackage, which impletmets theSerializableandComparable<Boolean>interfaces.
Syntax
int compare(boolean x, boolean y)
Parameters
- boolean
x: First argument value of primitive boolean type. - boolean
y: Second argument value of primitive boolean type.
Return value
The compare() method returns an integer value:
- Equal to 0:
compare()returns0when bothxandyaretrue. - Less than 0:
compare()returns a negative number whenxisfalseandyistrue. - Greater than 0:
compare()returns a positive number whenxistrueandyisfalse.
Code
Below are some examples to illustrate the usage of the compare() method in Java.
- Case #1: As highlighted,
Boolean.compare(x, y)returns0becausexandyare bothtrue. - Case #2:
compare()returns-1becausexisfalseandyistrue. - Case #3:
compare()returns1becausexistrueandyisfalse.
// Compare() method implementation// importing base classimport java.lang.Boolean;class EdPresso {// main method is starting herepublic static void main(String[] args){// declaring and defining// x, y variablesboolean x = true;boolean y = true;// calling compare methodSystem.out.println(x + " comparing with " + y+ " = " + Boolean.compare(x, y));}}