Boxing and unboxing

What's boxing anyway?

Every type in Java is either a reference type or a primitive type. A reference type is any class, instance, or array type. All reference types are subtypes of class Object, and any variable of reference type may be set to the value null. There are eight primitive types, and each of these has a corresponding library class of reference type. The library classes are located in the package java.lang.

Primitive : Reference Mapping
byte : Byte
short : Short
int : Integer
long : Long
float : Float
double : Double
bool : Boolean
char : Character

Conversion of a primitive type to the corresponding reference type is called boxing and conversion of the reference type to the corresponding primitive type is called unboxing.

But what's autoboxing?

Autoboxing / unboxing is the automated under the covers conversion between primitive types and their equivalent object types. For example, the conversion between an int primitive and an Integer object or between a boolean primitive and a Boolean object. This was introduced in Java 5.

// Assigning primitive type to wrapper type : Boxing
   Integer iWrapper = 10;

 // Assigning object to primitive : Unboxing
   public void intMethod(Integer iWrapper){
      int iPrimitive = iWrapper;
   } 

The basic differences between primitive and reference types

  • Primitive types are typically fast and lightweight - they have a small memory footprint. Object equivalents are heavyweight and can burden the VM if created in large numbers.
  • Primitive types are not objects - they are not polymorphic and cannot exhibit any object behavior. Object equivalents behave polymorphically (the numeric ones form an inheritance hierarchy derived from java.lang.Number) and exhibit useful behaviour - e.g. Integer.compareTo(Integer).
  • Primitive types are passed by value into methods. Object equivalents are passed by reference.
  • Primitive types are not reference counted or garbage collected. Object equivalents are.
  • Primitive types are mutable. Their object equivalent classes are all immutable.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

manveen

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today