Thursday, June 6, 2013

Boxing

Conversion of a value type to a reference type is termed as Boxing.

For example int is a value type, when we try to assign an int to an object, it gets converted to a reference type this is called boxing. When a value type is converted into a reference type it will be moved to the Heap. Stack is more efficient than Heap, hence we should avoid Boxing as much as possible.

The following example causes Boxing to happen.
int nAge = 10;
Object objAge = nAge; // Boxing occurs here.

Allocation of an object into Heap involves more work, since the object needs to be placed in the heap and a reference to the object needs to be added to the stack. Also when the object moves out of scope the reference will get deleted, but the actual object will still remain in memory till the Garbage collector clears the object. Hence we should not perform a Boxing operation unnecessarily.

Search Flipkart Products:
Flipkart.com

No comments: