Wrapper Classes

Thinking

Imagine a situation where you need to store a primitive value in a data structure like an ArrayList — it can only store objects, not primitive types. Java solves this using Wrapper Classes, which wrap primitives into objects.

Understanding wrapper classes helps bridge the gap between object-oriented programming and primitive types, enabling flexibility and utility in real-world Java applications.

Description

Wrapper Classes in Java are used to convert primitive data types into objects. Each primitive has a corresponding wrapper class in the java.lang package.

Primitive Types and Their Wrappers:

  • byteByte
  • shortShort
  • intInteger
  • longLong
  • floatFloat
  • doubleDouble
  • charCharacter
  • booleanBoolean
Note:

Wrapper classes are immutable and provide utility methods for parsing and conversions. Java supports autoboxing (primitive to object) and unboxing (object to primitive).

Video Resources

Wrapper Classes in Java

Detailed explanation of wrapper classes, autoboxing, and utility methods.

Examples (code)

Basic Wrapper Class Usage


public class WrapperExample {
    public static void main(String[] args) {
        int primitiveInt = 42;

        // Autoboxing: primitive to object
        Integer wrappedInt = primitiveInt;

        // Unboxing: object to primitive
        int unwrappedInt = wrappedInt;

        System.out.println("Wrapped: " + wrappedInt);
        System.out.println("Unwrapped: " + unwrappedInt);
    }
}
  

Using Wrapper Classes in Collections


import java.util.ArrayList;

public class WrapperList {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();

        numbers.add(10);  // Autoboxing
        numbers.add(20);
        numbers.add(30);

        for (int num : numbers) {
            System.out.println(num); // Unboxing
        }
    }
}
  

Real-World Applications

Collection Framework

Storing primitive values in collections like ArrayList or HashMap requires wrapper classes.

Parsing and Conversion

Convert strings to primitives using wrapper methods like Integer.parseInt().

Reflection & Utilities

Wrapper classes are used in reflection, type conversion, and generic utility functions.

Interview Questions

Q1: What is the difference between a primitive type and a wrapper class?

Show Answer

Primitive types are basic data types (like int, char) with no methods, while wrapper classes are object representations of these types that provide utility methods.

Q2: What are autoboxing and unboxing in Java?

Show Answer

Autoboxing is the automatic conversion of a primitive type to its wrapper object. Unboxing is the reverse process. Java does this automatically when needed.

Q3: Why are wrapper classes immutable?

Show Answer

Immutability ensures thread-safety and consistent behavior, especially when used in collections and caching mechanisms.