nerdexam
Oracle

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 ==…

Working with Java Data Types

Question

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 + " "); System.out.println(s2 == s3); What is the result?

Options

  • Atrue false true
  • Btrue false false
  • Cfalse false true
  • Dfalse true false
  • Efalse false false

How the community answered

(25 responses)
  • B
    4% (1)
  • C
    12% (3)
  • D
    4% (1)
  • E
    80% (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 never true; s1 (heap object) cannot equal (s2 + " ") (a different string).
  • Why D is wrong: s1 == s3 is false because s1 is a heap object and s3 is the pool reference.
  • Why E is wrong: It claims s2 == s3 is false, but intern() is guaranteed by the Java spec to return the canonical pool reference - the same object s2 already points to, making s2 == s3 true.

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

#string interning#object references#string pool#reference equality

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice