Java OCA OCP Practice Question 1756

Question

What is the result of running the following program?.

public class Main {
  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]);
  }
}

Select the one correct answer.

  • (a) When run, the program throws an exception of type ArrayIndexOutOfBoundsException.
  • (b) When run, the program will print "9 9 6".
  • (c) When run, the program will print "9 0 6".
  • (d) When run, the program will print "9 3 6".
  • (e) When run, the program will print "9 3 9".


(b)

Note

The element referenced by a[i] is determined based on the current value of i, which is zero.

The element a[0]. The expression i = 9 will evaluate to the value 9, which will be assigned to the variable i.

The value 9 is also assigned to the array element a[0].

After the execution of the statement, the variable i will contain the value 9, and the array a will contain the values 9 and 6.

The program will print 9 9 6, when run.




PreviousNext

Related