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.Boolean
package, which impletmets theSerializable
andComparable<Boolean>
interfaces.
int compare(boolean x, boolean y)
x
: First argument value of primitive boolean type.y
: Second argument value of primitive boolean type.The compare()
method returns an integer value:
compare()
returns 0
when both x
and y
are true
.compare()
returns a negative number when x
is false
and y
is true
.compare()
returns a positive number when x
is true
and y
is false
.Below are some examples to illustrate the usage of the compare()
method in Java.
Boolean.compare(x, y)
returns 0
because x
and y
are both true
.compare()
returns -1
because x
is false
and y
is true
.compare()
returns 1
because x
is true
and y
is false
.// 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));}}