Wrapper classes let us use simple values like numbers and letters as objects. This helps when we need to store or work with these values in special ways.
0
0
Why wrapper classes are used in Java
Introduction
When you want to store numbers or characters in collections like ArrayList that only accept objects.
When you need to convert between strings and numbers or characters.
When you want to use utility methods that come with wrapper classes, like checking if a string is a valid number.
When you need to treat primitive values as objects to use features like synchronization or generics.
Syntax
Java
WrapperClassName variableName = new WrapperClassName(primitiveValue);Wrapper classes have names like Integer, Double, Character, Boolean.
Since Java 5, autoboxing lets you assign primitives directly to wrapper objects without 'new'.
Examples
line_end_arrow_notchCreates an Integer object holding the value 10.
Java
Integer num = new Integer(10);
line_end_arrow_notchAutomatically converts the primitive double 19.99 to a Double object.
Java
Double price = 19.99; // autoboxing
line_end_arrow_notchWraps the char 'A' into a Character object.
Java
Character letter = 'A';Sample Program
This program shows how wrapper classes let us store numbers in an ArrayList and convert strings to numbers easily.
Java
import java.util.ArrayList; public class WrapperExample { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); // Add primitive int values, autoboxed to Integer objects numbers.add(5); numbers.add(10); numbers.add(15); // Print all numbers for (Integer num : numbers) { System.out.println(num); } // Convert String to Integer String str = "123"; int value = Integer.parseInt(str); System.out.println("Parsed value: " + value); } }
OutputSuccess
Important Notes
line_end_arrow_notch
Wrapper classes are immutable, meaning their value cannot change once created.
line_end_arrow_notch
Autoboxing and unboxing make using wrapper classes easier by converting automatically between primitives and objects.
Summary
Wrapper classes let primitive values be used as objects.
They are needed for collections and utility methods.
Autoboxing simplifies working with wrapper classes.
