• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

postincrement

 
Wojtek Klem
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

why the output of this code is 0 ;)

int a = 0;
for (int i = 0; i < 100; i++) {
a = a++;
}

System.out.println("a = " + a);
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look at this
 
Darek odarek
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is simple to explain in bytecode

Java:
     a = a++;

Java bytecode:
     6: istore_3
     7: iload_3
     8: iinc 3, 1
     11: istore_3


assume that a = 0;
7: iload_3 - The value of the local variable at index 3 (a) is pushed onto the operand stack. (value from a (0) --> operand stack)
8: iinc 3, 1 - The local variable at index 3 (a) is incremented by 1 (a=1)
11: istore_3 - The value (0) is popped from the operand stack, and local variable at index 3 is set to value 0 (old value from operand stack (0) --> a)

and now
a == 0

Best regards,
Darek
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic