6

Possible Duplicate:
Java - Order of Operations - Using Two Assignment Operators in a Single Line

If we assign a variable a value in a chain like the following,

int x=10, y=15;
int z=x=y;

System.out.println(x+" : "+y+" : "+z);

then the value of all three variables x, y and z becomes 15.


I however don't understand the following phenomenon with an array.

int array[]={10, 20, 30, 40, 50};
int i = 4;

array[i] = i = 0;    
System.out.println(array[0]+" : "+array[1]+" : "+array[2]+" : "+array[3]+" : "+array[4]);

It outputs 10 : 20 : 30 : 40 : 0. It replaces the value of the last element which is array[4] with 0.

Regarding previous assignment statement - int z=x=y;, I expect the value of the first element means array[0] to be replaced with 0. Why is it not the case? It's simple but I can't figure it out. Could you please explain?


By the way, this assignment statement array[i] = i = 0; is dummy and it has no value of its own in this code and should no longer be used but I just wanted to know how thing actually works in this case.

Community
  • 1
  • 1
Tiny
  • 27,221
  • 105
  • 339
  • 599
  • 1
    See http://stackoverflow.com/questions/9440844/java-order-of-operations-using-two-assignment-operators-in-a-single-line – Mikhail Oct 29 '12 at 06:31
  • I think `array[i]` is evaluated as `array[4]` at the compile time itself (May be some optimization done by Compiler). – Shashank Kadne Oct 29 '12 at 06:31

4 Answers4

8

int i = 4; when i equals to 4 the array[i] equals to array[4] so array[i] = i = 0; is equivalent to array[4] = i = 0;. That is way it change the value of index 4 with 0.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
7

The separators [] and () change precedence. Everything within these separators will be computed before Java looks outside them.

array[i] = i = 0;

During compiler phases, the first change to this line will happen as follows:

array[4] = i = 0; // subscript separator is evaluated first.

Now, assignment operation is right-associative, So, i is assigned value 0 and then array[4] is assigned value of i i.e. 0.

Check following links:

Azodious
  • 13,752
  • 1
  • 36
  • 71
3

Let me break it....

Your statement:

int array[]={10, 20, 30, 40, 50};

Implementation:

array[0] => 10

array[1] => 20

array[2] => 30

array[3] => 40

array[4] => 50

Your statement:

int i = 4;

Implementation:

i => 4

Your statement:

array[i] = i = 0;

Implementation:

array[4] = i = 0;

array[4] = 0

Well if you want array[0] => 0, then do this...

int i = 0;

array[i] = i = 0
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
2

because array[i] is evaluated before assignment opeartion

Ravindra Bagale
  • 17,226
  • 9
  • 43
  • 70