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 Long object with the name val and value 10.

  • In line 4, we call the compareTo() method on the val object with 10l as 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 the val object with 11l as the argument. We will get -1 as the return value because the value of val is numerically less than the argument.

  • In line 6, we call the compareTo() method on the val object with 9l as the argument. We will get 1 as the return value because the value of val is greater than the argument.

Free Resources