Friday 24 April 2009

Array Access Evaluation Order in Java

Consider the java program written below and then guess its output.
public class ArrayEvaluationOrder {
public static void main(String[] args) 
{

int[] aryA = { 10, 20, 30, 40, 50, 60 };
int[] aryB = { 1, 2, 3, 4, 5, 6 };

System.out.println(aryA[(aryA=aryB)[4]]); //1
System.out.println(aryA[(aryA=aryA)[4]]); //2
System.out.println(aryA[(aryA=aryB)[3]]); //3
}
}
The output is:
60
6
5

If you are scratching your head, let me be of some assistance and explain the reason behind this.

As per Array Access Evaluation Order in java, in case of an array access, the expression to the left of the brackets is fully evaluated before any part of the expression within the brackets is evaluated.

For example consider the following line of code:
System.out.println(aryA[(aryA=aryB)[4]]); 
The expression aryA is fully evaluated before the expression (aryA=aryB)[4] is evaluated. This means that the original value of aryA is fetched and remembered while the expression (aryA=aryB)[4] i.e. 5 is evaluated.

Since aryA still remembers its original value aryA[5] returns 60. But after the execution of this line, aryA and aryB both would be pointing to array pointed to by aryB.

I would leave figuring out the rest of the output to you.

No comments:

 
Technology