nerdexam
Oracle

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.

Working with Selected Classes from the Java API

Question

Given:

What is the result?

Exhibit

1Z0-803 question #184 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)
  • A
    2% (1)
  • B
    2% (1)
  • C
    83% (40)
  • D
    8% (4)
  • E
    4% (2)

Why each option

The program attempts to access a character at an invalid index within a string, which results in a runtime exception.

AThe program prints nothing

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.

Bd

Printing 'd' would imply successful execution and the character 'd' being the intended output, which is incorrect given that an exception is thrown.

CA StringIndexOutOfBoundsException is thrown at runtime.Correct

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.

DAnArrayIndexOutOfBoundsException is thrown at runtime.

An ArrayIndexOutOfBoundsException is thrown when accessing an array with an invalid index, whereas StringIndexOutOfBoundsException is specific to string operations.

EA NullPointerException is thrown at runtime.

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

#String methods#runtime exception#StringIndexOutOfBoundsException

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice