Java Integer compareTo() method
The compareTo() method of Integer class compares two Integer objects numerically.
Syntax
public static int compareTo(int anotherInteger)
Parameters
The parameter ‘anotherInteger’ represents the Integer to be compared.
Specified by
This method is specified by compareTo in interface Comparable< Integer >
Return Value
This method returns an integer value.
- It returns zero, if this Integer is equal to the parameter.
- It returns positive one, if this Integer is numerically greater than the argument Integer.
- It returns negative one, if this Integer is numerically smaller than the argument Integer.
Example 1
public class JavaIntegerCompareToExample1 { public static void main(String[] args) { Integer val1 = 500 ; Integer val2 = 127654 ; // It compares two Integer objects numerically int val = val1.compareTo(val2); if(val==0){ System.out.println("Both 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 500
Example 2
import java.util.Scanner; public class JavaIntegerCompareToExample2 { 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 two Integer objects numerically. int val = val1.compareTo(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 : 70 Congratulations! You are an adult. You can vote..
Example 3
import java.util.Scanner; public class JavaIntegerCompareToExample3 { public static void main(String[] args) { Integer val1 = 90 ; Scanner scanner=new Scanner(System.in); System.out.print("Enter you 12 percentage : "); Integer val2 = scanner.nextInt(); // It compares two Integer objects numerically. int val = val1.compareTo(val2); if (val<0){ System.out.println("Congratulations! You 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 you 12 percentage : 98 Congratulations! You percentage is with the first cut off list.