7

I am new to java. I had a doubt.

class ArrTest{ 
  public static void main(String args[])
{ 
    int   i = 0; 
    int[] a = {3,6}; 
    a[i] = i = 9; 
    System.out.println(i + " " + a[0] + " " + a[1]); // 9 9 6
  } 
} 
hello_there_andy
  • 2,039
  • 2
  • 21
  • 51
  • 1
    Please note that, expressly because of the confusion you (and potentially someone else) are experiencing, it is *never* a good idea to try 'tricky' code like `a[i] = i = 9;` Instead, factor it out to seperate lines - future generations will thank you. – Clockwork-Muse Jul 28 '11 at 15:41

2 Answers2

8

This is another good example the great Java evaluation rule applies.

Java resolves the addresses from left to right. a[i] which is the address of a[0], then i which is the address of i, then assign 9 to i, then assign 9 to a[0].

IndexOutOfBoundsException will never be throw since a[0] is not out of bound.
The misconception is a[9], which is against the left-to-right-rule

Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
0

It should not.

a[i] = i = 9 (makes i equal to 9) a[0] should also be 9 since you assigned 9 to it (a[i] = i = 9), Initially a[0] was 3 and a[1] is 6 (initial value (int[] a = {3, 6};)

You should get 9 9 6.

If you do a[2] then it will give you an IndexOutOfBoundsException.

MammothOne
  • 490
  • 2
  • 5
  • 12