CodeQL documentation

Implicit narrowing conversion in compound assignment

ID: java/implicit-cast-in-compound-assignment
Kind: problem
Severity: warning
Precision: very-high
   - reliability
   - security
   - external/cwe/cwe-190
   - external/cwe/cwe-192
   - external/cwe/cwe-197
   - external/cwe/cwe-681
Query suites:
   - java-code-scanning.qls
   - java-security-extended.qls
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

Compound assignment statements of the form x += y or x *= y perform an implicit narrowing conversion if the type of x is narrower than the type of y. For example, x += y is equivalent to x = (T)(x + y), where T is the type of x. This can result in information loss and numeric errors such as overflows.


Ensure that the type of the left-hand side of the compound assignment statement is at least as wide as the type of the right-hand side.


If x is of type short and y is of type int, the expression x + y is of type int. However, the expression x += y is equivalent to x = (short) (x + y). The expression x + y is cast to the type of the left-hand side of the assignment: short, possibly leading to information loss.

To avoid implicitly narrowing the type of x + y, change the type of x to int. Then the types of x and x + y are both int and there is no need for an implicit cast.