File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Increment Operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of RabbitMQ in Depth this week in the Open Source forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Increment Operator" Watch "Increment Operator" New topic

Increment Operator

Alpana Singh
Ranch Hand

Joined: Sep 27, 2005
Posts: 36
I came across this question.

public class static1{
public static void main (String args[])
int i=0;

And the ouput generated is 0.I can't understand why?
Please help.
Tim McGuire
Ranch Hand

Joined: Apr 30, 2003
Posts: 820

The ++ is evaluated after the assignment.

so i starts out as zero.
i=i++; // assign the value of i as zero, then increment. The incremented value is not kept!

i is still zero for the next expression:
i=i++; // same as saying i=0

and so on

try it with i = ++i instead to see the difference.
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
Also have a look at these simple one
good one

Thanks & regards, Srini
MCP, SCJP-1.4, NCFM (Financial Markets), Oracle 9i - SQL ( 1Z0-007 ), ITIL Certified
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

The ++ is evaluated after the assignment.
Not quite; the assignment happens *last*. The increment occurs after the expression "i++" is evaluated. That expression ("i++") evaluates to the original value of i, and the result is "remembered". If the result of the expression "i++" is stored back into i, it's as if nothing happened at all. Here's another example:

The right-hand expression is evaluated as follows, starting with the first i++, the second i++, then adding the results of those two expressions, then assigning *that* value to i...

[ September 30, 2005: Message edited by: Steve Morrow ]
Alpana Singh
Ranch Hand

Joined: Sep 27, 2005
Posts: 36
Thanks Steve,Tim and Raghavan for clearing this.
I agree. Here's the link:
subject: Increment Operator