Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Double.compare(): compare double values

Compare two primitive `double` values by reading the sign of the result. Learn how the method distinguishes signed zeros and places `NaN` last in ascending order.

Version: Java SE 21

Syntax

public static int compare(double d1, double d2)

int order = Double.compare(a, b);

Double.compare() is a static method of java.lang.Double. Call Double.compare(a, b) with two primitive double values to get an int. Unlike the instance method compareTo(Double), it does not need a receiver object; both methods use the same ordering.

Check the sign of the result: a negative value means a comes before b, 0 means they compare equal, and a positive value means a comes after b. Do not assume a nonzero result is exactly -1 or 1.

The method defines a total order. Apart from NaN, values follow the usual numeric order with one difference: -0.0 comes before +0.0, although primitive == treats the zeros as equal. All NaN values compare equal to one another and come after Double.POSITIVE_INFINITY. When either operand is NaN, the primitive operators <, <=, >, >=, and == all return false.

Use this method in a comparator when you want to sort by a double value in ascending order with these rules. It does not test for equality within a tolerance.

Examples

public class Main {
    public static void main(String[] args) {
        double nan = Double.NaN;

        System.out.println(Integer.signum(Double.compare(2.5, 7.0)));
        System.out.println(Double.compare(2.5, 2.5));
        System.out.println(Integer.signum(Double.compare(-0.0, +0.0)));
        System.out.println(-0.0 == +0.0);
        System.out.println(Integer.signum(Double.compare(nan, Double.POSITIVE_INFINITY)));
        System.out.println(Double.compare(nan, nan));
        System.out.println(nan == nan);
    }
}

Result

-1
0
-1
true
1
0
false

`Integer.signum` reduces the result to `-1`, `0`, or `1`. The first two lines compare ordinary numbers, the next two contrast signed-zero ordering with `==`, and the last three show where `NaN` is placed and how it compares with itself.

Related lessons

  • Java · Lesson 48 · Basic · Version: 2
  • Java · Lesson 5 · Intermediate · Version: 2

Sources