Wrapper Class in Java
Wrapper Class in java
- The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.
A Wrapper class in Java is a class whose object wraps or contains primitive data types.
When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with objects many times like in Collections, Serialization, Synchronization.
- Serialization: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in objects through the wrapper classes.
( Serialization in Java is a mechanism of writing the state of an object into a byte-stream.)
- Synchronization: Java synchronization works with objects in Multithreading.
- java.util package: The classes in java.util package handles only objects and hence wrapper classes help in this case also.
- Collection Framework: Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
Advantages of Wrapper Classes
- Collections allowed only object data.
- On object data we can call multiple methods compareTo(), equals(), toString()
- Object data allowed null values.
- Serialization can allow only object data.
Autoboxing and Unboxing
1. Autoboxing
The automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double, etc.
2. Unboxing
It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double, etc.
Comments
Post a Comment