• 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

Need explanation for the code

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Why the output is "value of i: 0"
 
Sheriff
Posts: 14691
16
Eclipse IDE VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check this FAQ.
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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. ]
 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic