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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)