Multiple choice string

Consider the following code snippet. What will be assigned to the variable fourthChar, if the code is executed? String str = new String(“Java”); char fourthChar = str.charAt(4);

  1. A. ‘a’

  2. B. ‘v’

  3. C. throws StringIndexOutofBoundsException

  4. D. null characater

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

charAt() is zero-indexed. 'Java' has indices 0-3 (J=0, a=1, v=2, a=3). Index 4 is out of bounds, so StringIndexOutOfBoundsException is thrown. Option C is correct.

AI explanation

To answer this question, we need to understand the charAt() method and how it works in Java.

The charAt() method is used to return the character at a specified index position in a string. In Java, string indexes are zero-based, which means the first character is at index 0, the second character is at index 1, and so on.

In the given code snippet, we have the following line:

char fourthChar = str.charAt(4);

Here, we are trying to access the character at index 4 of the string str. However, the string "Java" has a length of only 4 characters (indexes 0 to 3). Therefore, when we try to access the character at index 4, it will throw a StringIndexOutOfBoundsException.

Therefore, the correct answer is:

C. throws StringIndexOutOfBoundsException.