Wrapper Classes

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Wrapper Classes are objects that encapsulate (wrap) a primitive data type.
  • Example: int is a primitive, Integer is its wrapper class.
  • They allow primitives to be used in contexts that strictly require objects, such as the Java Collections Framework (e.g., ArrayList).

Concept

Java is an object-oriented language, but it retains the 8 primitive types for performance. However, many of Java’s built-in utilities and data structures can only work with objects.

PrimitiveWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean
charCharacter

Utility Methods

Wrapper classes also provide very useful static methods for data conversion (e.g., parsing a String into an integer).

Examples

import java.util.ArrayList;

public class WrapperExample {
    public static void main(String[] args) {
        // 1. Collections require Wrapper Classes
        // ArrayList<int> list = new ArrayList<>(); // Compile error!
        ArrayList<Integer> list = new ArrayList<>();
        list.add(10); // Autoboxing takes over here
        
        // 2. Utility Methods
        String numberStr = "123";
        int parsedNumber = Integer.parseInt(numberStr);
        
        System.out.println(parsedNumber + 10); // Outputs: 133
        
        // 3. Constants
        System.out.println("Max Int: " + Integer.MAX_VALUE);
    }
}

Interview Questions

Q: Can wrapper classes be null?
A: Yes. Unlike primitives which always have a default value (like 0 or false), Wrapper classes are Objects. Like any object reference in Java, they can be null.

Q: Are Wrapper classes immutable?
A: Yes. All wrapper classes (Integer, Double, etc.) and String are immutable. Once an Integer object is created with a value, that internal value cannot be changed. If you reassign the variable, a brand new Integer object is created.