• Post Reply Bookmark Topic Watch Topic
  • New Topic

boxing unboxing  RSS feed

 
rakhee gupta
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Boxing unboxing concept is not getting clear to me.Can anyone refer me a good document on web so that I can go through and get my concept clear.
What exactly is boxing unboxing?
Thanks
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Essentially, boxing is the automatic conversion of a primitive value to a corresponding wrapper instance. Unboxing is the automatic conversion of a wrapper instance to a primitive type. For example...

Without this automatic conversion (boxing and unboxing), you would need to do something like...

See JLS...
  • 5.1.7 Boxing Conversion
  • 5.1.8 Unboxing Conversion
  •  
    Rob Spoor
    Sheriff
    Posts: 21135
    87
    Chrome Eclipse IDE Java Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Originally posted by marc weber:

    Without this automatic conversion (boxing and unboxing), you would need to do something like...

    Technically the first would be Integer.valueOf(17), not new Integer(17). That's also why auto(un)boxing numbers between -128 and 127 (inclusive) will always yield the same objects - those are cached and valueOf returns the cached versions for those values.

    The second line also shows you a possible danger in auto unboxing:
     
    marc weber
    Sheriff
    Posts: 11343
    Java Mac Safari
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Originally posted by Rob Prime:
    ... Technically the first would be Integer.valueOf(17), not new Integer(17)...

    I just meant calling the constructor as an example of getting a wrapper reference from a primitive. But yes, if you wanted to mimic autoboxing's use of cached instances, then valueOf would be the way to do that.
    [ June 16, 2008: Message edited by: marc weber ]
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!