2

Suppose i have initialised two variables like this

int a=0;
int b=0;

Now if i assign b a value like this

b=a++ + ++a + ++a;

Now a=3 and b=5 Shouldnt it have been b=2 ? Why is b assigned value 5 ?

thkala
  • 84,049
  • 23
  • 157
  • 201
GoodSp33d
  • 6,252
  • 4
  • 35
  • 67
  • It will be ecaluated like b = 0 + 2 + 3 and at the end b will be 5 and a will be 3. – jaxb Jul 26 '10 at 07:05
  • possible duplicate of [explain working of post and pre increment operator in Java](http://stackoverflow.com/questions/2371118/explain-working-of-post-and-pre-increment-operator-in-java) – Pascal Thivent Jul 26 '10 at 07:28
  • Related [explain-working-of-post-and-pre-increment-operator-in-java](http://stackoverflow.com/questions/2371118/explain-working-of-post-and-pre-increment-operator-in-java). – Zaki Jul 26 '10 at 07:14

3 Answers3

0

lets see:

  • a++ = 0, afterwards increased to 1.

  • ++a = (the one from the a++ plus one preincreased) 2

  • ++a = (the two from the ++a above plus one preincreased) 3

in total: 0 + 2 + 3 = 5

This also explains why a is three. In the last step a is increased to three.

StampedeXV
  • 2,715
  • 2
  • 24
  • 40
0

it works like this

b = a++ + ++a + ++a

b = 0 + 2(1+1) + 3(2+1)

b = 5.

and a = 3

In a++ which uses post increment operator, the the current value of the variable is used first and then gets incremented.

but in ++a which uses pre increment operator, the increment happens first and then gets used. so the behavior is as expected.

GuruKulki
  • 25,776
  • 50
  • 140
  • 201
0

Let's inspect it with my favorite tool: javap...

The bytecode emitted by Suns javac for

int a = 0;
int b = 0;
b = a++ + ++a + ++a;

looks as follows:

                                             a  b   Stack:
 0: iconst_0      // push 0                  0  0   0
 1: istore_1      // store in a              0  0   empty
 2: iconst_0      // push 0                  0  0   0
 3: istore_2      // store in b              0  0   empty
 4: iload_1       // push value of a         0  0   0
 5: iinc    1, 1  // inc a with 1            1  0   0
 8: iinc    1, 1  // inc a with 1 again      2  0   0
11: iload_1       // push value of a again   2  0   0,2
12: iadd          // add top two elements    2  0   2
13: iinc    1, 1  // inc a with 1            3  0   2  
16: iload_1       // push a again            3  0   2,3
17: iadd          // add top two elements    3  0   5
18: istore_2      // store in b              3  5   empty
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • i missed out on using javap , i was trying using jdb it always incremented in steps of 1 instruction so couldnt get to know what was actually happening – GoodSp33d Jul 26 '10 at 09:08