Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the following code does not throw IndexOutOfBoundsException, and print out 9 9 6?

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
  } 
} 
like image 386
rohit singh Avatar asked Jul 28 '11 14:07

rohit singh


1 Answers

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

like image 171
Saurabh Gokhale Avatar answered Oct 18 '22 19:10

Saurabh Gokhale