ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
public class Main {
public static void main(String[] a) {
int[] arr = {1, 2, 3};
try {
System.out.print(arr[5]);
} catch (Exception e) {
System.out.print("caught " + e.getClass().getSimpleName());
}
}
}- A. caught Exception
- B. caught ArrayIndexOutOfBoundsException
- C. Compile-time error: catch (Exception e) cannot catch an array index error
- D. The program crashes: ArrayIndexOutOfBoundsException is not a subtype of Exception
Correct answer: B. caught ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException is an unchecked RuntimeException, and all RuntimeExceptions are subtypes of Exception, so catch (Exception e) catches it. e.getClass().getSimpleName() reports the actual runtime class, ArrayIndexOutOfBoundsException, not the static catch type.
More OOP with C++ and Java questions
- What is printed? java public class Main { static void a() { b(); } static void b() { c(); } static void c() { throw new…
- Does this compile? java public class Main { public static void main(String[] a) { try { throw new RuntimeException(); } catch (Exception…
- What is printed? java class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) {…
- What is printed? java public class Main { public static void main(String[] args) { String a = "hello"; String b = "hello"; String c = new…
- What is printed? java public class Main { public static void main(String[] args) { String a = "hello"; String c = new…
- What is printed? java import java.util.; public class Main { public static void main(String[] args) { List<Integer> nums =…