Java · OOP, JVM and backend craft
What is the difference between primitives and wrapper classes?
Short answer
Primitives store raw values on the stack or inside objects. Wrapper classes are heap objects that add nullability, methods and generic compatibility at the cost of allocation and identity pitfalls.
Java has eight primitives: boolean, byte, short, char, int, long, float and double. Each has a corresponding wrapper such as Integer or Double. Autoboxing converts between them automatically, but the conversion is not free and the identity rules are surprising.
Integer a = 127;
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a == b);
System.out.println(c == d);Where each is appropriate
- Use primitives for arithmetic, loop counters and hot paths
- Use wrappers when null is meaningful, such as an optional database column
- Use wrappers in generics because type parameters cannot be primitives
- Use equals rather than == when comparing wrapper values
Unboxing a null wrapper throws NullPointerException. That commonly appears when a missing database value is assigned to an int field. Prefer primitive types in method signatures when absence is not allowed, and validate wrapper inputs at the boundary.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does 128 == 128 behave differently for Integer objects?
- 2What happens when you unbox null?
- 3When is a wrapper the better choice?
- 4How does autoboxing affect performance in a loop?
Say it in the interview
Primitives hold raw values and are cheap. Wrappers are objects, so they can be null and can be used in generics, but they allocate and introduce identity confusion. The classic trap is comparing Integer objects with double equals: values from minus 128 to 127 come from the cache, larger values do not. I use equals for wrapper values and unbox carefully because unboxing null throws a NullPointerException.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.