Question:
Consider the following Java code snippet:
public class ExceptionHandlingExample {
public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Charlie", "David"};
try {
for (int i = 0; i <= names.length; i++) {
System.out.println(names[i]);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("An exception occurred: " + e.getMessage());
} finally {
System.out.println("Program execution completed.");
}
}
}
If the above code is executed, what will be the output?
A) Alice B) Bob C) Charlie D) David E) An exception occurred: Array index out of range F) An exception occurred: Array index out of bounds G) An exception occurred: null H) Program execution completed. I) None of the above.
Answer:
The correct answer is E) An exception occurred: Array index out of range.
Here's a step-by-step explanation of the code execution:
String
array names
with four elements: "Alice", "Bob", "Charlie", and "David".names
array using a for loop.i = 0
to i <= names.length
, which means it will iterate 5 times (0, 1, 2, 3, 4).names[i]
, starting from i = 0
. This will successfully print "Alice", "Bob", "Charlie", and "David" in separate lines.i
becomes 4
, which is beyond the index range of the names
array, an ArrayIndexOutOfBoundsException
is thrown.finally
block is executed, which prints "Program execution completed.".Therefore, the final output will be:
Alice
Bob
Charlie
David
An exception occurred: Array index out of range
Program execution completed.