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()…
Question
Options
- AMatch 1
- BMatch 2
- CNo Match
- DA NullPointerException is thrown at runtime.
How the community answered
(29 responses)- A7% (2)
- B72% (21)
- C17% (5)
- D3% (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
Community Discussion
No community discussion yet for this question.