What is the Long.compare method in Java?

compare() is a static method of the Long class which is used to compare two long values.

Syntax

public static int compare(long x, long y);

Parameters

The function takes in two long values as parameters.

Return value

This method returns:

  • 0 if both the values are the same.

  • A value less than zero, if x is less than y.

  • A value greater than zero, if the x is greater than y.

Long.compare(x,y)

Case

Retturn Value

x == y

0

x < y

< 0

x > y

> 0

Code

The example below uses the Long.compare() method.

class LongCompare {
public static void main( String args[] ) {
long ten = 10l;
long twenty = 20l;
System.out.println("ten, ten : " + Long.compare(ten, ten));
System.out.println("twenty, twenty : " + Long.compare(twenty, twenty));
System.out.println("ten, twenty : " + Long.compare(ten, twenty));
System.out.println("twenty, ten : " + Long.compare(twenty, ten));
}
}

Explanation

In the code above:

  • We created two long variables:
ten = 10l;
twenty = 20l;
  • We used the compare() method of the Long class to compare the long values. First, we compared the same values:
compare(ten,ten);
compare(twenty, twenty);

  • The compare() method returns 0 because both the compared values are the same.

  • Then, we compared ten with twenty:

compare(ten, twenty);
  • The compare() method returns a value < 0 because the first value is less than the second value.

  • Then, we compared twenty with ten:

compare(twenty, ten);
  • The compare() method returns a value > 0 because the first value is greater than the second value.

Free Resources