In Java, a wrapper class makes it easier to turn a primitive into an object and an object into a primitive. Autoboxing and unboxing transform primitives automatically into objects and objects into primitives. Primitive is automatically transformed into an object is referred to as unboxing and autoboxing.
Need of Wrapper Class:
Java is an object-oriented programming language, so We need to deal with objects many times like in Collections, Serialization, Synchronization, etc.
Let's see where we need to use the wrapper classes.
Change the value in method:
Java Supports only call by value. So, if we pass a Primitive value, it will not change the original value. But, if we convert the primitive value in an object, it will change the original value.
Serialization:
If we have a primitive value, we can convert it in Objects through the wrapper classes then perform Serialization.
Synchronization:
Java synchronization works with objects in Multithreading.
Java.util package:
The java.util package provides the utility classes to deal with objects.
Collections:
Java collection framework works with objects only. All classes of the Collection framework ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque deal with objects.
Autoboxing
The automatic conversion of primitive data type Into its corresponding wrapper class is known as Autoboxing.
public class WrapperExample {
public static void main(String args[]){
int a=20;
Integer i=Integer.valueOf(a); //converting int into Integer explicitly
Integer j=a; //autoboxing
System.out.printin(a+" "+i+" "+j);
}
}
Unboxing
It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type.
public class Unboxing {
public static void main(String[] args){
Character ch = 'a';
// unboxing - Character object to primitive
char a = ch;
System.out.println(a);
}
}
Commentaires