Java Reference
In-Depth Information
Variables of type
byte
and
short
do save a little memory, but unless you have a lot of values of these types
to store, that is, values with a very limited range, they won't save enough to be worth worrying about. They
also introduce complications when you use them in calculations, as you will see shortly, so generally you
should not use them unless it is absolutely necessary. Of course, when you are reading data from some ex-
ternal source, a disk file for instance, you need to make the type of variable for each data value correspond
to what was written originally.
FLOATING-POINT DATA TYPES
Numeric values that are not integral are stored as
floating-point
numbers. A floating-point number has
a fixed number of digits of accuracy but a very wide range of values. You get a wide range of values,
even though the number of digits is fixed, because the decimal point can “float.” For example the values
0.000005, 500.0, and 5,000,000,000,000.0 can be written as 5 × 10
-6
, 5 × 10
2
, and 5 × 10
12
respectively
— you have just one significant digit
5,
but you get three different numbers by moving the decimal point
around.
There are two primitive binary floating-point types in Java: type
float
and type double, described in
Table 2-2
.
These give you a choice in the number of digits available to represent your data values, and in the
range of values that can be accommodated.
DESCRIPTION
float
Variables of this type can have values from −3.4E38 (−3.4 × 10
38
) to +3.4E38 (+3.4 × 10
38
) and occupy 4
bytes in memory. Values are represented with approximately 7 decimal digits accuracy. The smallest non-zero
float
value that you can have is approximately 1.4 × 10−
45
.
double
Variables of this type can have values from −1.7E308 (−1.7 × 10
308
) to +1.7E308 (+1.7 × 10
308
) and occupy 8
bytes in memory. Values are represented with approximately 17 decimal digits accuracy. The smallest non-zero
double
value that you can have is approximately 4.9 × 10−
324
.
The number of digits in representing a floating-point value is called its
precision
.
NOTE
All floating-point operations and the definitions for values of type
float
and type
double
conform to the IEEE 754 standard.
As with integer calculations, floating-point calculations in Java produce the same results on any com-
puter.
Floating-Point Literals
Floating-point literals are of type
double
by default, so 1.0 and 345.678 are both of type
double
. When you
want to specify a value of type
float
, you just append an
f
, or an
F
, to the value, so 1.0f and 345.678F are