In Java, which gets executed first, "+" or "++"?
You are nearly correct but you are subtly misunderstanding how the precedence rules work.
Compare these two cases:
int t1 = 5;
int t2 = t1 + (++t1);
System.out.println (t2);
t1 = 5;
t2 = (++t1) + t1;
System.out.println (t2);
The result is:
11
12
The precedence does indeed say to evaluate the ++
before the +
, but that doesn't apply until it reaches that part of the expression.
Your expression is of the form X + Y
Where X
is t1
and Y
is (++t1)
The left branch, i.e. X
, is evaluated first.
Afterwards the right branch, i.e. Y
, is evaluated.
Only when it comes to evaluate Y
the ++
operation is performed.
The precedence rules only say that the ++
is "inside" the Y
expression, they don't say anything about the order of operations.
Your logic is close, but not quite right. The order of evaluation is Left to Right for the + operator. t1 comes before the binary op, LHS and then the increment is on the RHS of that binary op. The LHS is executed first.
t2 = t1 + (++t1);
t2 = 5 + 6; // t1 becomes 6 here as a side effect before being read on the RHS
t2 = 11;
Visualised as a tree you have,
+
/ \
t1 ++t1
Precedence Order
When two operators share an operand the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition.
Associativity
When two operators with the same precedence the expression is evaluated according to its associativity. For example x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with the value 17, since the = operator has right-to-left associativity (and an assignment statement evaluates to the value on the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right associativity.
Another way of thinking of it is to expand the ++ expression:
++t1
is the same as putting t1 = t1 + 1
.
1) t1 = 5;
2) t2 = t1 + (++t1);
3) t2 = t1 + (t1 = t1 + 1),
4) t2 = 5 + (t1 = t1 + 1)
5) t2 = 5 + (t1 = 6)
6) t2 = 5 + 6 = 11
If you were to reverse the order to t2 = (++t1) + t1;
Then the expression would expand to:
1) t2 = (t1 = t1 + 1) + t1
2) t2 = (t1 = 5 + 1) + t1
3) t2 = (t1 = 6) + t1
4) t2 = 6 + 6 = 12
To add a point to Chris K,
The associativity is from left to right
So,
t2 = t1 + (++t1);
t2 = 5 + 6; // first t1 is replaced with 5 and then the next 6
t2 = 11;