3
int a[]={1, 2, 3, 4, 5};
int b[]={4, 3, 2, 1, 0};

a=b;

System.out.println("a[0] = "+a[0]);

This displays a[0] = 4 as obvious because a is assigned a reference to b.


If it is modified as follows

int a[]={1, 2, 3, 4, 5};
int b[]={4, 3, 2, 1, 0};        

System.out.println("a[(a=b)[0]] = "+a[(a=b)[0]]);  //<-------

then, it displays a[(a=b)[0]] = 5.


Why doesn't this expression - a[(a=b)[0]] yield 4, the 0th element of b even though it appears to be the same as the previous case?

1
  • 1
    Array index has the highest priority. Commented Oct 13, 2013 at 17:24

1 Answer 1

7

The second expression features an assignment expression inside an array indexer expression. The expression evaluates as follows:

  • The target of the indexer expression is selected. That's the original array a
  • The index expression is evaluated by first assigning b to a, and then taking the element of b at index zero
  • The index of the outer indexer is evaluated as b[0]
  • The index is applied to a, returning 5
  • The assignment of b to a takes effect. Subsequent accesses to a[i] will reference b, not the original a.

Essentially, your single-line expression is equivalent to this two-line snippet:

System.out.println("a[(a=b)[0]] = "+a[b[0]]); // Array reference completes first
a=b;                                       // Array assignment is completed last
Sign up to request clarification or add additional context in comments.

3 Comments

so in the end its nothing but a[4]..:)
@dasblinkenlight, but why assignment of b to a takes effect only at the end of the process?
@AlexR It does not matter when the assignment actually happens in order to decide what's the outcome of the expression a[something] is going to be. The only thing that matters is what object is picked as the first operand of the [] expression. In this example, the object is the old a, because the assignment is to the right of the operand, so the assignment's effect is not visible at that point of the expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.