Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

double — double-precision floating-point numbers

double is Java's primitive 64-bit IEEE 754 binary64 floating-point type. Learn its precision limits, how it differs from Double, and the rules for comparison, maximum selection, and hashing.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

double value = 1.5;
Double boxed = value;
double unboxed = boxed;
int order = Double.compare(value, 2.0);
double maximum = Double.max(value, 2.0);
int hash = Double.hashCode(value);

double is the keyword for the primitive IEEE 754 binary64 type: 64 bits with 53 bits of significand precision for normal numbers. It includes finite numbers, +0.0, -0.0, infinities, and NaN. Many decimal fractions have no exact binary representation: 0.1 + 0.2 produces 0.30000000000000004. Do not assume decimal exactness.

Double is the object wrapper class for double. Boxing converts a primitive value to its wrapper, and unboxing performs the reverse conversion. A Double variable can hold null; unboxing that value throws NullPointerException. A primitive double cannot hold null.

Double.compare(a, b) returns a negative integer, zero, or a positive integer according to the arguments' order. It orders -0.0 before +0.0 and treats all NaN values as equal and greater than positive infinity. In contrast, primitive == considers the two zeros equal but does not consider NaN equal even to itself.

Double.max(a, b) behaves like Math.max: it returns the greater value, returns NaN if either argument is NaN, and returns +0.0 for opposite-signed zeros. Double.hashCode(value) returns an int hash compatible with the instance method Double.hashCode(): all NaN representations share a hash, while the two zeros have different hashes. A hash is not a unique identifier.

Examples

public class DoubleDemo {
    public static void main(String[] args) {
        double sum = 0.1 + 0.2;
        Double boxed = sum;
        System.out.println(boxed);
        System.out.println(-0.0 == 0.0);
        System.out.println(Double.compare(-0.0, 0.0) < 0);
        System.out.println(Double.compare(Double.NaN, Double.NaN) == 0);
        System.out.println(Double.max(-0.0, 0.0));
        System.out.println(Double.max(1.0, Double.NaN));
        System.out.println(Double.hashCode(0.0));
        System.out.println(Double.hashCode(-0.0));
    }
}

Result

0.30000000000000004
true
true
true
0.0
NaN
0
-2147483648

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources