1Z0-819 · Question #164
Given the following fragment: String s1 = new String("ORACLE"); String s2 = "ORACLE"; String s3 = s1.intern(); System.out.println(s1 == s2 + " "); System.out.println(s1 == s3 + " ")…
The correct answer is E. false false false. Note: The stated correct answer appears to be E, but based on Java specification, option C (false false true) is actually correct. Here is why: The first two println calls contain a subtle operator precedence trap: + binds tighter than ==, so s1 == s2 + " " evaluates as s1 ==…
Question
Options
- Atrue false true
- Btrue false false
- Cfalse false true
- Dfalse true false
- Efalse false false
How the community answered
(25 responses)- B4% (1)
- C12% (3)
- D4% (1)
- E80% (20)
Explanation
Note: The stated correct answer appears to be E, but based on Java specification, option C (false false true) is actually correct. Here is why:
The first two println calls contain a subtle operator precedence trap: + binds tighter than ==, so s1 == s2 + " " evaluates as s1 == (s2 + " ") - comparing s1 ("ORACLE") against a new string "ORACLE " (with a trailing space). Since those have different values and different references, both print false. For the third line, s2 == s3 compares two references to the same string pool object: s2 is the literal "ORACLE" already interned in the pool, and s3 = s1.intern() returns that exact same pool reference - so s2 == s3 is true.
- Why A/B are wrong: The first
==is nevertrue;s1(heap object) cannot equal(s2 + " ")(a different string). - Why D is wrong:
s1 == s3isfalsebecauses1is a heap object ands3is the pool reference. - Why E is wrong: It claims
s2 == s3isfalse, butintern()is guaranteed by the Java spec to return the canonical pool reference - the same objects2already points to, makings2 == s3true.
Memory tip: intern() always returns the pool reference - so comparing it to another literal using == will be true. The new String(...) trap only matters when comparing heap objects to each other or to pool strings, never when both sides went through interning.
Topics
Community Discussion
No community discussion yet for this question.