nerdexam
Oracle

1Z0-811 · Question #50

Given the code fragment: String a = "Java"; String b = new String("Java"); System.out.println(a.equals(b)); System.out.println(a==b); What is the result?

The correct answer is C. true false. Option C is correct because equals() compares string content (both hold "Java", so it returns true), while == compares object references - a points to the String pool and b points to a separate heap object created by new, so they are different references and == returns false. A…

Data Types and Operators

Question

Given the code fragment: String a = "Java"; String b = new String("Java"); System.out.println(a.equals(b)); System.out.println(a==b); What is the result?

Options

  • Afalse false
  • Btrue true
  • Ctrue false

How the community answered

(50 responses)
  • A
    4% (2)
  • B
    6% (3)
  • C
    90% (45)

Explanation

Option C is correct because equals() compares string content (both hold "Java", so it returns true), while == compares object references - a points to the String pool and b points to a separate heap object created by new, so they are different references and == returns false.

A (false/false) is wrong because equals() is designed to compare character content, not memory addresses - it will always return true for two strings with identical characters.

B (true/true) is wrong because new String(...) explicitly creates a fresh object on the heap, guaranteeing a different reference from the pooled literal, so == can never be true here.

Memory tip: Think of == as asking "same object?" and equals() as asking "same value?" - in Java, new always means a brand-new object, so == fails; use equals() whenever comparing String contents.

Topics

#String equality#equals() vs ==#reference vs value#String interning

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice