nerdexam
Oracle

1Z0-803 · Question #230

Given: public class Test { public static void main(String[] args) { int arr[] = new int[4]; arr[0] = 1; arr[1] = 2; arr[2] = 4; arr[3] = 5; int sum = 0; try { for (int pos = 0; pos <= 4; pos++) { sum

The correct answer is B. Invalid Index 12. The loop (for (int pos = 0; pos <= 4; pos++) {), it should be pos <= 3, causes an exception, which is caught. Then the correct sum is printed.

Handling Exceptions

Question

Given:

public class Test { public static void main(String[] args) { int arr[] = new int[4]; arr[0] = 1; arr[1] = 2; arr[2] = 4; arr[3] = 5; int sum = 0; try { for (int pos = 0; pos <= 4; pos++) { sum = sum + arr[pos]; } } catch (Exception e) { System.out.println("Invalid index"); } System.out.println(sum); } } What is the result?

Options

  • A12
  • BInvalid Index 12
  • CInvalid Index
  • DCompilation fails

How the community answered

(31 responses)
  • A
    10% (3)
  • B
    84% (26)
  • C
    3% (1)
  • D
    3% (1)

Explanation

The loop (for (int pos = 0; pos <= 4; pos++) {), it should be pos <= 3, causes an exception, which is caught. Then the correct sum is printed.

Topics

#arrays#ArrayIndexOutOfBoundsException#try-catch#for loop

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice