| Author |
Boxing,autoboxing,unboxing
|
maddy saddy
Greenhorn
Joined: Mar 13, 2007
Posts: 5
|
|
Anyone please explain Boxing,autoboxing and unboxing in detail. I was unable get a clear cut view(even after reading K&B) on this topic. I appreciate your help. Thanks.
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Can you tell us specifically what your questions are? Are there certain code examples that you're questioning? (We could write a whole chapter going into detail... ) In the meantime, try this Autoboxing article.
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
Chandra Bhatt
Ranch Hand
Joined: Feb 28, 2007
Posts: 1707
|
|
Originally Posted By Maddy Saddy
Anyone please explain Boxing,autoboxing and unboxing in detail. I was unable get a clear cut view(even after reading K&B) on this topic. I appreciate your help.
We have primitive date types to work with but alas we were not allowed to work with Collection using primitive data types where objects are required. What is Wrapper? : You know the class encapsulates member variables and methods to work on with, the same goes with wrapper, wrappers encapsulate corresponding primitive data type. Boxing is simply meaning of encapsulating particular primitive to the corresponding class. Integer i1 = new Interger(12); Now i1 is a reference varaible that refers to a Integer wrapper object that encapsulates 12 (int primitive value). We can use this Integer reference whereever Object is required to be use in the collections. More enhanced facility: With Java 5.0 onwards we have one great facility and that is autoboxing. You need not to use new to create object of corresponding primitive; you simply write Integer i1=12; and that is equivalent to Integer i1 = new Integer(12); **Note except subtle issues related to creating wrapper Byte,Short,Character,Integer using new or compile time constant as you see Integer i1 =12; //compile time constant One exception : You may know integral wrappers I mentioneds above; if they encapsulate same value (within 127) they would give true in equality test. This is another issue. Unboxing: Integer i1 = new Integer(12); int a = i1; //No problem, unboxing is done Unboxing means, extract the primitive member value from the object; In our case it is happening the same; 12 is extracted from the Integer object and assigned to primitive int a; int a = i1; is equivalent to int a = i1.intValue(); But who cares to do that when unboxing takes place automatically. Boxing: Integer i1 = new Integer(12); Autoboxing: Integer i1 = 12; Unboxing: int a = i1; Hope this clarifies your doubts, Thanks and regards, cmbhatt
|
cmbhatt
|
 |
maddy saddy
Greenhorn
Joined: Mar 13, 2007
Posts: 5
|
|
Thanks alot Chandra. Now the picture seems to be clear for me on boxing.
|
 |
 |
|
|
subject: Boxing,autoboxing,unboxing
|
|
|