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.