LAST UPDATED: JANUARY 15, 2021
Java Integer compareTo() Method
Java compareTo()
Method belongs to the Integer
class. This method is similar to the compare()
method of the same class but the only difference is that here the Integer Objects are compared numerically rather than the integer values.
The object1.compareTo(int object2)
method returns the value
-
0; if object1 is equal to object2
-
-1; if object1 is less than object2
-
1; if object1 is greater than object2
Syntax:
public int compareTo(Integer integer2)
Parameter:
Parameter includes the integer object to be compared.
Returns:
0,-1,1 depending upon the value of the argument integer.
Example 1:
import java.lang.Integer;
public class StudyTonight
{
public static void main(String[] args)
{
Integer ob1 = 100;
Integer ob2 = 200;
Integer ob3 = 300;
Integer ob4 = 100;
System.out.println(ob1.compareTo(ob2)); //Output will be less than zero
System.out.println(ob3.compareTo(ob1)); // Output will be greater than zero
System.out.println(ob1.compareTo(ob4)); // Output will be equal to zero
}
}
-1
1
0
Example 2:
Here, an array of Integer
objects is created and every object in the array is compared with the first object of the array.
import java.lang.Integer;
public class StudyTonight
{
public static void main(String[] args)
{
Integer [] ob = {-100,-200,300,-100};
for(int i=0;i<4;i++)
{
System.out.println(ob[0].compareTo(ob[i])); // comparing each object of array with first object
}
}
}
0
1
1
0
Example 3:
Here is a general example where the user can enter the numbers of his choice and get the desired output. The try
and catch
block is used for handling any exception taking place during the execution of the program. (For example, the user enters a String, etc. in place of the integer).
import java.util.Scanner;
import java.lang.Integer;
public class StudyTonight
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter first and second number ");
try
{
Integer n1 = sc.nextInt();
Integer n2 = sc.nextInt();
int r = n1.compareTo(n2);
if(r > 0)
{
System.out.println("first number is greater");
}
else if(r< 0)
{
System.out.println("second number is greater");
}
else
{
System.out.println("both numbers are equal");
}
}
catch(Exception e)
{
System.out.println("Error!!");
}
}
}
Enter first and second number 121 898
second number is greater
***********************************************
Enter first and second number 100 60
first number is greater
***********************************************
Enter first and second number 0x555 0x565
Error!!
Live Example:
Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.