[Unicode]   Common Locale Data Repository : Bug Tracking Home | Site Map | Search

CLDR Ticket #8315(accepted tools)

Opened 3 years ago

Last modified 3 years ago

Java code: Make all implicit narrowing compound assignments explicit

Reported by: markus Owned by: markus
Component: util Data Locale:
Phase: rc Review:
Weeks: 0.4 Data Xpath:


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!


Change History

comment:1 Changed 3 years ago by emmons

  • Owner changed from anybody to markus
  • Status changed from new to assigned
  • Milestone changed from UNSCH to 28

comment:2 Changed 3 years ago by markus

  • Type set to tools
  • Component changed from tools to unknown

comment:3 Changed 3 years ago by srl

  • Status changed from assigned to accepted

comment:4 Changed 3 years ago by emmons

  • Component changed from unknown to util

comment:5 Changed 3 years ago by markus

  • Milestone changed from 28 to 29

comment:6 Changed 3 years ago by emmons

  • Milestone changed from 29 to upcoming

Add a comment

Modify Ticket

as accepted

E-mail address and user name can be saved in the Preferences.

Note: See TracTickets for help on using tickets.