Java compareTo() method
compareTo() method is used to compare a Number object with the parameters of the method. Can be used to compare Byte, Long, Integer, etc.
This method is used to compare two data types of the same type. Two data of different types cannot be compared using this method.
Syntax
public int compareTo( NumberSubClass referenceName )
Parameters
referenceName -- can be a Byte, Double, Integer, Float, Parameters of type Long or Short.
Return value
If the specified number is equal to the parameter, 0 is returned.
If the specified number is less than the parameter, -1 is returned.
If the specified number is greater than the parameter, return 1.
Example
public class Test{ public static void main(String args[]){ Integer x = 5; System.out.println(x.compareTo(3)); System.out.println(x.compareTo(5)); System.out.println(x.compareTo(8)); }}
Compile the above program and the output result is:
10-1