Next: The character type. Up: Primitive types. Previous: Integer primitive types.


Floating-point primitive types

Textbook: Section 9.3

The types

Java actually has four primitive types for representing integer values.

floatrepresents a 32-bit floating-point value
doublerepresents a 64-bit floating-point value
Both use the IEEE formats, similar to what you would have seen in CS 150.
typemaximumprecision
float 3.40×1038 6 digits
double 1.79×10308 15 digits

There are constants defined in the Float and Double classes that represent extremes for the types.

Generally you should just stick with double, but occasionally you'll need a float. The most frequent reason for this would be a huge array of floating-point numbers, when spending 8 bytes on each number isn't acceptable, and the added precision isn't needed.

Literals

Any numerical representation containing a decimal point (3.14) or an exponent (3e8) is a floating-point literal. By default, it is a double, but you can append a f (or F) to specify it as a float literal.

You can also append a d or f to what would otherwise be an int literal, making it either a double or float literal: 3d would represent the double value 3.0. (But it's better to just put in the decimal point.)

There's no literal for infinity, negative infinity, or NaN (not a number), but the IEE format permits these values. Instead, you can use Java's built-in constants Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY, and the class method Double.NaN, which tells whether a double value represesents NaN.


Next: The character type. Up: Primitive types. Previous: Integer primitive types.