The compare() method compares two primitive int values passed as arguments to this method. It compares both the int values numerically.
Syntax of compare() method
public static int compare(int x, int y)
compare() Parameters
x
– First int number to compare.y
– Second int number to compare.
compare() Return Value
- It returns the value 0 if first number is equal to the second number, a value less than 0 if first number < second number, or a value greater than 0 if first number > second number.
Supported java versions: Java 1.7 and onwards.
Example 1
public class JavaExample{ public static void main(String[] args){ int x = 125, y = 250, z = 250; //comparing x and y, x < y so result is -1 System.out.println(Integer.compare(x, y)); //comparing x and z, x < z so result is -1 System.out.println(Integer.compare(x, z)); //comparing y and z, y == z so result is 0 System.out.println(Integer.compare(y, z)); } }
Output:
Example 2
Order of arguments matter in compare() method.
public class JavaExample{ public static void main(String[] args){ int x = 10, y = 20; //First argument is < second argument // so the result is -1 System.out.println(Integer.compare(x, y)); //Arguments in reverse order: Here, first argument is // greater than second argument so the result is 1 System.out.println(Integer.compare(y, x)); } }
Output:
Example 3
Comparing user entered numbers using Scanner class and java.lang.Integer.compare() method.
import java.util.Scanner; public class JavaExample{ public static void main(String[] args){ int x, y; Scanner scan = new Scanner(System.in); System.out.print("Enter first int number: "); x = scan.nextInt(); System.out.print("Enter second int number: "); y = scan.nextInt(); scan.close(); if(Integer.compare(x, y)==0){ System.out.println("Input numbers are equal"); }else if(Integer.compare(x, y) > 0){ System.out.println("First number > second number"); }else{ System.out.println("First number < second number"); } } }
Output: