Wrapper classes

Java provides wrapper classes in the java.lang package to convert primitive data types into objects. These classes are essential for treating primitive data types as objects, enabling them to be used in data structures like collections.

Why Wrapper Classes?

  1. Object Manipulation: Primitive data types cannot be treated as objects. Wrapper classes bridge this gap.
  2. Data Structures: Collections like ArrayList, HashMap, etc., only work with objects, not primitives.
  3. Utility Methods: Wrapper classes provide useful methods for data conversion and manipulation.
  4. Autoboxing and Unboxing: Automatic conversion between primitives and their corresponding wrapper objects.

Wrapper Classes Mapping

Important Wrapper Class Methods:

Conversion Methods:
Integer.parseInt(String s) — Converts a string to an int.

Double.parseDouble(String s) — Converts a string to a double.Code language: JavaScript (javascript)
Value Extraction Methods:
intValue() — Extracts the primitive int value from an Integer object.

doubleValue() — Extracts the primitive double value from a Double object.Code language: JavaScript (javascript)
Comparison Methods:
compare(int x, int y) — Compares two integers.

equals(Object obj) — Checks equality of two objects.Code language: JavaScript (javascript)

Example Program

public class WrapperClassDemo {
    public static void main(String[] args) {
        // Autoboxing: Converting primitive to Wrapper
        Integer intObj = 100;
        Double doubleObj = 45.67;
        Boolean boolObj = true;

        System.out.println("Integer Object: " + intObj);
        System.out.println("Double Object: " + doubleObj);
        System.out.println("Boolean Object: " + boolObj);

        // Unboxing: Converting Wrapper to primitive
        int intValue = intObj;
        double doubleValue = doubleObj;
        boolean boolValue = boolObj;

        System.out.println("Primitive int: " + intValue);
        System.out.println("Primitive double: " + doubleValue);
        System.out.println("Primitive boolean: " + boolValue);

        // Using Wrapper class methods
        int maxInt = Integer.MAX_VALUE;
        int minInt = Integer.MIN_VALUE;
        int parsedInt = Integer.parseInt("123");

        System.out.println("Max Integer: " + maxInt);
        System.out.println("Min Integer: " + minInt);
        System.out.println("Parsed Integer: " + parsedInt);
    }
}
/*
Integer Object: 100
Double Object: 45.67
Boolean Object: true

Primitive int: 100
Primitive double: 45.67
Primitive boolean: true

Max Integer: 2147483647
Min Integer: -2147483648
Parsed Integer: 123
*/

Wrapper classes in Java provide a mechanism to treat primitive data types as objects, enabling the use of methods and data structures that require objects. They are essential for data conversion, manipulation, and interacting with Java collections.

Scroll to Top