Thursday, February 10, 2011

Boxing

In situations where value types need to be treated as objects, the .NET and Java runtimes automatically converts value types to objects by wrapping them within a heap-allocated reference type in a process called boxing. The process of automatically convert an object to its corresponding value type such as converting an instance of java.lang.Integer to an int is known as unboxing. Below are examples of various situations where boxing occurs in both runtimes.


C# Code
using System;
using System.Collections;

//stack allocated structs also need to be boxed to be treated as objects
struct Point{

//member fields
private int x;
private int y;

public Point (int x, int y){

this.x = x;
this.y = y;

}

public override string ToString(){

return String.Format("({0}, {1})", x, y);

}


}//Point

class Test{


public static void PrintString(object o){

Console.WriteLine(o);

}

public static void Main(string[] args){

Point p = new Point(10, 15);
ArrayList list = new ArrayList();
int z = 100;

PrintString(p); //p boxed to object when passed to PrintString
PrintString(z); //z boxed to object when passed to PrintString

// integers and float boxed when stored in collection
// therefore no need for Java-like wrapper classes
list.Add(1);
list.Add(13.12);
list.Add(z);

for(int i =0; i < list.Count; i++)
PrintString(list[i]);

}

}

Java Code
import java.util.*;

class Test{

public static void PrintString(Object o){

System.out.println(o);

}

public static void PrintInt(int i){

System.out.println(i);

}

public static void main(String[] args){

Vector list = new Vector();
int z = 100;
Integer x = new Integer(300);
PrintString(z); //z boxed to object when passed to PrintString
PrintInt(x); //x unboxed to int when passed to PrintInt

// integers and float boxed when stored in collection
// therefore no need for Java wrapper classes
list.add(1);
list.add(13.12);
list.add(z);

for(int i =0; i < list.size(); i++)
PrintString(list.elementAt(i));

}

}

No comments:

Post a Comment