Explain wrapper class with example.

Java Wrapper Class Explained with Example

In Java, a wrapper class is an object-based representation of a primitive data type. For example, int is wrapped by Integer, and double is wrapped by Double. Wrapper classes are immutable and belong to the java.lang package.

Primitive Types and Their Wrapper Classes

  • byte → Byte
  • short → Short
  • int → Integer
  • long → Long
  • float → Float
  • double → Double
  • char → Character
  • boolean → Boolean

Why Wrapper Classes Are Useful

  • Work with collections and generics (e.g., ArrayList requires objects, not primitives).
  • Support null values when a “no data” state is needed.
  • Provide utility methods like parsing, value conversion, and constants (MIN_VALUE, MAX_VALUE).
  • Enable autoboxing and unboxing for easy conversion between primitives and objects.

Example: Autoboxing, Unboxing, and Collections

// Demonstrating wrapper classes in Java

import java.util.ArrayList;

public class WrapperDemo {
    public static void main(String[] args) {
        // Autoboxing: primitive -> wrapper
        int a = 10;
        Integer x = a;           // automatic conversion to Integer

        // Unboxing: wrapper -> primitive
        int b = x;               // automatic conversion back to int

        // Using wrapper types in collections (primitives are not allowed)
        ArrayList list = new ArrayList<>();
        list.add(5);             // autoboxing of int to Integer
        list.add(Integer.valueOf(15));
        int first = list.get(0); // unboxing Integer to int

        // Parsing from String using wrapper class methods
        String s = "42";
        int parsed = Integer.parseInt(s);  // "42" -> 42 (int)

        // Useful constants and methods
        int max = Integer.MAX_VALUE;
        int compareResult = Integer.compare(10, 20); // -1 because 10 < 20

        System.out.println("x = " + x + ", b = " + b);
        System.out.println("List first = " + first + ", parsed = " + parsed);
        System.out.println("MAX_INT = " + max + ", compare(10,20) = " + compareResult);
    }
}

In short, a Java wrapper class lets you treat primitive values as objects, making them compatible with collections and providing handy utility methods, while autoboxing and unboxing keep the code simple.