Java Integer compareTo() method

The compareTo() method is a method of Integer class under java.lang package. This method compares two integer objects numerically. It returns the result of the value 0 if Integer is equal to the argument Integer, a value less than 0 if Integer is less than the argument Integer and a value greater than 0 if Integer is greater than the argument Integer. This method is specified by Comparable<Integer>Interface.

Note: This method cannot be compared two different types of argument, so both the argument and the number should be the same type.

Syntax

Following is the declaration of compare() method:

Parameter:

DataTypeParameterDescriptionRequired/Optional
intanotherIntegerThe Integer value to be compareRequired

Returns:

This method will returns the following values:

Exceptions:

NA

Compatibility Version:

Java 1.2 and above

Example 1

Output:

-1
0
1

Example 2

Output:

x is greater than y

Example 3

Output:

1
0
-1

Example 4

Output:

Enter the integer value to be campare with another Integer: 200
-1
0
1