1Z0-809 · Question #81
Given: public class X { public static void main(String[] args) { String theString = "Hello World"; System.out.println(theString.charAt(11)); } } What is the result?
The correct answer is C. A StringIndexOutOfBoundsException is thrown at runtime. charAt(11) throws a StringIndexOutOfBoundsException because "Hello World" has exactly 11 characters (indices 0–10), making index 11 one past the last valid position - Java's String class explicitly throws this exception when an index is out of range. Option A is wrong because…
Question
Options
- AThe program prints nothing
- Bd
- CA StringIndexOutOfBoundsException is thrown at runtime.
- DAnArrayIndexOutOfBoundsException is thrown at runtime.
- EA NullPointerException is thrown at runtime.
How the community answered
(33 responses)- A9% (3)
- B3% (1)
- C82% (27)
- E6% (2)
Explanation
charAt(11) throws a StringIndexOutOfBoundsException because "Hello World" has exactly 11 characters (indices 0–10), making index 11 one past the last valid position - Java's String class explicitly throws this exception when an index is out of range. Option A is wrong because the program does not reach println silently; it crashes. Option B is wrong because 'd' (index 10, the last character) would require charAt(10), not charAt(11). Option D is wrong because String is not an array - ArrayIndexOutOfBoundsException applies to array access (arr[i]), not String methods. Option E is wrong because theString is clearly initialized and not null, so no NPE can occur. Memory tip: Count the characters in the string first - "Hello World" is 11 chars, so valid indices are 0 to 10; any index ≥ length triggers StringIndexOutOfBoundsException, which is always the culprit for charAt/substring range errors on String.
Community Discussion
No community discussion yet for this question.