4

Consider

int b = 2;

int[] a = new int[4];

a[a[b]] = a[b] = b = 2;

for (int i = 0; i <= 3; i++)
{
    System.out.println(a[i]);
}

The output is

2
0
2
0

I was expecting a[0] to be zero.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483

6 Answers6

2

Excerpt from JLS 15.26.1. Simple Assignment Operator =

If the left-hand operand is an array access expression (ยง15.13), possibly enclosed in one or more pairs of parentheses, then:

First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index subexpression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.

This means that a[a[b]] evaluates to a[0] as it's evaluated first. Then we proceed simply as a[0] = a[b] = b = 2, with the assignment taking place from right to left.

See http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.1

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Because a[a[b]] is same as a[0] and you are assigning value 2 for that..

b = 2, a[b] = 0 so a[a[b]] = 2
Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
1

a[a[b]] = a[b]=b=2 , This executes from left hand side

First

a[a[b]] i.e, a[a[2]] -> a[0] //initially the value of a[2] will be 0

now,

a[0]=a[2]=b=2;

so the output is,

2 0 2 0
RKC
  • 1,834
  • 13
  • 13
1

I guess this thread might help you to understand the evaluation order in java: What are the rules for evaluation order in Java?

The most important part of this problem is that the first = is the actual assignment. In java the index is always evaluated befor the asignment, therefor a[a[b]] is the fist one in the evaluation order. And at this point a[b] is 0.

Community
  • 1
  • 1
The End
  • 709
  • 3
  • 18
0

Let's see what a[a[b]] = a[b]=b=2; does in detail:

a[a[b]] : b is 2, a[2] is 0, a[a[2]] is a[0].

so a[a[b]] = a[b]=b=2; is evaluated to a[0] = a[b]=b=2;

that is evaluated to a[0] = a[2] =2;, so a[2] is 2 and a[0] is equal to a[2]

Theolodis
  • 4,977
  • 3
  • 34
  • 53
0

I think you are reading

a[a[b]] = a[b]=b=2;

from right to left and expecting the array and b to be reevaluated at each step, when in fact it seems like a and b are frozen at the time of the assignment. Consider the equivalent code:

1) int b = 2;          

//array initialized to 0
2) int[] a= new int[4]; // 0 0 0 0   

// at this point a[b] is a[2] = 0, therefore  below a[a[b]]=2 is equivalent to  a[0]=2
3) a[a[b]] = 2          // 2 0 0 0    

// the same: a[b] = 2 is equivalent to a[2] = 2  -note that the arrays are zero based
4) a[b]= 2              // 2 0 2 0

5) b=2;
Leo
  • 283
  • 2
  • 4