A wrapper class in Java is an object representation of primitive data types. Wrapper classes allow primitive types (e.g., int
, double
) to be treated as objects.
Examples of Wrapper Classes:
Primitive Type | Wrapper Class |
---|---|
int |
Integer |
char |
Character |
double |
Double |
float |
Float |
boolean |
Boolean |
byte |
Byte |
short |
Short |
long |
Long |
Why Do We Need Wrapper Classes?
-
Object Requirement:
- Many Java classes (e.g.,
Collections
framework) work only with objects, not primitives. Wrapper classes allow you to use primitive values as objects.
12List<Integer> numbers = new ArrayList<>(); // Works with Integer, not intnumbers.add(10); // Autoboxing converts int to Integer - Many Java classes (e.g.,
-
Utility Methods:
- Wrapper classes provide useful utility methods like parsing strings to numbers.
1int number = Integer.parseInt("123"); // Converts string to int -
Default Values in Generics:
- Generic types in Java can only accept objects. Wrapper classes allow you to use primitives in generics.
1List<Double> list = new ArrayList<>(); // Double instead of double -
Null Representation:
- Primitives cannot hold
null
, but wrapper objects can.
1Integer nullableValue = null; // Works - Primitives cannot hold
-
Type Conversion:
- Wrapper classes allow easy conversion between types.
12Integer i = 10;double d = i.doubleValue(); // Convert Integer to double -
Immutability:
- Wrapper objects are immutable, ensuring safety in multi-threaded environments.
Key Features:
-
Autoboxing and Unboxing:
- Autoboxing automatically converts primitives to their wrapper objects.
- Unboxing automatically converts wrapper objects back to primitives.
12Integer obj = 10; // Autoboxingint primitive = obj; // Unboxing -
String Parsing:
- Converting strings to numbers or vice versa is simplified.
12int num = Integer.parseInt("42"); // String to intString str = Integer.toString(42); // int to String
Example Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class WrapperExample { public static void main(String[] args) { // Autoboxing Integer num = 5; // int to Integer System.out.println("Wrapper Object: " + num); // Unboxing int primitive = num; // Integer to int System.out.println("Primitive Value: " + primitive); // Utility method: Parsing a String String str = "123"; int parsedNum = Integer.parseInt(str); System.out.println("Parsed Number: " + parsedNum); // Storing primitive types in a collection List<Double> doubles = new ArrayList<>(); doubles.add(3.14); // Autoboxing doubles.add(2.71); System.out.println("List of Doubles: " + doubles); } } |
Conclusion:
Wrapper classes bridge the gap between primitives and objects in Java. They are essential for working with frameworks, collections, and generics that require objects. They also provide additional utility methods for parsing, type conversion, and more.