String Objects: Concatenation, Literals, and More

AP Computer Science A· difficulty 4/5

Consider:

<code class="language-java">String a = "hi"; String b = "hi"; String c = new String("hi"); String d = a + ""; boolean p = (a == b); boolean q = (a == c); boolean r = a.equals(c); boolean s = (a == d); </code></pre> What are the values of <code>p, q, r, s</code> respectively?

  • A

    true, false, true, false

    check_circle
  • B

    true, true, true, true

  • C

    true, false, false, false

  • D

    false, false, true, false

Explanation

String literals are interned, so a==b is true. <code>new String("hi")</code> creates a distinct object, so a==c is false but a.equals(c) is true. <code>a + ""</code> produces a new String object at runtime, so a==d is false.

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

Related questions