Multiple choice

What will be the result of the following code?

String s = “Welcome To Java”; s.charAt(s.length());

  1. a

  2. v

  3. Compiler Error : cannot pass a function as parameter

  4. Compiler Error : parameters not sufficient

  5. Run time error

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

This is the correct answer. s.length() will return 15 because there are 15 characters in the string. So, the code looks like this: s.charAt(15); the index count starts at 0. In this way, the last character is 'a' at index number 14. So, if we try to access a character in a string which is out of bound, then a runtime exception “StringIndexOutOfBound” will be thrown. So, we can pass only till s.charAt(s.length()-1).