There are some operators that have side effects.
One of the most common operations in program is increasing a variable's value by 1 or decreasing by 1. Increasing by 1 is usually called incrementing. Decreasing by 1 is called decrementing.
Since we need to both read and write to the box for incrementing and decrementing, the thing we're incrementing/decrementing must be both an lvalue as well as an rvalue. The only expression that is an lvalue (so far) is a variable. Thus, we can only increment and decrement variables.
int i = 0 ; ++ i ; // Preincrment iNotice that every Java statement ends in a semicolon. We've added a semicolon at the end.
The operator ++ goes before the variable when it is preincremening. When you just have ++ i by itself, it increases the value of i by 1. Thus, the value of i was read in (it was 0), then incremented (to 1), and written back to i.
It's basically equivalent to i = i + 1.
However, preincrement gets very weird when you begin to use it in more complicated statements.
For example, look at:
int i = 0, j ; j = ++ i ;The effect of preincrementing is to add 1 to i just before evaluating. The side effect is that i has its value changed. In the example, we have the assignment statement j = ++ i.
Recall that we evaluate the RHS. But before we do that, we increment i to 1. Thus, the RHS evaluates to 1, and that is what is assigned to j. i has also been changed to 1 as a result of evaluating ++ i.
What happens in this piece of code?
int i = 1, j ; j = ++ i + ++ i;This looks more complicated. First, we note that ++ has higher precedence than +. Thus, the following parenthesization occurs internally when Java runs the program: ((++i) + (++i)).
We evaluate one of the ++i. This increments to 2, and we have: (2 + (++i)). Then we evaluate the other ++. At this point i is already 2, so incrementing results in 3. We have: (2 + 3). The evaluating results in 5.
Notice that we deviate from the usual evaluation rules for expressions. In particular, we don't substitute the current values of each variable into the expression. We must, instead, substitute only after the preincrement has been done.
In general, you should avoid writing expressions with more than one preincrement (or predecrement), since many programmers find it hard to read and understand.