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). ?
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 :
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.
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 :
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With