Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java

What is the Boolean compare() method in Java?

Salman Yousaf

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 the Serializable and Comparable<Boolean> interfaces.

Syntax


int compare(boolean x, boolean y)

Parameters

  1. boolean x: First argument value of primitive boolean type.
  2. boolean y: Second argument value of primitive boolean type.

Return value

The compare() method returns an integer value:

  • Equal to 0: compare() returns 0 when both x and y are true.
  • Less than 0: compare() returns a negative number when x is false and y is true.
  • Greater than 0: compare() returns a positive number when x is true and y is false.

Code

Below are some examples to illustrate the usage of the compare() method in Java.

  • Case #1: As highlighted, Boolean.compare(x, y) returns 0 because x and y are both true.
  • Case #2: compare() returns -1 because x is false and y is true.
  • Case #3: compare() returns 1 because x is true and y is false.
// Compare() method implementation
// importing base class
import java.lang.Boolean;
class EdPresso {
// main method is starting here
public static void main(String[] args)
{
// declaring and defining
// x, y variables
boolean x = true;
boolean y = true;
// calling compare method
System.out.println(x + " comparing with " + y
+ " = " + Boolean.compare(x, y));
}
}

RELATED TAGS

communitycreator
java

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring