Java OCA OCP Practice Question 381

Question

Which of these statements concerning the charAt () method of the String class are true?

Select 2 options

  • A. The charAt() method can take a char value as an argument.
  • B. The charAt() method returns a Character object.
  • C. The expression char ch = "12345".charAt (3) will assign 3 to ch.
  • D. The expression char ch = str.charAt (str.length ()) where str is "12345", will assign 3 to ch.
  • E. The index of the first character is 0.
  • F. It throws StringIndexOutOfBoundsException if passed an value higher than or equal to the length of the string (or less than 0).
  • G. It throws ArrayIndexOutOfBoundsException if passed an value higher than or equal to the length of the string (or less than 0).


Correct Options are  : A E

Note

A. is correct. Yes, it can because it takes an int and char will be implicitly promoted to int.

B. is wrong since charAt() returns char.

C. is wrong since it will assign 4 as indexing starts from 0.

D. is wrong since it will throw IndexOutOfBoundsException as str.length () is 5 and there is no str.charAt (5);

Since indexing starts with 0, the maximum value that you can pass to charAt is length-1.

charAt() throws IndexOutOfBoundsException if you pass an invalid value.




PreviousNext

Related