Java long compareTo() with examples
The java.lang.Long.compareTo() is a built-in method in java that compares two Long objects numerically. This method returns 0 if this object is equal to the argument object, it returns less than 0 if this object is numerically less than the argument object and a value greater than 0 if this object is numerically greater than the argument object.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
public int compareTo(Object obj) Parameter: obj - The object which is to be compared to.
Returns: The function returns three values:
- equal to 0: Object is equal to the argument object
- less than 0: Object is less than the argument object
- greater than 0: Object is greater than the argument object
Program 1: The program below demonstrates the working of function.
object1 is less than object2
Program 2: The program below demonstrates the working of function when no argument is passed
prog.java:14: error: method compareTo in class Long cannot be applied to given types; int compareValue = obj1.compareTo(); ^ required: Long found: no arguments reason: actual and formal argument lists differ in length 1 error
Program 3: The program below demonstrates the working of function when anything other than object is passed in an argument
prog.java:14: error: incompatible types: String cannot be converted to Long int compareValue = obj1.compareTo("gfg"); ^ Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error