Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Double.max(): the greater of two double values

Double.max(a, b) returns the greater of two double values, with special rules for NaN and signed zero.

Version: Java SE 21

Syntax

public static double max(double a, double b)

// Call with two arguments:
double larger = Double.max(a, b);

Double.max() is a static method on java.lang.Double. Call it as Double.max(a, b): it takes two primitive double arguments and returns a primitive double. You do not need a Double object. The method has been available since Java 8.

The result is the same as for the double overload of Math.max: the greater value is returned, and equal values with no difference in zero sign are returned unchanged. If either argument is NaN (not a number), the result is NaN. If one argument is -0.0 and the other is +0.0, the result is +0.0, even though == treats the two zeros as equal.

Do not confuse the method with Double.MAX_VALUE: that constant is the largest positive finite double, not the result of comparing two arguments.

Examples

public class Main {
    public static void main(String[] args) {
        System.out.println(Double.max(4.5, 7.25));
        System.out.println(Double.max(-0.0, 0.0));
        System.out.println(Double.max(Double.NaN, 7.25));
    }
}

Result

7.25
0.0
NaN

The expected lines are `7.25` for the greater value, `0.0` for positive zero, and `NaN` because one argument is `NaN`.

Related lessons

  • Java · Lesson 65 · Basic · Version: 2

Sources