File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Vishal Hegde
Ranch Hand
Posts: 1077
Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


output: 1
 
amit punekar
Ranch Hand
Posts: 544
  • 2
  • Mark post as helpful
  • send pies
  • 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
 
anirudh jagithyala
Ranch Hand
Posts: 41
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
Campbell Ritchie
Sheriff
Pie
Posts: 47293
52
  • 0
  • Mark post as helpful
  • send pies
  • 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™.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic