File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes why is the below code not printing 2 i agree its a post increment but its being assigned to x??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "why is the below code not printing 2 i agree its a post increment but its being assigned to x???" Watch "why is the below code not printing 2 i agree its a post increment but its being assigned to x???" New topic
Author

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

Vishal Hegde
Ranch Hand

Joined: Aug 01, 2009
Posts: 1056



output: 1


http://www.lifesbizzare.blogspot.com || OCJP:81%
amit punekar
Ranch Hand

Joined: May 14, 2004
Posts: 516
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

Joined: Dec 07, 2010
Posts: 41
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

Joined: Oct 13, 2005
Posts: 40052
    
  28
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
 
subject: why is the below code not printing 2 i agree its a post increment but its being assigned to x???