1Z0-811 · Question #22
Given the code fragment: String flavors[] = {"Vanilla", "Chocolate"}; int choice = 2; switch (choice) { case 1: System.out.println("Selected " + flavors[1] + " flavor."); break; case 2…
The correct answer is C. An ArrayIndexOutOfBoundsException is thrown at run time. Option C is correct because the array flavors has only two elements at indices 0 ("Vanilla") and 1 ("Chocolate") - valid indices are 0 and 1 only. When choice is 2, execution jumps to case 2, which attempts to access flavors[2], a non-existent index, causing an…
Question
Options
- ASelected null flavor.
- BSelected Chocolate flavor.
- CAn ArrayIndexOutOfBoundsException is thrown at run time.
- DSelected Chocolate flavor. Thank you!
How the community answered
(47 responses)- A4% (2)
- B15% (7)
- C72% (34)
- D9% (4)
Explanation
Option C is correct because the array flavors has only two elements at indices 0 ("Vanilla") and 1 ("Chocolate") - valid indices are 0 and 1 only. When choice is 2, execution jumps to case 2, which attempts to access flavors[2], a non-existent index, causing an ArrayIndexOutOfBoundsException at runtime before any output is produced.
Options B and D (both say "Selected Chocolate flavor.") are wrong because "Chocolate" is at flavors[1], not flavors[2] - the code would need to read flavors[1] in case 2 to print that. Option A is wrong because Java throws an exception on an out-of-bounds access rather than returning null; null would only appear if the array slot itself held a null value.
Memory tip: Java arrays of size n have valid indices 0 through n-1. Whenever you see an array access, quickly check: length - 1 = last valid index. Here, length 2 means index 2 is always one too far.
Topics
Community Discussion
No community discussion yet for this question.