• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

postincrement

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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);
 
Ranch Hand
Posts: 5575
Eclipse IDE Windows XP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have a look at this
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Whose rules are you playing by? This tiny ad doesn't respect those rules:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic