Boxing and Unboxing

Table of contents

No heading

No headings in the article.

In Java , every data type is either of type "Reference" or type "Primitive".

Reference Type : Any class , Interface or Array type is considered as Refernce type . Any variable of reference type can be set value "null".

Primitive Type : There are 8 Primitive data types and for each Primitive data type there is respective Reference class associated with it.

image.png

Boxing : Conversion of primitive type to corresponding Reference type . Unboxing : Conversion of the reference type to corresponding primitive type.

Java with generics automatically inserts Boxing and Unboxing at appropriate places .

If an expression e of type int appears where a value of type Integer is expected, boxing converts it to new Integer(e) . If an expression e of type Integer appears where a value of type int is expected, unboxing converts it to the expression e.intValue().

image.png

is equivalent to

image.png

From the below code , we can understand that always ,

  • Type Parameters always are bound to "Reference types".
  • Return types are always "Primitive types".

image.png

== has different meaning for reference types and primitive types.

.So its better to use "equals" instead of == for Reference types(Such as String or Integer). where as in Primitive Types == checks for equality of values.