1Z0-803 · Question #184
Given: What is the result?
The correct answer is C. A StringIndexOutOfBoundsException is thrown at runtime.. The program attempts to access a character at an invalid index within a string, which results in a runtime exception.
Question
Given:
What is the result?
Exhibit
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
(48 responses)- A2% (1)
- B2% (1)
- C83% (40)
- D8% (4)
- E4% (2)
Why each option
The program attempts to access a character at an invalid index within a string, which results in a runtime exception.
The program would print nothing only if it completed without error and had no print statements, or if a print statement was called with an empty string, which does not align with an exception being thrown.
Printing 'd' would imply successful execution and the character 'd' being the intended output, which is incorrect given that an exception is thrown.
A StringIndexOutOfBoundsException occurs when a program tries to access an index that is out of bounds for the string's length, either a negative index or an index greater than or equal to the string's length. This is a common runtime error in Java when working with string characters or substrings, such as using charAt() or substring() methods with incorrect arguments.
An ArrayIndexOutOfBoundsException is thrown when accessing an array with an invalid index, whereas StringIndexOutOfBoundsException is specific to string operations.
A NullPointerException occurs when trying to invoke a method on a null object reference, not when accessing an out-of-bounds string index.
Concept tested: Java String indexing and exceptions
Source: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringIndexOutOfBoundsException.html
Topics
Community Discussion
No community discussion yet for this question.
