What is Boxing and Unboxing?
There are various primitive data types in java such as byte, int, long. etc. We have wrapper classes corresponding to each of the data type in java.
Sometimes the values of primitive data types are needed but in the form of objects. They needs to be wrapped in the form of objects. So here comes the role of wrapper classes . It wraps the value of primitive data types in the form of the objects.
Once we wrap the values by using wrapper classes, we cannot inherit those classes because all the wrapper classes are by default declared as final.
Boxing:
When we convert the value of a primitive data type in the form of objects by referencing it by the wrapper class that corresponds to that type, then it is known as boxing.
e.g. converting an int into Integer type.
suppose we have a variable x.
int x=10;
Integer a=new Integer(x);
This is boxing. i.e wrapping x in the form of Integer object.
Unboxing:
When we convert the value of an Object back to the primitive data type that corresponds to that particular object wrapper class, then it is known as unboxing.
e.g. converting Integer into int or Byte to byte.
suppose we have a variable x.
Integer x= new Integer(10);
int a=x.intValue();
This is unboxing. i.e unwrapping x into primitive data type int.
Example: Demo.java
public class Demo {
public static void main(String[] args) {
int x= 10;
Integer a=new Integer(x); //boxing
x=a.intValue(); //Unboxing
System.out.println(x);
}
}
Output: 10
Autoboxing:
Till JDK1.4 we need to perform boxing and unboxing manually but from JDK 1.5 onwards the process in carried out automatically and so it is known as autoboxing.
e.g.
int i=10;
Integer x=i;
It automatically wraps the primitive type into reference type.
Integer i=new Integer(10);
int x=i;
It automatically does the unboxing also as shown above.
Example: Demo.java
public class Demo {
public static void main(String[] args) {
int a=10;
Integer b=a; // Auto Boxing
int c= b; //Auto Unboxing
System.out.println(c);
}
}
Output:10
Demo1.java
public class Demo1
{
public static void main(String args[])
{
Integer i=0;
Integer sumOfNumbers= 0;
for (i = 0; i < 10; i++) {
sumOfNumbers=sumOfNumbers+i;//Autoboxing
}
}
}
0 Comment(s)