2

In Java

int a=10; a = a + ++a; System.out.println(a); 

it prints 21. I had understood that it would print 22

I had understood that since '++' has higher precedence, so it will be calculated first and it will change a's value as it is pre-increment, so increment to variable 'a' would happen there and then...later it should add with a's latest value

like below:

a = a + 11; // (a is 11 after pre - increment) 

so, now a = 11 + 11 = 22, but program produces o/p = 21.

means it is not picking a's latest value which is 11, and using the old value which was 10

a = 10+ 11 = 21 

.. can someone please clear my doubt?

would appreciate it if the answer contains the concept/reference from any book or java specification

2
  • 3
    You need to understand how you statement is being executed, Its Executed from left to right. So for Instance -> a = 10 + 11 = 21 Commented Dec 5, 2021 at 9:49
  • 2
    @Vivek Swansi is right. When you add a = ++a +a you get 11 +11 = 22 Commented Dec 5, 2021 at 9:52

3 Answers 3

2

From Java docs:

All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

Sign up to request clarification or add additional context in comments.

Comments

2
  • i++ - get and then increment
  • ++i - increment and then get
  • unary operations (++, !) have the highest priority
  • expression is evaluated from Left to Right (thanks to user16320675)
int i = 10; System.out.println(i++); // 10 System.out.println(i); // 11 System.out.println(++i); // 12 System.out.println(i); // 12 

In your example:

int a = 10; a = a + ++a; // -> 10 + (10 + 1), from left to right System.out.println(a); // 21 

Comments

0

Since a =10, a = 10 + 11 = 21.

Why? Because the value of a is 10, Because You Didn't Increment it yet, it stays at 10.

in ++a, now only you incremented it, then becomes 11. now , a = 10 + 11 is 21.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.