Which Java class inherits its equals() and hashCode() directly from java.lang.Object (i.e., does not override them)?

Difficulty: Easy

Correct Answer: java.lang.StringBuffer

Explanation:


Introduction / Context:
Many core Java classes override equals() and hashCode() to provide value-based equality. Others, notably mutable sequence classes, keep identity-based equality from Object. Recognizing which is which is a common exam topic.



Given Data / Assumptions:

  • We compare several classes from java.lang.
  • We must identify the one that does not override equals() and hashCode().


Concept / Approach:
String, Integer, Double, and Character are value types and override equals()/hashCode() to compare by content/value. StringBuffer, being a mutable buffer, inherits identity-based equality from Object, meaning two different buffers with the same characters are not considered equal unless they are the same instance.



Step-by-Step Reasoning:

Check class docs/behavior: String → overrides (content-based).Double, Integer, Character → wrapper types, also override.StringBuffer → does not override; identity equality.


Verification / Alternative check:
Printing new StringBuffer("a").equals(new StringBuffer("a")) yields false, confirming identity equality.



Why Other Options Are Wrong:
Each of them defines value-based equality and a corresponding hash code implementation.



Common Pitfalls:
Confusing StringBuffer with StringBuilder (neither overrides equals/hashCode) versus String which does.



Final Answer:
java.lang.StringBuffer

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion