What is the Double.compareTo method in Java?
The compareTo method of the Double class is used to compare the current object’s double value to another double value.
Syntax
public int compareTo(Double b);
This method returns:
-
0 if the current object value and passed argument value are the same.
-
A positive value if the current object value is greater than the argument.
-
A negative value if the current object value is less than the argument value.
Points to be noted
-
When comparing this method ,
0.0dis considered to be greater than-0.0d. -
When comparing this method,
Double.NaNis considered to be equal toDouble.NaNand greater than all other values (includingDouble.POSITIVE_INFINITY).
Code
The code below uses the compareTo method to compare the double values.
class DoubleCompareToExample {public static void main( String args[] ) {Double val = 10.55d;System.out.println("10.55, 10.55 : " + val.compareTo(10.55d));System.out.println("10.55, 11.55 : " + val.compareTo(11.55d));System.out.println("10.55, 9.55 : " + val.compareTo(9.55d));System.out.println("10.55, Double.NaN : " + val.compareTo(Double.NaN));}}
Explanation
In the code above:
-
In line 3, we create a
Doubleobject variable with the namevaland value10.55. -
In line 4, we call the
compareTomethod on thevalobject with10.55das the argument. We get0as a result because both the values are equal. -
In line 5, we call the
compareTomethod on thevalobject with11.55das the argument. We get-1as a result because the value ofvalis less than the argument. -
In line 6, we call the
compareTomethod on thevalobject with9.55das the argument. We get1as a result because the value ofvalis greater than the argument. -
In line 7, we call the
compareTomethod on thevalobject withDouble.NaNas the argument. We get-1as a result becauseDouble.NaNis considered to be equal toDouble.NaNand greater than all other values (includingDouble.POSITIVE_INFINITY).