Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment operator explanation in Java

Tags:

java

public class Conversions {

        public static void main(String[] args) {

                    int index = 3;
                    int[] arr = new int[] { 10, 20, 30, 40};

                    arr[index] = index = 2; //(1)
                    System.out.println("" + arr[3] + " " + arr[2]);

            }
    }

I have this and it gives:

2 30 

I was hoping it will give

40 2

At (1) Why was the value of the index in assignment not changed to 2 ( and kept as 3). ?

like image 514
Ankur Agarwal Avatar asked Jul 21 '13 23:07

Ankur Agarwal


People also ask

How to divide assignment operator in Java?

In java we can divide assignment operator in two types : The = operator in java is known as assignment or simple assignment operator. It assigns the value on its right side to the operand (variable) on its left side. For example :

What are the assignment operators?

This article explains all that one needs to know regarding the Assignment Operators. These operators are used to assign values to a variable. The left side operand of the assignment operator is a variable, and the right side operand of the assignment operator is a value.

What is the = operator in Java?

The = operator in java is known as assignment or simple assignment operator. It assigns the value on its right side to the operand (variable) on its left side. For example :

What is the difference between variable and value in assignment operator?

The left side operand of the assignment operator is a variable and the right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the operand on the left side otherwise the compiler will raise an error.


1 Answers

The right-associativity of = implied by section 15.26 of the Java Language Specification (JLS) means that your expression can be represented as a tree, thus:

           =
    +------+-------+
    |              |
arr[index]         =
              +----+----+
              |         |
            index       2

But then, section 15.7 states:

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

Therefore, arr[index] is evaluated before index = 2 is, i.e. before the value of index is updated.


Obviously, you should never write code that relies on this fact, as it relies on rules that almost no reader understands.

like image 173
Oliver Charlesworth Avatar answered Sep 26 '22 01:09

Oliver Charlesworth