Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

integer
compare
java
communitycreator

What is the Integer.compare method in Java?

Programming Bytes

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.

compare is the static method of the Integer class and is used to compare two int values.

Syntax

public static int compare(int x, int y);

Return value

This method returns:

  • 0 if both values are the same.

  • A value less than zero , if the x < y.

  • A value greater than zero, if the x > y.

Integer.compare(x,y)

Case

Return value

x == y

0

x < y

< 0

x > y

> 0

Code

class IntegerCompare {
public static void main( String args[] ) {
int ten = 10;
int twenty = 20;
System.out.println("ten, ten : " + Integer.compare(ten, ten));
System.out.println("twenty, twenty : " + Integer.compare(twenty, twenty));
System.out.println("ten, twenty : " + Integer.compare(ten, twenty));
System.out.println("twenty, ten : " + Integer.compare(twenty, ten));
}
}

Explanation

In the code above:

  • We created two int variables:
ten = 10;
twenty = 20;
  • We used the compare method of the Integer class to compare the int values. First, we compared the same values:
compare(ten, ten);
compare(twenty, twenty);

The compare method returns 0 because both the compared values are the same.

  • Then, we compare ten with twenty:
compare(ten, twenty);

The compare method returns the value -1 because the first value is less than the second value.

  • Then, we compare twenty with ten:
compare(twenty, ten);

The compare method returns the value > 0 because the first value is greater than the second value.

RELATED TAGS

integer
compare
java
communitycreator

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