BalramSharma
BalramSharma

Reputation: 31

Pre/Post Increment operator expression Java

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

Upvotes: 2

Views: 127

Answers (3)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

  • 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

Upvotes: 2

lkatiforis
lkatiforis

Reputation: 6255

From Java docs:

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

Upvotes: 2

user14616876
user14616876

Reputation:

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.

Upvotes: 0

Related Questions