• 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

Post Increment question from Examulator.

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Inc{
public static void main(String argv[]){
Inc inc = new Inc();
int i =0;
inc.fermin(i);
i = i++;
System.out.println(i);
}
void fermin(int i){
i++;
}
}

The answer is 0, But can anybody explain what's happening behind the scenes. Why it's not 1.
Thanks guys.
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
since java is pass by value, the whole method call is irrelevant. so, this boils down to the

i = i++;

for that, we have a FAQ that i can never find... but basically what happens is this.

the 'i' on the right is evaluated to 0 - we remember this.

We then increment i, since post-fix increments after evaluation. i is now 1.

we then assign the value we evaluated before - which is 0 - to i. i is now 0.
 
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Post Increment
 
What's a year in metric? Do you know this metric stuff tiny ad?
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic