• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Increment Operator

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 820
IntelliJ IDE VI Editor Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also have a look at these simple one
good one
 
Ranch Hand
Posts: 657
Spring VI Editor Clojure
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Steve,Tim and Raghavan for clearing this.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic