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

二次信任 提交于 2019-11-27 09:26:22

= is parsed as right-associative, but order of evaluation is left-to-right.

So: The statement is parsed as a[i] = (i = 9). However, the expression i in a[i] is evaluated before the right hand side (i = 9), when i is still 0.

It's the equivalent of something like:

int[] #0 = a;
int #1 = i;
int #2 = 9;
i = #2;
#0[#1] = #2;
icyrock.com

As per the specs:

15.26 Assignment Operators There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a.

So, a[i] = i = 9; is the same as i = 9; a[i] = i;

Edit

Actually, that's not the case. Sample test class:

import java.util.Arrays;

public class Mkt {
  public static void main(String[] args) {
    int[] a = new int[10];
    int i = 5;
    a[i] = i = 9;

    System.out.println(Arrays.toString(a));
  }
}

Sample run:

$ javac Mkt.java && java Mkt
[0, 0, 0, 0, 0, 9, 0, 0, 0, 0]

Please refer to the other answer for more information. Basically:

  • a[i] = i = 9 is the same as a[i] = (i = 9), as = is right-associative
  • However, operand evaluation is left-to-right, as per this:

    15.7. Evaluation Order

    The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

    It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.

I copied the second paragraph which is very instructive here - rarely does it make sense to write confusing code like that.

I also find this worth checking out.

If I remember correctly, = operator is right-associative; so i will be assigned first, then a[i].

The = operator is right-associative(as others have already said). This can be easily proven with this test:

int i = 2;
int j = 3;
int x = i = j;
System.out.println(x); // This prints out 3.

This works with all types, Objects and primitives.

The way I have heard this referred to is "dual assignment", since, using the example above, you are assigning the value of j to both i and x.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!