Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • 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
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

why is the below code not printing 2 i agree its a post increment but its being assigned to x???

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


output: 1
 
Ranch Hand
Posts: 544
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
This is because you are assiging x the value of x itself which is 1 i.e before incrementing.
This is post-increment so it is evaluated at last.
Instead if you just write "x++;" then you can get the expected output i.e 2.

There is one very nice explaination abt post/pre-increment on Javaranch.

regds,
Amit
 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I agree with Amit's post
Further adding to Amit's explanation




In case of post increment first the assignment is done and then the increment.....{the incremented value may or may not be assigned}
in this case.
a=a++;
Here first 'a' is assigned with value of a ie 1 and then a+1 is done which is not assigned to any variable.
sequence for a=a++;
1....a=a;
2....a+1;

but in case of pre increment its different
a=++a;
1....a=a+1;
2....a=a;


It is more clear if you see this process with different variable b=a++;
Hope this might help
 
Marshal
Posts: 76486
366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This question arises very frequently. You might find lots more if you search this forum and "Beginning Java".

I tried it once in C and got 1, 1, and 2 with three different compilers. That is permissible in C but not in Java™.
reply
    Bookmark Topic Watch Topic
  • New Topic