In this Java tutorial, you will learn about Integer.compare()
method, and how to use this method to compare two integer values, with the help of examples.
Integer.compare()
Integer.compare() compares two int values numerically and returns an integer value.
- If x>y then the method returns an int value greater than zero.
- If x=y then the method returns zero.
- If x<y then the method returns an int value less than zero.
Syntax
The syntax of compare() method with two integers as parameters is
Integer.compare(int x, int y)
where
Parameter | Description |
---|---|
x | The first integer value to compare. |
y | The second integer value to compare. |
Returns
The method returns value of type int.
Examples
1. compare(x, y) where x>y
In this example, we will take int values for x and y such that x is greater than y. When we compare x and y using Integer.compare(x, y) method, we should get a return value greater than zero, since x is greater than y.
Java Program
public class Example{
public static void main(String[] args){
int x = 7;
int y = 3;
int result = Integer.compare(x, y);
System.out.println("Result of compare("+ x +", "+ y +" )"+ " = "+ result);
}
}
Output
Result of compare(7, 3 ) = 1
2. compare(x, y) where x<y
In this example, we will take int values for x and y such that x is less than y. When we compare x and y using Integer.compare(x, y) method, we should get a return value less than zero, since x is less than y.
Java Program
public class Example{
public static void main(String[] args){
int x = 7;
int y = 9;
int result = Integer.compare(x, y);
System.out.println("Result of compare("+ x +", "+ y +" )"+ " = "+ result);
}
}
Output
Result of compare(7, 9 ) = -1
3. compare(x, y) where x=y
In this example, we will take int values for x and y such that x and y are equal. When we compare x and y using Integer.compare(x, y) method, we should get a return value of 0, since x and y have same integer value.
Java Program
public class Example{
public static void main(String[] args){
int x = 7;
int y = 7;
int result = Integer.compare(x, y);
System.out.println("Result of compare("+ x +", "+ y +" )"+ " = "+ result);
}
}
Output
Result of compare(7, 7 ) = 0
Conclusion
In this Java Tutorial, we have learnt the syntax of Java Integer.compare() method, and also how to use this method with the help of Java example programs.