Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 916
vivek Avatar asked Sep 10 '14 09:09

vivek


People also ask

Which method in Java executes first?

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

What is the order of execution in Java?

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.

Which operator will be executed first?

Operators in an expression that have higher precedence are executed before operators with lower precedence. For example, multiplication has a higher precedence than addition.


1 Answers

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.

like image 167
Tim B Avatar answered Sep 16 '22 16:09

Tim B