wood burning stoves 2.0*
The moose likes Java in General and the fly likes dose increment operator works differently at different places? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "dose increment operator works differently at different places?" Watch "dose increment operator works differently at different places?" New topic
Author

dose increment operator works differently at different places?

Rauhl Roy
Ranch Hand

Joined: Aug 01, 2006
Posts: 401




May i know why Line number 5 and 7 are giving incremented result but not line number 8 and 9.

why the result of increment (@ 8 and 9 lines) is not being directly reflecting on the output.
Ove Lindström
Ranch Hand

Joined: Mar 10, 2008
Posts: 326

It is the way Java reads your code.

Line 4: the variable i, increase it
Line 5: print variable i.
Line 6, increase variable i.
Line 7: print variable i.
Line 8: with i, increase it then print it
Line 9: print variable i, then increase it.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13875
    
  10

The postfix increment operator, where the ++ is after the variable name, will return the old value of the variable. So if i = 5, and you print the value of i++, you will get 5 (and i is incremented to the value 6).

The prefix increment operator, where the ++ is before the variable name, will return the new value of the variable. So if i = 5, and you print the value of ++i, you will get 6 (and i is incremented to the value 6).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10916
    
  12

This is why after running this code:



i will still be 3. the i++ says 'return the old value, but increase it by 1. So we set i to 4 (due to the ++), we return the old value of 3, and then assign 3 to i.

Therefore, never never never write line 2.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36482
    
  16
There is no such thing as "the increment operator". There are two increment operators.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: dose increment operator works differently at different places?
 
Similar Threads
Confused help
Post Increment Operator
Why doesn't autoboxing work here ?
while and post increment
Need Explanation of unpredicted output even if methods are synchronized