Infolinks In Text Ads

Nov 27, 2010

autoboxing and unboxing in java

autoboxing and unboxing in java –


autoboxing and unboxing concepts is related to primitive data types and its wrapper classes. If any wrapper class holds the value of its primitive data type called boxing. And if any primitive data type holds the objects of its wrapper class called unboxing.

autoboxing and unboxing in java is two types :
1) Implicit Auto boxing.
2) Explicit boxing.
3) Implicit unboxing.
4) Explicit unboxing.


Implicit Auto boxing –


J2SE 5 was added autoboxing. Autoboxing is internal process where primitive data type automatically encapsulated within their wrapper classes. So there is no need to wrap primitive data type to its wrapper classes. There is really very helpful with in collection framework. Because collections framework allows objects instead of primitive data type.

Example :-

Integer intObj = 786; // Autoboxing
List listObj = new ArrayList();
listObj.add(786); // Autoboxing
listObj.add(787); // Autoboxing

So in this line there is no need to make an object and then explicitly encapsulate the value.


Explicit boxing –


Before J2SE 5, autoboxing was not present then developers was use explicit boxing.

Example –
List listObj = new ArrayList();
listObj.add(new Integer(786)); // Explicit boxing
listObj.add(new Integer(787)); // Explicit boxing


Implicit unboxing (Auto-unboxing) –


J2SE 5 was added unboxing. unboxing is internal process where wrapper classes objects directly converted to primitive data type automatically. So there is no need to convert manually to primitive data types.

Example –
Integer intObj = 786; // Autoboxing
Int intvariable = intObj;
//or
List listObj = new ArrayList();
listObj.add(new Integer(786)); // Explicit boxing
listObj.add(new Integer(787)); // Explicit boxing
int x = listObj.get(0);   //Implicit unboxing
int y = listObj.get(1);   //Implicit unboxing


Explicit unboxing –


Before J2SE 5 , developers was do explicitly unboxing.

Example –
Integer intObj = 786; // Autoboxing
Int intvariable = intObj.intValue();   // Explicit unboxing
//or
List listObj = new ArrayList();
listObj.add(new Integer(786));      // Explicit boxing
listObj.add(new Integer(787));      // Explicit boxing
int x = new Integer(listObj.get(0)).intValue(); // Explicit unboxing
int y = new Integer(listObj.get(1)).intValue(); // Explicit unboxing

1 comment:

  1. Hi,
    Autoboxing is a great feature provided by JAVA5 but using it blindly may result in very subtle problem which will take hours and hours to
    debug and find. to read more see the link
    What is the problem while using '==' in autoboxing world in Java 5 ?

    Thanks
    Javin

    ReplyDelete

LinkWithin

Related Posts Plugin for WordPress, Blogger...