Java Notes: Extended Assignment Operators

It's very common to see statement like the following, where you're adding something to a variable.

sum = sum + currentValue;
i = i + 2;

A shortcut way to write assignments like this is to use the += operator. It's one operator symbol so don't put blanks between the + and =. With this notation it isn't necessary to repeat the variable that is being assigned to.

sum += currentValue;   // Same as "sum = sum + currentValue"
i += 2;                // Same as "i = i + 2"

Commonly used with arithmetic operators

You can use this style with all arithmetic operators (+, -, *, /, and even %).

measurementRange /= 2;         // Divides measurementRange by 2.
accountBalance -= withdrawal;  // Subtracts withdrawal from accountBalance.

Four ways to add one

There are four ways to add one to a variable. Many languages only support the first way. Current compilers translate them into equivalent code, so there's no efficiency difference, unlike early C compilers where ++ was more efficient.

i = i + 1;        // Common in all languages.
i += 1;           // Common when adding values other than one.
i++;              // Most common, but only works for adding one.
++i;              // Least common.

Can be used with most computational operators

This notation can also be used with the bit operators (^, &, |). It can not be used with the logical short-circuit operators && and ||, but you can use the & and | versions. It can only be used with binary (two operand) operators, not unary operators.

Where it makes a difference

For simple variables, which kind of assignment to use is mainly a style or readability difference. However, when assigning to l-values that require computation, there is a real difference, both in performance and possible side-effects.

a[f(x)] = a[f(x)] + 1;   // Calls f(x) twice!
a[f(x)] += 1;            // Calls f(x) only once.