Assignment operator explanation in 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 , gives:

2 30  

i hoping give

40 2 

at (1) why value of index in assignment not changed 2 ( , kept 3). ?

the right-associativity of = implied section 15.26 of java language specification (jls) means expression can represented tree, thus:

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

but then, section 15.7 states:

the java programming language guarantees operands of operators appear evaluated in specific evaluation order, namely, left right.

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


obviously, should never write code relies on fact, relies on rules no reader understands.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -