Java Reference
In-Depth Information
The compound operation involves an
int
value that contains too many significant bits
to fit in the 23-bit mantissa of a Java
float
, causing the widening conversion from
int
to
float
to lose precision. The resulting value is frequently unexpected.
Compliant Solution (Compound Addition and Assignment)
For defensive programming purposes, avoid using any of the compound assignment oper-
ators on variables of type
byte
,
short
, or
char
. Also, refrain from using a wider operand
ontheright-handside.Inthiscompliantsolution,alloperandsareoftheJavatype
double
.
double x = 2147483642; // 0x7ffffffa
x += 1.0; // x contains 2147483643.0 (0x7ffffffb.0) as expected
Noncompliant Code Example (Compound Bit Shift and Assignment)
This noncompliant code example uses a compound right-shift operator for shifting the
value of
i
by one bit.
short i = -1;
i >>>= 1;
Unfortunately, the value of
i
remains the same. The value of
i
is first promoted to an
int
. This is a widening primitive conversion, so no data is lost. As a
short
,
-1
is repres-
ented as
0xffff
. The conversion to
int
results in the value
0xffffffff
, which is right-
shifted by 1 bit to yield
0x7fffffff
. To store the value back into the
short
variable
i
,
Java performs an implicit narrowing conversion, discarding the 16 higher-order bits. The
final result is again
0xffff
, or
-1
.
Compliant Solution (Compound Bit Shift and Assignment)
This compliant solution applies the compound assignment operator to an
int
, which
does not require widening and subsequent narrowing. Consequently,
i
gets the value
0x7fffffff
.
int i = -1;
i >>>= 1;