Array chain assignment in Java

Consider the following code snippet in Java. I know that the statement temp[index] = index = 0;in the following code fragment is largely unacceptable, but may be required in some situations and, therefore, you need to know.

package arraypkg;

final public class Main
{
    public static void main(String... args)
    {
        int[]temp=new int[]{4,3,2,1};
        int index = 1;

        temp[index] = index = 0;
        System.out.println("temp[0] = "+temp[0]);
        System.out.println("temp[1] = "+temp[1]);
    }
}

It displays the following output on the console.

temp[0] = 4
temp[1] = 0

I do not understand this statement temp[index] = index = 0;. How does it temp[1]contain 0? How does this appointment happen?

+5
source share
4 answers

Assignment is performed ( temp[index] = (index = 0)), right associative.

But first, the expression temp[index]is evaluated for the LHS variable. At this time, indexit is still 1. Then RHS ( index = 0) is executed .

+8
source

. temp [index] = index = 0 AND temp [index]. . 0.

+1

What this line does is say that it temp[index]should equal indexafter indexa value is assigned 0.

This is why this syntax is in most cases unacceptable. It is difficult to read, and most people do not understand this.

+1
source

you set both temp [1] and the index at '0' it works from left to right. think donkey [index / * * /]

+1
source

All Articles