aspose file tools*
The moose likes Beginning Java and the fly likes Need explanation for the code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Need explanation for the code" Watch "Need explanation for the code" New topic
Author

Need explanation for the code

siddharth paul
Greenhorn

Joined: Apr 30, 2008
Posts: 20

Why the output is "value of i: 0"
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

Check this FAQ.


[My Blog]
All roads lead to JavaRanch
david j greenfield
Greenhorn

Joined: Jan 11, 2010
Posts: 3
Hey,

It seems you are trying to get the int i to increment, The issue you are running into is your are using a postfix operator in an expression.
When you use a postfix operator in an expression such as ( i = i++;). The returned value is the value prior to the postfix operation.

The post and prefix operators i++, ++i, essentially translate to i = i +1;



run:
value of i:3

Hope this helps, if not clear please let me know.


(Sorry about the formatting on the code posting, for some reason the code formatting tag isnt working at the moment).

~djg

[ UD: The "Disable BB Code in this message" box was checked. ]
Charan kumar sarvepalli
Ranch Hand

Joined: Dec 14, 2008
Posts: 40
Prefix ++i and Postfix i++

Prefix increments the value and assigns immediately.
Postfix increments the value and incremented value effects for the next occurrence of the variable.

Prefix value change effects :

System.out.println(++i);//value is 1.
System.out.println(++i);//value is 2.
System.out.println(++i);//value is 3.

Postfix value change effects:

System.out.println(i++);//value is 0.
System.out.println(i++);//value is 1.
System.out.println(i++);//value is 2. In the next occurrence it value has effected to 3.
System.out.println(i);//value is 3.

-- Charan
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39828
    
  28
Please always tell us what the thread is about.

And please search this forum; that sort of question comes up about 4-6 times a year. For example here, here and here.
 
 
subject: Need explanation for the code