Search code examples
javaoperator-precedence

In Java, which gets executed first, "+" or "++"?


I tried the following code in Java

t1 = 5;
t2 = t1 + (++t1);
System.out.println (t2);

My view is since ++ has a higher precedence than +, the above becomes

t2 = t1 + (++t1);
t2 = t1 + 6;      // t1 becomes 6 here
t2 = 6 + 6;
t2 = 12;

However, I get the answer 11 for t2. Can someone explain?


Solution

  • 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.