liveBook · Manning

Augmented assignment

As explained in 100 Java Mistakes and How to Avoid Them

Augmented assignment is syntax that combines an operation with assignment to update a variable or object using its current value.

Augmented assignment updates a variable with its current value through an operation, as in `x *= 2`. It is not always equivalent to `x = x * 2`: Java treats it as `x = (type_of_x)(x * 2)`, allowing implicit narrowing conversion. The target variable’s type can therefore silently change or discard the computed result. section 4.9

A byte update that changes nothing

For a negative byte, `b += 256` first widens `b` to `int`, adds 256, then narrows the result back to the byte range −128..127. The original value is restored instead of becoming an unsigned value such as 255. Declaring the variable as `int`, or converting explicitly with `Byte.toUnsignedInt`, preserves the intended positive value. section 4.9

Conversion can produce surprising characters

With `char c = 'a'; c *= 1.2;`, the character is widened to 97.0, multiplied to 116.4, and narrowed back to `char`, producing `t`. Similar loss can occur with `byte b = -1; b >>>= 1;`: widening and shifting are followed by narrowing, restoring −1.

Avoid augmented-assignment mistakes by applying these checks:

  • Inspect the target variable type and ask whether narrowing conversion can occur. section 4.9
  • Prefer `int` or `long` over `byte` and `short` when practical; their narrower ranges can cause conversion and overflow problems. section 4.16 section 4.9
  • Remember that boolean compound assignments such as `result &= check1()` never short-circuit; write the full `result = result && check1()` form when later checks should be skipped. section 2.7
  • Use static analysis as a clue, not proof: IntelliJ can report updates that do nothing, but complex cases or changed results may remain silent. section 4.9

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains widening, operation, narrowing, and discarded bits, then stops short of broader numeric-algorithm treatment.
Examples
Uses character multiplication, negative-byte conversion, unsigned shifting, and boolean accumulation as focused failure cases.
What you can do after
Diagnose ineffective updates by tracing operand widening, arithmetic, narrowing, discarded bits, and boolean evaluation.
How it connects
Connects augmented assignment with implicit narrowing conversion, numeric overflow, byte types, unsigned shifts, and static analysis.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.