Java Wrapper Classes-interview
Q1. What are Wrapper Classes in Java, and why are they needed?
Wrapper classes are object representations of primitive data types. They are needed because Java collections and generics work with objects, not primitive
Q2. What is the difference between primitive types and wrapper classes?
- Primitives → stored directly, faster, not objects.
- Wrapper Classes → objects, provide methods, required in collections and frameworks.
Q3. Explain Autoboxing and Unboxing with examples.
- Autoboxing: Automatic conversion of primitive to wrapper object. Example: Integer i = 10;
- Unboxing: Automatic conversion of wrapper object to primitive. Example: int x = i;
Q4. Are Wrapper Classes immutable in Java?
Yes, all wrapper classes (Integer, Double, etc.) are immutable. Once created, their values cannot be changed.
Q5. Can a Wrapper Class object be null? What happens if we unbox it?
Yes, wrapper objects can be null. If we try to unbox a null wrapper object, it results in a NullPointerException.