nerdexam
Oracle

1Z0-808 · Question #53

Given the code fragment: public static void main(String[] args) { StringBuilder sb = new StringBuilder(5); String s = ""; if (sb.equals(s)) { System.out.println("Match 1"); } else if…

The correct answer is B. Match 2. B is correct because StringBuilder does not override equals() from Object, so sb.equals(s) performs reference comparison - two different objects, so it returns false, skipping "Match 1". However, sb.toString() produces "" and s.toString() also produces "", and String.equals()…

Working with Selected Classes from the Java API

Question

Given the code fragment: public static void main(String[] args) { StringBuilder sb = new StringBuilder(5); String s = ""; if (sb.equals(s)) { System.out.println("Match 1"); } else if (sb.toString().equals(s.toString())) { System.out.println("Match 2"); } else { System.out.println("No Match"); } } What is the result?

Options

  • AMatch 1
  • BMatch 2
  • CNo Match
  • DA NullPointerException is thrown at runtime.

How the community answered

(29 responses)
  • A
    7% (2)
  • B
    72% (21)
  • C
    17% (5)
  • D
    3% (1)

Explanation

B is correct because StringBuilder does not override equals() from Object, so sb.equals(s) performs reference comparison - two different objects, so it returns false, skipping "Match 1". However, sb.toString() produces "" and s.toString() also produces "", and String.equals() compares content, so the second condition evaluates to true, printing "Match 2".

A is wrong because StringBuilder inherits Object.equals(), which compares object references, not content. Even though both sb and s represent empty strings, they are different object types at different memory addresses.

C is wrong because toString() on an empty StringBuilder produces an empty String "", which does equal s by content - so "No Match" is never reached.

D is wrong because neither sb nor s is null; new StringBuilder(5) constructs a valid (empty) builder and "" is a valid (empty) String literal.

Memory tip: Think of StringBuilder as "equals-blind" - it never learned to compare by content. Whenever you see StringBuilder.equals(anything), mentally replace it with == and expect false unless it's the exact same object reference.

Topics

#StringBuilder vs String equality#equals() method behavior#toString() conversion#Object comparison

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice