JDK-8286378 : Address possibly lossy conversions in java.base
  • Type: Sub-task
  • Component: core-libs
  • Priority: P4
  • Status: Resolved
  • Resolution: Fixed
  • Submitted: 2022-05-09
  • Updated: 2022-05-13
  • Resolved: 2022-05-12
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 19
19 masterFixed
Related Reports
Relates :  
Relates :  
Description
Existing code within java.base uses implicit casts for a variety of compound assignments.
8244681: proposes to add compiler warnings for possible lossy conversions

The warnings should be addressed to clear up the warnings by adding explicit casts to replace the implicit casts.
In most cases, the cast matches the type of the right-hand side to type of the compound assignment.
Since these casts are truncating the value, there might be a different refactoring that avoids the cast.

From the CSR:

"If the type of the right-hand operand of a compound assignment is not assignment compatible with the type of the variable, a cast is implied and possible lossy conversion may silently occur. While similar situations are resolved as compilation errors for primitive assignments, there are no similar rules defined for compound assignments."
Comments
Changeset: 17c52789 Author: Roger Riggs <rriggs@openjdk.org> Date: 2022-05-12 16:50:36 +0000 URL: https://git.openjdk.java.net/jdk/commit/17c52789b79a4ccd65308f90c4e02c1732b206be
12-05-2022

A pull request was submitted for review. URL: https://git.openjdk.java.net/jdk/pull/8642 Date: 2022-05-10 21:32:10 +0000
10-05-2022

The new methods in PR#8548 would provide checked conversions. Math.toIntExact, toShortExact, toByteExact, toUnsignedRangeShort, toUnsignedRangeByte, toUnsignedRangeInt, ...
10-05-2022

This issue would probably need to split to smaller chunks.
10-05-2022

Thanks for the wording correction. Unfortunately I'm not aware of a core library methods to recommend.
10-05-2022

A note on wording: the warning message may be more helpful to users if the exact situation is more explicitly detailed, such as "implicit cast from $TYPE_1 to $TYPE_2 in compound assignment is possibly lossy.... Are there core library methods that can be recommended instead?
09-05-2022