Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

float — single-precision floating-point type

float is a Java primitive numeric type based on the 32-bit IEEE 754 binary32 format. It stores approximations of many fractions. Float is its wrapper class, not an alternative spelling of the same type.

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

Syntax

float value = 1.5f;
Float boxed = value;
float unboxed = boxed;

float is a keyword naming the primitive IEEE 754 binary32 floating-point type. It has 24 bits of significand precision, or roughly 6–7 decimal digits. It cannot represent every decimal number exactly; for example, 0.1f is an approximation. Adding a small value to a large one may leave the result unchanged because of rounding.

A floating-point literal with the suffix f or F, such as 1.5f, has type float; without that suffix, such as 1.5, it has type double. Assigning a double value to float requires an explicit cast, such as (float) 1.5, and may lose precision or range.

Float (java.lang.Float) is the wrapper class for a float value. Assigning Float boxed = value performs automatic boxing, while float unboxed = boxed performs unboxing. Unlike float, a Float variable can hold null; unboxing null throws NullPointerException.

float also includes positive and negative zero, infinities, and NaN. Floating-point division by zero does not throw ArithmeticException: 1f / 0f produces positive infinity, while 0f / 0f produces NaN. Test for NaN with Float.isNaN(value), not value == Float.NaN, because an == comparison involving NaN always produces false.

Examples

public class Main {
    public static void main(String[] args) {
        float value = 1.5f;
        Float boxed = value;
        float unboxed = boxed;
        float large = 16_777_216f;

        System.out.println(unboxed);
        System.out.println(large + 1f == large);
        System.out.println(Float.isNaN(0f / 0f));
    }
}

Result

1.5
true
true

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