The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
September 2000



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.


RE: You made me more curious

Posted by YJ on September 13, 2000 at 5:33 PM

Thanks for your reply. I followed your advice and found a
Java programming forum at Sun site.
Someone posted a similar question similar to mine.
However, the answers didn't satisfy me.
If interested, you can check it out by enering "x=x++;"
when searching in that forum.
Just now I tried to run the following statements in C++
and got the result below.

int a=9;
a = a++;
printf( "a=%d\n", a);
a= ++a;
printf( "a=%d\n", a);


Does it mean that the definition of "++" in Java is
different from that in C?

> Hi
> I was also curious after reading your question to know what exactly was happening inside. I just tried to prove Sun guys correct and am puting forward my logic. It may be I am wrong, but my logic proves what is going on is correct.
> Let us consider the following piece of code.

> ///////////////////
> class Num {
> int i
> }

> Num n1 = new Num ( ) ;
> Num n2 = n1 ;

> n1.i = 10 ;

> n2.i = n1.i-- ;
> System.out.println ( "n1.i = " + n1.i + " : n2.i = " + n2.i ) ;

> Output: n1.i = 10 : n2.i = 10
> ///////////////////////////////
> How the expression n2.i = n1.i-- is executed. Because there are three operations involved in this expression.
> 1. Evaluate the right hand expression and get a value
> 2. Assign the value to n2.i
> 3. Decrement n1.i by 1
> The order of evaluation is the important here. In my opinion the order of evaluation is like this.

> 1. Evaluate the right hand expression and get a value
> 3. Decrement n1.i by 1
> 2. Assign the value to n2.i
> So first of all the right hand expression is evaluated and it results in a value of 10. Second, n1.i is decremented by 1. At this point in time both n1.i and n2.i have value of 9 because both of them point to the same memory location. Third, value of 10 is assigned to n2.i which overwrites the old ( you can say transitional ) value of 9 for both n1.i and n2.i and we get the final value as 10 which gives us an impression that "--" ( decrement operator did nothing ) . The same thing happens when you write a = a-- ;

> This logic explains your question, but makes me more curious to know whether this is the way java was supposed to work or this is just an overlook on the part of java implementors.
> You can send this question to Sun and get the explanation and let us know what is the truth.

> Thanx
> Kishori


Sponsored Links

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