Home »
Java programming language
Java - Long Class compareTo() Method
Long class compareTo() method: Here, we are going to learn about the compareTo() method of Long class with its syntax and example.
By Preeti Jain Last updated : March 20, 2024
Long class compareTo() method
- compareTo() method is available in java.lang package.
- compareTo() method is used to check equality or inequality for this Long object against the given Long object mathematically or in other words, we can say this method is used to compare two Long objects.
- compareTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- compareTo() method does not throw an exception at the time of comparing Long object.
Syntax
public int compareTo(Long value2);
Parameters
- Long value2 – represents the Long object to compare with.
Return Value
The return type of this method is int, it returns an integer value based on the following cases,
- It returns 0, if value1 is mathematically equal to value2.
- It returns the value < 0, if value1 is mathematically less than value2.
- It returns the value > 0, if value1 is mathematically greater than value2.
Example
// Java program to demonstrate the example
// of compareTo(Long value2) method of Long class
public class CompareToOfLongClass {
public static void main(String[] args) {
// Variables initialization
long l1 = 10;
long l2 = 20;
// Long instance
Long ob1 = new Long(l1);
Long ob2 = new Long(l2);
// It compares two Long objects and placed the result in
// another variable (compare) of integer type
int compare = ob1.compareTo(ob2);
// Display result
System.out.println("ob1.compareTo(ob2): " + compare);
System.out.println();
if (compare == 0)
System.out.println("ob1 is equal to ob2");
else if (compare < 0)
System.out.println("ob1 is less than ob2");
else
System.out.println("ob1 is greater than ob2");
}
}
Output
ob1.compareTo(ob2): -1
ob1 is less than ob2