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.0d is considered to be greater than -0.0d.

  • When comparing this method, Double.NaN is considered to be equal to Double.NaN and greater than all other values (including Double.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 Double object variable with the name val and value 10.55.

  • In line 4, we call the compareTo method on the val object with 10.55d as the argument. We get 0 as a result because both the values are equal.

  • In line 5, we call the compareTo method on the val object with 11.55d as the argument. We get -1 as a result because the value of val is less than the argument.

  • In line 6, we call the compareTo method on the val object with 9.55d as the argument. We get 1 as a result because the value of val is greater than the argument.

  • In line 7, we call the compareTo method on the val object with Double.NaN as the argument. We get -1 as a result because Double.NaN is considered to be equal to Double.NaN and greater than all other values (including Double.POSITIVE_INFINITY).

Free Resources