Friday, 24 August 2007

Evaluation Of Arrays

Continuing reading Java Language Specification slowly navigating to "Arrays Section" found out pretty interesting new stuff.

I was little suprised to see the evaluation of Arrays specified by JLS.

Take a look at this example: Can you predict the output of this program?

public class ArrayEvaluation {

public static void main(String[] args) {
int[] a = { 11, 12, 13, 14 };
int[] b = { 3,0,1,2 };

System.out.println(a[(a=b)[3]]);
System.out.println(a[(a=a)[3]]);

System.out.println(a[(a=b)[3]]);
System.out.println(b[(b=a)[3]]);


}
}


Guessing some answer or closed this blog ???? Well guys with good knowledge can answer this surely.
But as i am not the one with them i need to analyze and know the reason why it prints...etc...

Output:
13
1
1
1

Here is the analysis:

If you carefully read section "15.13.2 Examples: Array Access Evaluation Order" in Java Language Specification here it states.

An array access, the expression to the left of he brackets appears to be fully evaluated before any part of the expression within the brackets is evaluated

In example expression a[(a=b)[3]], the expression a is fully evaluated before the expression (a=b)[3]; this means that the original value of a is fetched and remembered while the expression (a=b)[3] is evaluated.

This array referenced by the original value of a is then subscripted by a value that is element 3 of another array (possibly the same array) that was referenced by b and is now also referenced by a.

Hence the output above.
System.out.println(a[(a=b)[3]]); = 13 because (a=b)[3] evaluates to 2 and a[2]=13
similarly for other statements..

Note: As we all know assigning same object back to ifself donot make any change :-)

Any suggestions encouraged.

No comments: