Java OCA OCP Practice Question 895

Question

Which is the first line to prevent this code from compiling and running without error?

char[][] myField = new char[3][3];                 // r1 
myField[1][3] = 'X';                               // r2 
myField[2][2] = 'X'; 
myField[3][1] = 'X'; 
System.out.println(myField.length + " in a row!"); // r3 
  • A. Line r1
  • B. Line r2
  • C. Line r3
  • D. None of the above


B.

Note

Arrays begin with an index of 0.

This array is a 3 by 3 array.

Therefore. only indexes 0, 1. and 2 are valid.

Line r2 throws an ArrayIndexOutOfBoundsException.

Therefore. Option B is correct.




PreviousNext

Related