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);

Options
- ‘a’
- ‘v’
- throws StringIndexOutofBoundsException
- null characater


CORRECT ANSWER : throws StringIndexOutofBoundsException

Discussion Board
StringIndexOutofBoundsException

If you see the string then "JAVA" where J starts with a position 0 and ends at A having position 3. The function is trying to access an unknown location that doesn;t exist that is why the exception StringIndexOutOfBounds will be thrown. This StringIndexOutOfBoundsException class when used with an argument indicates the illegal index. It is usually thrown by charAt method in class String and by other String methods to indicate that an index is either negative or greater than or equal to the size of the string. It usually taken an Int paramater and whenever a function tries to call an unknown memory location then this exception is usually thrown by the program.

Rohit Sharma 07-27-2014 03:50 PM

Write your comments


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)


Advertisement