aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes postincrement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "postincrement" Watch "postincrement" New topic
Author

postincrement

Wojtek Klem
Greenhorn

Joined: Jan 16, 2011
Posts: 3
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

Joined: Jan 28, 2008
Posts: 5575

Have a look at this
Darek odarek
Greenhorn

Joined: Jan 16, 2011
Posts: 9
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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: postincrement