Subdomain 1.2: Manipulate text, including text blocks, using String and StringBuilder classes
1.What is printed by the following code? ```java String s1 = "Java"; String s2 = "Java"; String s3 = new String("Java"); String s4 = s3.intern(); System.out.println((s1 == s2) + " " + (s1 == s3) + " " + (s1 == s4)); ```
- A.true false true
- B.true true true
- C.false false true
- D.true false false
Show answer & explanation
Correct answer: A — true false true
- A. `s1` and `s2` are both string literals, so the compiler resolves them to the same interned reference in the string pool, making `s1 == s2` true. `s3` is created with `new String(...)`, producing a distinct heap object, so `s1 == s3` is false; calling `intern()` on `s3` returns the pooled reference for "Java", which is the same object as `s1`, making `s1 == s4` true.
- B. This assumes `new String("Java")` also produces the pooled reference, but the `new` keyword explicitly forces allocation of a separate heap object distinct from anything in the string pool. `s1 == s3` must therefore be false, not true.
- C. This assumes string literals are not automatically pooled, but the Java compiler always interns literal strings, so `s1` and `s2` refer to the identical pooled object and their comparison must be true, not false.
- D. This correctly identifies that `s1 == s3` is false but incorrectly assumes `intern()` returns a fresh object rather than the existing pooled reference. `intern()` specifically looks up and returns the canonical pooled instance, so `s1 == s4` must be true.