![]() |
VOOZH | about |
The Double.compareTo() method is a built-in method in Java of java.lang package. This method is used to compare two Double 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.
In this article, we are going to learn about the Double.compareTo() method in Java with examples.
public int compareTo(Double anotherDouble)
Parameter:obj: The object that is to be compared to.
Return Values: The function can return three values:
Note: This method only accepts a Double object as an argument. If we pass anything else or no argument at all, it will result in a compile-time error.
Example 1: In this example, we are going to compare two different Double objects.
obj1 is less than obj2
Example 2: In this example, we are going to pass no argument and see what happens.
Output:
error: method compareTo in class Double cannot be applied to given types;
int result = obj1.compareTo();
^
required: Double
found: no arguments
reason: actual and formal argument lists differ in length
Example 3: In this example, we are going to pass a non-Double object.
Output:
error: incompatible types: String cannot be converted to DoubleImportant Points: