Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The += operator is a compound assignment operator in Java that performs addition (or string concatenation) and assignment in a single operation. It evaluates the right-hand expression, adds its value to the current value of the left-hand variable, and stores the resulting value back into the left-hand variable.
variable += expression;

Compiler Equivalence and Implicit Casting

A critical technical distinction of the += operator is how the Java compiler handles type conversion. The expression E1 += E2 is not strictly equivalent to E1 = E1 + E2. Instead, it is equivalent to E1 = (T) ((E1) + (E2)), where T is the data type of E1. Because of this, the += operator automatically performs an implicit narrowing primitive conversion if the evaluated result is wider than the target variable’s type.
short a = 10;
a += 5; // Compiles successfully. Evaluated as: a = (short) (a + 5);

short b = 10;
b = b + 5; // Compilation error: incompatible types: possible lossy conversion from int to short

Evaluation Order

When using the += operator, the left-hand operand is evaluated exactly once. This distinction is important when the left-hand operand contains expressions with side effects, such as post-increment operators or method calls used for array indexing.
int[] array = {10, 20, 30};
int index = 0;

// 'index++' is evaluated only once. 
// array[0] becomes 15, and 'index' becomes 1.
array[index++] += 5; 

String Concatenation Overload

If the left-hand operand is of type String, the += operator is overloaded to perform string concatenation rather than numeric addition. If the right-hand operand is a primitive or a non-String object, Java automatically converts it to a String (via String.valueOf() or the object’s toString() method) before appending it.
String text = "Count: ";
text += 42; // Evaluates to "Count: 42"

text += true; // Evaluates to "Count: 42true"

Thread Safety

The += operator is not atomic. At the memory level, it executes a conceptual read-modify-write sequence: reading the current value, performing the addition, and writing the new value back. The actual number of bytecode instructions generated by the compiler depends entirely on the context and the variable’s scope. For example, applying += to a local int variable typically generates a single iinc instruction, whereas applying it to an instance field generates multiple instructions (e.g., aload, dup, getfield, iadd, putfield). Because it is a multi-step operation at the memory level, applying += to a shared variable across multiple threads without external synchronization (such as synchronized blocks or using java.util.concurrent.atomic classes) will result in race conditions.
Master Java with Deep Grasping Methodology!Learn More