Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array expressions in Java

Tags:

java

Consider the following expressions in Java.

int[] x={1, 2, 3, 4};
int[] y={5, 6, 7, 0};

x=y;
System.out.println(x[0]);

Would display 5 on the console because x is made to point to y through the expression x=y and x[0] would obviously be evaluated to 5 which is actually the value of y[0].

When I replace the above two statements with the following statement combining both of them into a single statement,

System.out.println(x[(x=y)[3]]);

it displays 1 which is the value of x[0] even though it seems to be equivalent to those above two statements. How?

like image 263
Lion Avatar asked Dec 28 '22 08:12

Lion


1 Answers

the third index in the array y points to is 0, so 1 is the correct output.

So you have

x[(x=y)[3]]

which is x[y[3]], but y[3] is 0, because arrays are 0-indexed, and x[0] is 1.

like image 54
hvgotcodes Avatar answered Dec 29 '22 22:12

hvgotcodes