What is the Long.compareTo() method in Java?
The compareTo() method of the Long class is used to compare two Long objects in Java.
Syntax
The syntax of the compareTo() method is as follows.
public int compareTo(Long b);
Parameter
The compareTo() method compares the Long object provided as a parameter with the current Long object.
Return value
The compareTo() method returns one of the following:
-
If the current object and passed argument value are numerically equal, then it returns 0.
-
If the current object is numerically greater than the argument, then it returns a positive value.
-
If the current object is numerically less than the argument, then it returns a negative value.
Code
The code below uses the compareTo() method to compare Long objects.
class LongCompareToExample {public static void main( String args[] ) {Long val = 10L;System.out.println("10, 10 : " + val.compareTo(10l));System.out.println("10, 11 : " + val.compareTo(11l));System.out.println("10, 9 : " + val.compareTo(9l));}}
Explanation
In the code above:
-
In line 3, we create a
Longobject with the namevaland value 10. -
In line 4, we call the
compareTo()method on thevalobject with10las the argument. We will get 0 as the return value because both the objects are numerically equal. -
In line 5, we call the
compareTo()method on thevalobject with11las the argument. We will get -1 as the return value because the value ofvalis numerically less than the argument. -
In line 6, we call the
compareTo()method on thevalobject with9las the argument. We will get 1 as the return value because the value ofvalis greater than the argument.