Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining array assignment in Java

Tags:

java

Consider the following code snippet in Java. I know that the statement temp[index] = index = 0; in the following code snippet is pretty much unacceptable but it may be necessary for some situations:

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 temp[index] = index = 0;.

How does temp[1] contain 0? How does this assignment occur?

like image 616
Lion Avatar asked Dec 15 '11 19:12

Lion


3 Answers

The assignment is done (temp[index] = (index = 0)), right associative.

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

like image 93
Joop Eggen Avatar answered Oct 14 '22 04:10

Joop Eggen


Your statement assigned zero to it. The statement temp[index] = index = 0 wrote zero into index AND into temp[index]. That's what that meant. Make all variables to the left of an assignment operator 0.

like image 44
chubbsondubs Avatar answered Oct 14 '22 03:10

chubbsondubs


What that line does is say that temp[index] should equal index after index is assigned the value 0.

This is why this syntax is mostly unacceptable. It's hard to read and most people don't understand it.

like image 30
Jon Egeland Avatar answered Oct 14 '22 05:10

Jon Egeland