almost 11 years ago
INTRODUCTION:
The automatic conversion made by the Java compiler between primitive types and their corresponding object wrapper classes, is known as Autoboxing
It allows us to use primitive and object type interchangeably in Java on many places like assignment, method invocation etc
For example
A primitive type like int gets automatically converted into corresponding wrapper class object e.g. Integer because primitive is boxed into wrapper class.
If the conversion goes the other way, this is called unboxing. Ex.: If Integer object is converted into primitive int.
Benefits of Autoboxing & Unboxing:
Example for Autoboxing :
- class Example1{
- public static void main(String args[]){
- int a=10;
- Integer a2=new Integer(a);//Boxing
- Integer a3=8;//Boxing
- System.out.println("values wil be" + a2+" "+a3);
- }
- }
class Example1{ public static void main(String args[]){ int a=10; Integer a2=new Integer(a);//Boxing Integer a3=8;//Boxing System.out.println("values wil be" + a2+" "+a3); } }
Output: 10 8
Example for unboxing:
output: 100
0 Comment(s)