Wrapper Class in Java - Autoboxing And Unboxing
Since Java supports primitive data types which do not inherit the Object class. Hence to convert or wrap data types into objects and to inherit the Object class, java introduces a wrapper class for each and every primitive data type
Primitive Data Type Wrapper Class
byte Byte
boolean Boolean
char Character
short Short
int Integer
float Float
long Long
double Double
There are two main reasons why we need Wrapper classes:
1. Java collections framework such as ArrayList, Map, HashMap, Vector etc. store only object types not primitive type
2. To support synchronization in multithreading
Autoboxing And Unboxing:
Autoboxing:
Implicit Conversion of primitive data types to the object of their respective wrapper classes is known as autoboxing.
For Example: int to Integer, long to Long, char to Character etc.
import java.util.ArrayList;
class Program{
public static void main(String[] args){
int num = 5;
//implicit conversion from int to Integer: Autoboxing
Integer a = num;
ArrayList<Integer> arr = new ArrayList<>();
arr.add(a);
System.out.println(arr.get(0)); //Output: 5
}
}
Unboxing:
It is just the opposite of Autoboxing. Implicitly converting a wrapper class into its corresponding primitive data type is called autoboxing.
For Example: Integer to int, Long to long, Character to char etc.
import java.util.ArrayList;
class Program{
public static void main(String[] args){
Integer a = 5;
//implicit conversion from Integer to int: Unboxing
int num = a;
System.out.println(num); //Output: 5
}
}
Comments
Post a Comment