Java Reference
In-Depth Information
long orig = 0x7effffff00000000L;
float fval = orig;
long lose = (long) fval;
System.out.println("orig = " + orig);
System.out.println("fval = " + fval);
System.out.println("lose = " + lose);
The first two statements create a long value and assign it to a float
value. To show that this loses precision, we explicitly cast fval to a long
and assign it to another variable (explicit casts are covered next). If you
examine the output, you can see that the float value lost some preci-
sion: The long variable orig that was assigned to the float variable fval
has a different value from the one generated by the explicit cast back
into the long variable lose :
orig = 9151314438521880576
fval = 9.1513144E18
lose = 9151314442816847872
As a convenience, compile-time constants of integer type can be as-
signed to smaller integer types, without a cast, provided the value of
the constant can actually fit in the smaller type and the integer type is
not long . For example, the first two assignments are legal while the last
is not:
short s1 = 27; // implicit int to short
byte b1 = 27; // implicit int to byte
short s3 = 0x1ffff; // INVALID: int value too big for short
Such a conversion, from a larger type to a smaller type, is a narrowing
primitive conversion.
 
Search WWH ::




Custom Search