• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need explanation for the code

 
siddharth paul
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why the output is "value of i: 0"
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check this FAQ.
 
david j greenfield
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • 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. ]
 
Charan kumar sarvepalli
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • 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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50171
79
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic