Wrapper Class in Java — Java Technical Interview Questions & Answers
Wrapper Class in Java
Wrapper Class in Java
- Wrapper classes box primitives into objects: int → Integer, double → Double, boolean → Boolean. ArrayList and HashMap need objects, not raw int.
- Autoboxing: Integer n = 5; Unboxing: int x = n;. If n is null, unboxing throws NullPointerException — a favourite trap.
- Use wrappers in collections. Use primitives for simple maths — cheaper.
- Let's take this on the board with one tiny Main class — no extra files. Wrapper Class in Java — 10 is boxed into Integer, then unboxed back to int for math. Start from main, go line by line, and stop at each print. That output is the proof for Wrapper Class.
Technical Interview Tip: Why wrappers? Lists need objects. Then mention null unboxing NPE.
Code Examples for Wrapper Class in Java
Example
// Wrapper / autoboxing
public class Main {
public static void main(String[] args) {
Integer a = 10; // autobox
int b = a; // unbox
System.out.println(a + b);
}
}Wrapper Class in Java — 10 is boxed into Integer, then unboxed back to int for math.
How to Explain Wrapper Class in Java to an Interviewer
What is Integer?
Wrapper for int
Why wrappers?
Collections need objects
Null Integer unboxed?
NullPointerException