• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Post Increment

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Code fragment is as below.......
int x =5;
int y = x++;
System.out.println(x);
System.out.println(y);

Now, the output is x = 6, y = 5. I agree with the result. Now, if the variable y is replaced by x, then the code ......

int x =5;
x = x++;
System.out.println(x);

the output to the code gives 5. But i think the value of x should be 6.Why is the output 5. can someone explain the second scenario?

Thankz
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please search this forum, this problem has been discussed recently, and many, many times before that.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,



check this JLS for postIncrements
In this case, (x = x++) x gets increment to 6 but assigns the previous value to the expression. (i.e x = 5). so the output would be 5. Hope it helps.
 
It's a beautiful day in this neighborhood - Fred Rogers. Tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic