Java OCA OCP Practice Question 844

Question

Consider the following program...

public class Main{ 
   public static void main (String [] args){ 
      int myArray [][] =  {  {1, 2}, null  }; 
      for  (int i = 0; i < 2; i++) 
         for  (int j = 0; j < 2; j++) 
            System .out.println (myArray [i][j]); 
    } 
} 

Which of the following statements are true?

Select 1 option

  • A. It will not compile.
  • B. It will throw an ArrayIndexOutOfBoundsException at Runtime.
  • C. It will throw a NullPointerException at Runtime.
  • D. It will compile and run without throwing any exceptions.
  • E. None of the above.


Correct Option is  : C

Note

It will throw a NullPointerException for myArray [1][0] because myArray [1] is null.

Note that null is not same as having less number of elements in an array than expected.

If you try to access myArray [2][0], it would have thrown ArrayIndexOutOfBoundsException because the length of myArray is only 2 and so myArray [2] tries to access an element out of that range.

myArray [2] is not null, it simply does not exist.




PreviousNext

Related