Interview Questions
Object Class and Wrapper Classes · Study material
Java Object and Wrapper Classes – Interview Questions
1. Which class is the parent of all classes?
java.lang.Object.
2. Name the main methods of Object.
toString, equals, hashCode, getClass, clone, wait, notify, notifyAll and the deprecated finalize.
3. What is the contract between equals and hashCode?
If a.equals(b), then a.hashCode() == b.hashCode(); the reverse need not hold.
4. What happens if you override equals but not hashCode?
Equal objects land in different buckets, so HashSet stores duplicates and HashMap lookups fail.
5. == vs equals?
== compares references (or primitive values); equals compares content when overridden.
6. Why is getClass() final?
So that it always reports the true run-time class.
7. What does clone() do?
Creates a field-by-field (shallow) copy if the class implements Cloneable; otherwise throws CloneNotSupportedException.
8. Shallow vs deep copy?
A shallow copy shares referenced objects; a deep copy duplicates them too.
9. What is a marker interface? Example?
An interface with no methods that tags a class – Cloneable, Serializable.
10. What are wrapper classes?
Classes that wrap primitives in objects: Byte, Short, Integer, Long, Float, Double, Character, Boolean.
11. What is autoboxing?
Automatic conversion from a primitive to its wrapper (Integer.valueOf).
12. What is unboxing?
Automatic conversion from a wrapper to its primitive (intValue).
13. What is the Integer cache?
valueOf returns shared Integer objects for −128 to 127, so == may be true for small values only.
14. What happens when null is unboxed?
NullPointerException.
15. parseInt vs valueOf?
parseInt returns int; valueOf returns Integer (possibly cached).
16. Are wrapper classes mutable?
No; they are immutable and final.
17. Why use BigDecimal for money?
double uses binary fractions and cannot represent most decimals exactly; BigDecimal is exact.
18. BigDecimal equals vs compareTo?
equals also compares scale (0.30 ≠ 0.3); compareTo compares only the value.
19. Why does Long.valueOf(1).equals(1) return false?
1 is boxed to Integer, and Long.equals requires a Long.
20. What does Objects.requireNonNull do?
Throws NullPointerException (with an optional message) if the argument is null, otherwise returns it.