CKTIS / Java
Addition assignment (+=)
The += operator adds a value to a variable or appends text to a String and stores the result, including an implicit conversion to the variable's type.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
variable += expression;variable += expression combines + with assignment. For numbers it adds; for a String variable it appends the right operand's string representation.
E1 += E2 corresponds to E1 = (T) ((E1) + (E2)), where T is the type of E1, except that E1 is evaluated only once. Its previous value is saved before evaluating E2.
Implicit narrowing can lose information: in the example, 12.5 becomes the short value 12. Writing total = total + 2.5 would require an explicit cast. Narrowing conversions can also change the result's sign.
Examples
public class Main {
public static void main(String[] args) {
short total = 10;
total += 2.5;
String label = "total=";
label += total;
System.out.println(label);
}
}Result
total=12
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.