In this Java tutorial, you will learn about Integer.compareTo() method, and how to use this method to compare two Integer objects, with the help of examples.

Integer.compareTo()

Integer.compareTo() compares two Integer objects numerically.

If x and y are two integer objects, and we are comparing x with y.

  • 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 compareTo() method is

Integer.compareTo(Integer anotherInteger)

where

ParameterDescription
anotherIntegerThe Integer object to which this Integer object has to be compared.

Returns

The method returns value of type int.

ADVERTISEMENT

Examples

1. Compare this integer value of 7 to another integer value of 3

In this example, we will create two Integer objects: integer and anotherInteger such that integer is greater than anotherInteger. We will use compareTo() method and compare integer with anotherInteger. Since, integer is greater than anotherInteger, compareTo() returns an int value greater than zero.

Java Program

public class Example {
	public static void main(String[] args){
		Integer integer = 7;
		Integer anotherInteger = 3;
		int result = integer.compareTo(anotherInteger); 
		System.out.println("Result of compareTo("+ integer +", "+ anotherInteger +" )"+ " = "+ result);
	}
}

Output

Result of compareTo(7, 3 ) = 1

2. Compare this integer value of 7 to another integer value of 9

In this example, we will create two Integer objects: integer and anotherInteger such that integer is less than anotherInteger. We will use compareTo() method and compare integer with anotherInteger. Since, integer is less than anotherInteger, compareTo() returns an int value less than zero.

Java Program

public class Example {
	public static void main(String[] args){
		Integer integer = 7;
		Integer anotherInteger = 9;
		int result = integer.compareTo(anotherInteger); 
		System.out.println("Result of compareTo("+ integer +", "+ anotherInteger +" )"+ " = "+ result);
	}
}

Output

Result of compareTo(7, 9 ) = -1

1. Compare this integer value of 7 to another integer value of 7

In this example, we will create two Integer objects: integer and anotherInteger such that integer is equal to anotherInteger in value. We will use compareTo() method and compare integer with anotherInteger. Since, integer is equal to anotherInteger in value, compareTo() returns an int of zero.

Java Program

public class Example {
	public static void main(String[] args){
		Integer integer = 7;
		Integer anotherInteger = 7;
		int result = integer.compareTo(anotherInteger); 
		System.out.println("Result of compareTo("+ integer +", "+ anotherInteger +" )"+ " = "+ result);
	}
}

Output

Result of compareTo(7, 7 ) = 0

Conclusion

In this Java Tutorial, we have learnt the syntax of Integer.compareTo() method, and also how to use this method with the help of Java example programs.