Facebook Page Twitter Page LinkedIn Page
× Java.lang Package Classes


The java.lang.Long.compareTo() method is used to compare two Long objects numerically.

Syntax

public int compareTo(Long anotherLong)

Parameters

anotherLong Specify the Long to be compared.

Return Value

Returns the value 0 if this Long is equal to the argument Long; a value less than 0 if this Long is numerically less than the argument Long; and a value greater than 0 if this Long is numerically greater than the argument Long (signed comparison).

Exception

NA.

Example:

In the below example, the java.lang.Long.compareTo() method is used to compare given Long objects.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //creating Long objects
    Long val1 = new Long("5");
    Long val2 = new Long("5");
    Long val3 = new Long("-5");

    //comparing Long objects 
    System.out.println("comparing val1 with val2: " + val1.compareTo(val2)); 
    System.out.println("comparing val1 with val3: " + val1.compareTo(val3)); 
    System.out.println("comparing val3 with val1: " + val3.compareTo(val1));    
  }
}

The output of the above code will be:

comparing val1 with val2: 0
comparing val1 with val3: 1
comparing val3 with val1: -1

❮ Java.lang - Long