Java Integer compare() method
The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to be compared. Return Value This method returns an integer value.
- It returns zero, if both the parameters are equal(x==y).
- It returns positive one, if x is greater than y(x>y).
- It returns negative one, if x if smaller than y(x<y).
public class JavaIntegerCompareExample1 { public static void main(String[] args) { Integer val1 = 500 ; Integer val2 = 127654 ; // It compares the two specified int values int val = Integer.compare(val1,val2); if (val==0){ System.out.println(val1+" and "+val2+" are equal."); } else if (val>0) { System.out.println(val1 + " is greater than " + val2); } else{ System.out.println(val2 + " is greater than " + val1); } } }Output
127654 is greater than 500Example 2
import java.util.Scanner; public class JavaIntegerCompareExample2 { public static void main(String[] args) { Integer val1 = 90 ; Scanner scanner=new Scanner(System.in); System.out.print("Enter your 12 percentage : "); Integer val2 = scanner.nextInt(); // It compares the two specified int values int val = Integer.compare(val1,val2); if (val<0){ System.out.println("Congratulations! Your percentage is with the first cut off list."); } else{ System.out.println("Sorry! Your percentage is not in the range of first cut off list. wait for the second cut off."); } } }Output
Enter your 12 percentage : 90 Sorry! Your percentage is not in the range of first cut off list. wait for the second cut off.Example 3
import java.util.Scanner; public class JavaIntegerCompareExample3 { public static void main(String[] args) { Integer val1 = 18 ; Scanner scanner=new Scanner(System.in); System.out.print("Enter your age : "); Integer val2 = scanner.nextInt(); // It compares the two specified int values int val = Integer.compare(val1,val2); if (val<=0){ System.out.println("Congratulations! You are an adult. You can vote.."); } else{ int year=18-val2; System.out.println("Sorry! You are not an adult. You can vote after "+year+" years."); } } }Output
Enter your age : 16 Sorry! You are not an adult. You can vote after 2 years.