File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Need explanation for the code

siddharth paul

Joined: Apr 30, 2008
Posts: 20

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

Joined: Nov 24, 2005
Posts: 14688

Check this FAQ.

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

Joined: Jan 11, 2010
Posts: 3

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;

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).


[ 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

Joined: Oct 13, 2005
Posts: 45255
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.
I agree. Here's the link:
subject: Need explanation for the code
jQuery in Action, 3rd edition