Java OCA OCP Practice Question 1748

Question

What will be the result of compiling and running the following program?.

public class Main {
  public static void main(String[] args) {
    int[] array = { 4, 8, 16 };
    int i=1;
    array[++i] = --i;
    System.out.println(array[0] + array[1] + array[2]);
  }
}

Select the one correct answer.

  • (a) 13
  • (b) 14
  • (c) 20
  • (d) 21
  • (e) 24


(a)

Note

First, the expression ++i is evaluated, resulting in the value 2.

Now the variable i also has the value 2.

The target of the assignment is now determined to be the element array[2].

Evaluation of the right-hand expression, --i, results in the value 1.

The variable i now has the value 1.

The value of the right-hand expression 1 is then assigned to the array element array[2], resulting in the array contents to become {4, 8, 1}.

The program sums these values and prints 13.




PreviousNext

Related