Java Integer compareTo() Method

Java Integer compareTo() Method | In this blog we discuss the pre-defined method compareTo() given in the wrapper class. The compareTo() method takes an integer argument to compare, if both are equal then it returns 0 else if the integer is greater than the argument integer then returns a value that is greater than 0 else if the integer is numerically lesser than the argument integer then it returns the value less than 0.

Java Integer compareTo() Method Syntax:-

The syntax for the compareTo() method is as follows:-
public int compareTo(Integer anotherInt)

parameter: anotherInt, the integer values to be compared.
Return type: int.
It returns the following values:-

  • 0 if both the integer values are equal.
  • < 0 if the integer value is less than the argument.
  • > 0 if the integer value is greater than the argument.

Java compareTo() Integers Example

Here, let us see the example for the compareTo() method.
Example-1:
int a1 = 45;
Int a2 = 45;
Compare both: 0

Example-2:
int b1 = 78;
int b2 = 96;
Compare both: -1

Example-3:
int c1 = 99;
int c2 = 23;
Compare both: 1

Java Integer.compareTo() Example

public class Main {
    public static void main(String args[]) {
        Integer var1 = 100;
        Integer var2 = 200;
        System.out.println(var1.compareTo(var2));

        Integer var3 = 300;
        Integer var4 = 300;
        System.out.println(var3.compareTo(var4));

        Integer var5 = 150;
        Integer var6 = 80;
        System.out.println(var5.compareTo(var6));
    }
}

Output:-

-1
0
1

The explanation of the above code is as follows:- The program has returned -1 for the first comparison because the var1 is lesser than var2 that is var1 is 100 and var2 is 200 and the second output is 0 because both the values are equal that is var3 and var4 are 300 and then the last value is 1 as vart is greater than var6, that is var5 is 150 and var6 is 80.

If we change the argument and this integer then we will get the opposite result. The below program demonstrates it:-

public class Main {
    public static void main(String args[]) {
        Integer var1 = 100;
        Integer var2 = 200;
        System.out.println(var2.compareTo(var1));

        Integer var3 = 300;
        Integer var4 = 300;
        System.out.println(var4.compareTo(var3));

        Integer var5 = 150;
        Integer var6 = 80;
        System.out.println(var6.compareTo(var5));
    }
}

Output:-

1
0
-1

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *