File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes unable to understand the output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "unable to understand the output" Watch "unable to understand the output" New topic
Author

unable to understand the output

nishant vats
Greenhorn

Joined: Feb 11, 2005
Posts: 23
int[] a = new int[2];
int n =0;
a[++n]= ++n;


System.out.println("the array contains "+ a[0] +a[1]);

output 0 2

can u explain what is logic behind output and if i change it to
a[n++]=++n;
then output is
output 2 0
Andris Jekabsons
Ranch Hand

Joined: Jan 20, 2004
Posts: 82
In the first example "a[ ++n ]" the increment is performed BEFORE evaluating the value of n.
So, the expressions becomes "a[ 0+1 ] = ++n", that is: "a[ 1 ] = ++n".
n now has value of 1, and it is incremented on the left side of " = ":
"a[ 1 ] = 1+1", that is: "a[ 1 ] = 2"
a[ 0 ] remains with the default value of 0.

In the second example "a[ ++n ]" the increment is performed AFTER evaluating the value of n.
So, the expressions becomes "a[ 0 ] = ++n".
Only then n is assigned the value of 1, and it is incremented on the left side of " = ":
"a[ 0 ] = 1+1", that is: "a[ 0 ] = 2"
a[ 1 ] remains with the default value of 0.
nishant vats
Greenhorn

Joined: Feb 11, 2005
Posts: 23
thanks for reply but i guess in assignment operator right hand evaluation is done before ..in that case ++n is evaluated first.. so can u nw explain the answer
Joe Sondow
Ranch Hand

Joined: Apr 10, 2005
Posts: 195
nish vats, that seems like a reasonable assumption but it turns out to be incorrect. The left-hand operand is evaluated first in order to determine the variable that will receive the newly assigned value. The entire procedure is described in the JLS 15.26.1.


SCJA 1.0 (98%), SCJP 1.4 (98%)
nishant vats
Greenhorn

Joined: Feb 11, 2005
Posts: 23
thanks joe ...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: unable to understand the output