Java Reference
In-Depth Information
You might expect the value of
x
to be 123,456 after this statement executes, but it isn't; it's -7,616.
The
int
value
123456
is too big to fit in a
short
. The automatically generated cast silently lops off
the two high-order bytes of the
int
value, which is probably not what you want.
The corresponding simple assignment is illegal because it attempts to assign an
int
value to a
short
variable, which requires an explicit cast:
x = x + i; // Won't compile - "possible loss of precision"
It should be apparent that compound assignment expressions can be dangerous. To avoid unpleasant
surprises,
do not use compound assignment operators on variables of type
byte, short
, or
char
.
When using compound assignment operators on variables of type
int
, ensure that the
expression on the right-hand side is not of type
long
,
float
, or
double
. When using compound
assignment operators on variables of type
float
, ensure that the expression on the right-hand side is
not of type
double
. These rules are sufficient to prevent the compiler from generating dangerous
narrowing casts.
In summary, compound assignment operators silently generate a cast. If the type of the result of the
computation is wider than that of the variable, the generated cast is a dangerous narrowing cast.
Such casts can silently discard precision or magnitude. For language designers, it is probably a
mistake for compound assignment operators to generate invisible casts; compound assignments
where the variable has a narrower type than the result of the computation should probably be
illegal.
< Day Day Up >
Search WWH ::
Custom Search