What is Boxing & AutoBoxing?
- Java Uses primitive types such as byte,short,int,long,float,double,char and boolean, to hold the basic data type supported by the language.
- And thus,the primitive types are not part of the Object hierarchy, and they do not inherit Object.
- primitive types are used for the sake of performance. Despite the performance benefit, there are times when you will need an object representation.
Eg. You can’t pass a primitive type by reference to a method. though many of the standard data structures implemented by java operate on objects. - So, Java provides type wrappers, which are classes that encapsulates a primitive type within an Object.
- Type wrappers are Byte, Short,Integer,Long, Float, Double, Character,Boolean. that provide wide ranage of methods that allow you to fully integrate the primitive types into java object hierarchy.
Methods available:
byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()
char charValue()
boolean booleanValue()
Demonstrate a type wrapper.
class Wrap {
public static void main(String args[]) {
Integer iOb = new Integer(100);
int i = iOb.intValue();
System.out.println(i + " " + iOb); // displays 100 100
}
}
Boxing -> The process of encapsulating a value within an object is called Boxing.
Integer iOb = new Integer(100);
Unboxing -> The process of extracting a value from a type wrapper is called UnBoxing.
int i = iOb.intValue();
Demonstrate a autoboxing/unboxing.
class AutoBox {
public static void main(String args[]) {
Integer iOb = 100; // autobox an int
int i = iOb; // auto-unbox
System.out.println(i + " " + iOb); // displays 100 100
}
}
Autoboxing is the process by which a primitive type is automatically encapsulated(boxed) into its equivalent type wrapper whenever an object of that type is needed. even no need to explicitly construct an object.
Integer iOb = 100; // autobox an int
Auto-unboxing is the process by which the value of a boxed object is automatically extracted(unboxed) from a type wrapper when its value is needed. There is no need to call method such as intValue(), or doubleValue().
int i = iOb; // auto-unbox
Recent Comments