CLDR Ticket #8315(accepted tools)
Java code: Make all implicit narrowing compound assignments explicit
|Reported by:||markus||Owned by:||markus|
A colleague is hunting down the following: "Compound assignments to variables with type byte, char, short, or float hide dangerous narrowing conversions. This change makes implicit narrowing conversions explicit ..."
Use http://errorprone.info/ and check it routinely. (The tool supports ant integration.)
Same as IcuBug:11607
Many programmers expect the compound assignment E1 op= E2 to be equivalent to
E1 = E1 op E2. However, this is not the case: compound assignment operators automatically cast the result of the computation to the type on the left hand side. So E1 op= E2 is actually equivalent to
E1 = (T) (E1 op E2), where T is the type of E1.
If the type of the expression is wider than the type of the variable (i.e. the variable is a byte, char, short, or float), then the compound assignment will perform a narrowing primitive conversion. Attempting to perform the equivalent simple assignment would generate a compilation error, and for good reason: narrowing primitive conversions are bug-prone. Having them happen implicitly as part of compound assignment makes it easy to accidentally discard data from computations.
(This explanation was paraphrased from Puzzle #9 in Java Puzzlers: Traps, Pitfalls, and Corner Cases)
byte b = 0; b = b << 1; // error: possible loss of precision b = (byte) (b << 1); // OK b <<= 1; // compiles without error!
- Owner changed from anybody to markus
- Status changed from new to assigned
- Milestone changed from UNSCH to 28