ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
String s = "hello";
System.out.print("[" + s.substring(5) + "]");
System.out.print(s.substring(6));
  1. A. "[o]" is printed, then StringIndexOutOfBoundsException is thrown
  2. B. "[]" is printed and nothing else
  3. C. "[]" is printed, then StringIndexOutOfBoundsException is thrown
  4. D. StringIndexOutOfBoundsException is thrown before anything is printed

Correct answer: C. "[]" is printed, then StringIndexOutOfBoundsException is thrown

substring(beginIndex) allows beginIndex == length() and returns the empty string; beginIndex 6 > length 5 is out of range and throws.

More OOP with C++ and Java questions

Exams that ask this topic