Array assignment inference behaves differently for two code snippets

First snippets of code 2

public static void main(String args[]) throws Exception {  
    int[] a = { 1, 2, 3, 4 };
    int[] b = { 2, 3, 1, 0 };
    int val = (a = b)[3];
    System.out.println( a [val  ] );
}

Secondary Code Snippets 1

public static void main(String args[]) throws Exception {
    int[] a = { 1, 2, 3, 4 };
    int[] b = { 2, 3, 1, 0 };
    int val;
    System.out.println(a[val = ((a = b)[3])]);
}

What's happening?

output1

2nd output

+4
source share
6 answers

The conclusion is reasonable. Let me break down two complex lines into several separate statements. The first fragment:

// This...
int val = (a = b)[3];
// Becomes...
a = b;
int val = a[3]; // 0

So, the print a[val]will print a[0], which is now 2.

The second fragment is more complex. The triple bit is that the "array into which we are indexing" is evaluated before the other side effects. So:

// This...
System.out.println(a[val = ((a = b)[3])]);
// Becomes...
int[] tmp = a; // So tmp is { 1, 2, 3, 4 }
a = b;
val = a[3]; // 0
System.out.println(tmp[val]); // 1

JLS Section 15.10.4 details this. The important parts are here:

:

  • . [...], .
  • . [...]
  • , null [...]
  • . [...]
  • T , .
+2

int val = (a = b)[3]

. (a = b), a , b ( , , , ).

3. "0". 0 . , , "2". , a , b.

:

System.out.println(a[val = ((a = b)[3])]);

, , , ( a).

, val "0", a , b. ( 0) . "1".

+1

Java Language (15.13.1. ) :

: . , . . , .

- : int val = (a = b)[3]; a { 2, 3, 1, 0 }, 0, 2.

a , a { 1, 2, 3, 4 }. 0 1.

+1

:

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

int val = (a = b)[3];
/**
* a=b => a = { 2, 3, 1, 0 };
* val = a[3] = 0;
* a[val] => a[0] =>2;
**/

System.out.println( a [val  ] );  //2

:

int[] a = { 1, 2, 3, 4 };
int[] b = { 2, 3, 1, 0 };
int val;
System.out.println(a[val = ((a = b)[3])]);
/**
* a[val = ((a = b)[3])]    
* => a[val=(b[3])]   val is not used here
* => a[b[3]] => a[0] => 1
**/
+1

:

:

1. int val = (a = b)[3];
2. a [val]

B:

1. a[val = ((a = b)[3])]

A.1: a={2,3,1,0} val=0, a[val]=2

B.1: a={1,2,3,4} val=0, a[val]=1

B (a=b) {2,3,1,0}, (a=b)[3]=0 val=0 a {1,2,3,4} ( ), a[0]=1

0

, b a, val 4- b, 0, 0, 2. .

, , 0, 1. :

int val = b[3];
System.out.println(a[val]);
a =b;
0

All Articles