Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the Integer.compareTo 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.

The compareTo() method of the Integer class compares the current object’s Integer value to another object’s Integer value.

Syntax

public int compareTo(Integer b);

Parameter

  • b: An object of type Integer whose value is compared to the caller object’s Integer value.

Return value

This method returns:

  • 0 if the caller object’s value and the passed argument’s value are the same.

  • A positive value if the caller object’s value is greater than the argument’s value.

  • A negative value if the caller object’s value is less than the argument’s value.

Code

The code below uses the compareTo method to compare the Integer values as follows:

class IntegerCompareToExample {
    public static void main( String args[] ) {
        Integer val1 = 10;

        Integer val2 = 10;
        System.out.println("10, 10 : " + val1.compareTo(val2));

        val2 = 11;
        System.out.println("10, 11 : " + val1.compareTo(val2));

        val2 = 9;
        System.out.println("10, 9 : " + val1.compareTo(val2));
    }
}

Explanation

In the code above:

  • In line 3 we create an Integer object variable with the name val1 and the value 10.

  • In lines 5 and 6 we create another Integer value val2 with the value 10. We call the compareTo method on the val1 object with val2 as the argument. We get 0 as a result because both the values are equal.

  • In lines 8 and 9 we change the value of val2 to 11 and call the compareTo method on the val1 object with val2 as the argument. We get -1 as a result because val1 is less than val2.

  • In lines 11 and 12 we change the value of val2 to 9 and call the compareTo method on the val1 object with val2 as the argument. We get 1 as a result because val1 is greater than val2.

RELATED TAGS

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