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?
button Java starts execution in the main method as shown in the code below ( public static void main(String[] args) ). The body of the main method is all the code between the first { and the last } .
Order of execution When you have all the three in one class, the static blocks are executed first, followed by constructors and then the instance methods.
Operators in an expression that have higher precedence are executed before operators with lower precedence. For example, multiplication has a higher precedence than addition.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With