Java · Question 11 · Medium

What will be the output of the following Java program?

public class Main {
    public static void main(String[] args) {
        try {
            int[] a = new int[3];
            a[3] = 1;
            System.out.print("A");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.print("B");
        } catch (Exception e) {
            System.out.print("C");
        } finally {
            System.out.print("D");
        }
    }
}
  1. BD
  2. ABD
  3. BCD
  4. CD
Answer and explanation

Answer: A. BD

Explanation: a[3] is out of bounds for an array of length 3, so the exception is thrown before "A" is printed. The first matching catch prints B, and finally always prints D.

Previous: What will be the output of the following Java program? · Next: What will be the output of the following Java program?

Practise java

Try a fresh set of java questions with an explanation after every answer, free and without signing up: Java practice. Or sit a full placement mock test.

More java questions

More technical & programming practice

Python · Data Structures · Algorithms · Object-Oriented Programming · DBMS · SQL · Operating Systems · Computer Networks

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge