Integer compare() method – Java – Explained with examples


Syntax –
Integer.compare(int a, int b)

Integer compare() method

The compare() method of the Integer class of the java.lang package compares two integer values (a, b) given as parameters and returns 

  • zero(0) if (a==b)
  • a value less than zero (or -1) if (a < b), and 
  • a value larger than zero (or 1) if (a > b).

From Java version 11, you may or may not include the java.lang.Integer class for using the Integer compare() method of Java. Importing isn’t mandatory.

The Integer compare() method of Java accepts two integer values as input parameters. These two input parameters are required. It then compares those two parameters and gives us the result.

Integer.compare(int a, int b)

NOTE: Input parameters for the Integer compare() method cannot be float or long. It has to be of int type.

Example 1:

Here is a simple example of Java Code showing the usage of the Integer compare() method –

package test1;

public class rough {

	public static void main(String[] args) {
		int a = 13;
        int b = 31;
        // Since a(13) is less than b(31), the output will be -1, which is less than 0
        System.out.println(Integer.compare(a, b));
  
        a = 20;
        b = 20;
        // Since a(20) is equal to b(20), the output will be 0
        System.out.println(Integer.compare(a, b));
  
        a = 31;
        b = 13;
     // Since a(31) is greater than b(13), the output will be 1, which is greater than 0
        System.out.println(Integer.compare(a, b));

	}

}

Output:

-1
0
1

Example 2:

Let’s look at another example where we will use the Integer compare() method inside a loop for a better understanding –

package test1;

public class rough {

	public static void main(String[] args) {
        int a = 3;
        for(int i=1;i<5;i++) {
        	int result = Integer.compare(i, a);
        	
        	if(result < 0) {
        		System.out.println(i + " is smaller than " + a);
        	}else if(result == 0) {
        		System.out.println(i + " is same as " + a);
        	}else {
        		System.out.println(i + " is greater than " + a);
        	}
        }
	}
}

Output:

1 is smaller than 3
2 is smaller than 3
3 is same as 3
4 is greater than 3

From the above example, we can see that we can compare two integer values using the Integer compare() method and store the result in an int variable. Using the result variable, we can take decisions further in our code.

I hope you found this article helpful.

Integer compare() method – Java – Explained with examples - FI

You may like to Explore-

Convert Char to String in Java

Random Number Java – using Math.random()

Modulus Operator (Modulo or Remainder) in Java

Cheers!

Happy Coding.

About the Author

This article was authored by Rawnak.