The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
November 2000

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:

RE:Incremental Operator query

Posted by Kishori Sharan on November 12, 2000 at 1:31 PM

We had a similar discussion ( a = a++ ) and the message was posted on September 12 at artima.com. I am attaching that message below. The way expression a = a++ ; is evaluated in java is a bit confusing and maybe it is a bug in java. It works as we expect in C++ in java it works differently.

//////////// Message POSTED on SEptember 12////////////////
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






Replies:

Sponsored Links



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