02 Floating
02 Floating
A floating-point value is a number that can have a fractional part (e.g. 3.14). A floating-point
variable must be declared as either float or double. Seasoned Java programmers use
double unless memory conservation is an issue. The sizes of these data types are shown below.
Java stores floating-point data in binary according to the IEEE 754 specification.
Floating-point literals are typed as a sequence of digits, preceded by an optional + or – sign, with
the fractional part identified by a decimal point. The underscore (_) can be used as a group
separator.
Example
double a = 150.;
double b = +150.;
double c = -.015;
double d = 1_000;
Although it is not required by Java’s grammar, seasoned programmers emphasize the decimal
point by typing a digit on both of its sides.
Example
double a = 150.0;
double b = +150.0;
double c = -0.015;
double d = 1_000.0;
Example
double a = 1_024.0D;
float b = 1_024.0F;
Example
Wrong!
float x = 1_024.0; The 64-bit literal 1_024.0 may not be stored in the
32-bit variable x.
Examples
Exercises
2. Declare d2 a double initialized to negative one million without using scientific notation.