• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Increment Operator

 
Alpana Singh
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came across this question.

public class static1{
public static void main (String args[])
{
int i=0;
i=i++;
i=i++;
i=i++;
System.out.println(i);
}
}

And the ouput generated is 0.I can't understand why?
Please help.
 
Tim McGuire
Ranch Hand
Posts: 820
IntelliJ IDE Tomcat Server VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also have a look at these simple one
good one
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Steve,Tim and Raghavan for clearing this.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic