Monday, January 26, 2009

Autoboxing support C# VB (.NET) vs Java

I am currently doing .NET by day but still teaching Java for UCSD by night. During the last lecture, autoboxing came up. So I thought I would do a simple comparison between .NET and Java on how it handles Autoboxing.


// AutoboxTest.cs
using System;

class AutoboxTest
{
static void Main()
{
Console.WriteLine(22.ToString());
}
}


And like wise in VB


''' AutoboxTest.vb
Module AutoboxTest
Sub Main()
Console.WriteLine(22.toString())
End sub
End Module


So I thought I would give it a try in Java:


public class AutoboxTest
{
public static void main(String args[])
{
System.out.println(((Integer)22).toString());
}
}


Note: I could not get the simple form "22.toString()" to work unless I cast the literal to an Integer first. Score one for .NET.

No real numbers were harmed in this example. The number 22 was chosen because that is my hockey jersey number and paying tribute to the classic movie Casablanca.

2 comments:

d said...

Interesting... Autoboxing sounds like much more of a fancier word than it really is. Never knew what that meant!

Unknown said...

Except that isn't autoboxing, that is simply the result of everything being an object in .Net. Boxing is when a NEW object is created and in C# that is much less common than in Java, particularly since the advent of generics.

Autoboxing is when this object creation is implicit, but auto or manual, it's all the same.

Here is an example of boxing in .Net, which shows the primary danger of boxing, in that you don't necessarily get the answer you expect from some comparisons. The other problem of course being that it's relatively slow and can end up creating a bunch of objects that need to be garbage collected.