The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
January 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Forget about C and C++

Posted by Kishori Sharan on January 11, 2001 at 10:59 AM

Hi
First thing I would like to tell you is forget about C and C++. This is what happens in case of Java. When you use post increment operator ++ in Java then it means the value of the variable on which it is used is put in the expression and immediately after that the value of the variable in memory is incremented by one. So when you write
a = 5 ;
b = 10 ;
a = b++ ;
then first of all the value of b is put in the expression
a = 10 and immediately b is incremented to 11, so at this time
value of a is still 5 and the value of b is 11. Now the assignment takes place and the value 10 is assigned to a. Since in expression
a = b++ ;
b++ is a sub expression , so as soon as this b++ sub expression is evaluated the value of b is incremented to 11. Java doen't wait to evaluate the whole expression. It evaluates only the expression where ++ operator is used.
Now take your example
i = 10
i = i++ ;
First value of i is substitued as part of evaluation on i++ and it becomes
i = 10 and then immediately value of i is incremented to 11 im memory and now the assignement i = 10 will take place which will overwrite the value of 11 in memory and make it 10. To prove this point let us take another example
i = 10 ;
i = i++ + i
First thing that happens is i++ is evaluated and its value is put in the expression
i = 10 + i ;
now the value of i is incremented to 11 in memory. Now the right hand operand of + operator is evaluated and the new value 11 is read from memory so the expression becomes
i = 10 + 11 ;
now addtion is performed and value of 21 is assined to i.
To make it more clear try
i = i + i++ ;


Thanx
Kishori



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us