Java Reference
In-Depth Information
Storing a Larger Number in a Smaller Number
Problem
You have a number of a larger type and you want to store it in a variable of a smaller type.
Solution
Cast the number to the smaller type. (A
cast
is a type listed in parentheses before a value that
causes the value to be treated as though it were of the listed type.)
For example, to cast a
long
to an
int
, you need a cast. To cast a
double
to a
float
, you also
need a cast.
Discussion
This causes newcomers some grief because the default type for a number with a decimal
point is
double
, not
float
. So code like:
float f = 3.0;
won't even compile! It's as if you had written:
double tmp = 3.0;
float f = tmp;
You can fix it in one of several ways:
▪ By making the 3.0 a
float
(probably the best solution)
▪ By making
f
a
double
▪ By putting in a cast
▪ By assigning an integer value of 3, which will get “promoted” (e.g.,
float f = 3
)
float f = 3.0f; // or just 3f
double f = 3.0;