String Methods

AP Computer Science A· difficulty 4/5

Consider:

<code class="language-java">String s = "ABCDE"; String t = s.substring(2, 2) + s.substring(1, 4) + s.substring(5); System.out.print("[" + t + "]"); </code></pre> What is printed?

  • A

    StringIndexOutOfBoundsException

  • B

    [BCD]

    check_circle
  • C

    [BCDE]

  • D

    [CBCD]

Explanation

<code>s.substring(2,2)</code> returns the empty string "". <code>s.substring(1,4)</code> returns "BCD". <code>s.substring(5)</code> is valid because it equals the length, returning "". Concatenating gives "BCD" inside the brackets.

Want 10 more like this — adaptive to your weak spots?

Related questions