Java Reference
In-Depth Information
Floating-Point Types
Two of the eight primitive data types are used for storing floating-point num-
bers: float and double. The only difference between them is their size, with a
float being 32 bits and a double being twice that size (which explains where the
term double comes from). Floating-point values are stored using the IEEE 754
standard format.
In the previous section, I discussed how integer literals are treated as ints,
except when an L is appended to the number, thereby making it a long. Simi-
larly, floating-point literals are treated as a double value by default. A floating-
point literal is any literal that contains a decimal point.
If you want a floating-point literal to be treated as a float, you need to
append an F to the literal. The following FloatDemo program demonstrates
using the float and double data types. Study the code and see if you can guess
the output. Figure 2.2 shows the actual output of the FloatDemo program.
public class FloatDemo
{
public static void main(String [] args)
{
double pi = 3.14159;
float f = 2.7F;
System.out.println(“pi = “ + pi);
System.out.println(“f = “ + f);
int n = 15, d = 4;
f = n/d;
System.out.println(“15/4 = “ + f);
int radius = 10;
double area = pi * radius * radius;
System.out.println(“area = “ + area);
}
}
In the FloatDemo program, 3.14159 and 2.7F are floating-point literals.
The first one is treated as a double, whereas 2.7 is treated as a float
because it has an F appended. Assigning f to 2.7 without the F generates a
compiler error because 2.7 would be a double, and you cannot assign a
double to a float (unless you use the cast operator).
Search WWH ::




Custom Search