Tuesday, January 17, 2012

Box with J2SE 5.0

Wondering what Boxing's got to do with Java? And I didn't mean Laila Ali, the first woman to win a World Boxing Council title, either! You wouldn't like to mess with her, would you?

So, what is Boxing in Java? Boxing refers to the automatic conversion from a primitive to its corresponding wrapper type: Boolean, Byte, Short, Character, Integer, Long, Float or Double. Since this happens automatically, it's also referred to as autoboxing. The reverse is also true, ie. J2SE 5.0 automatically converts wrapper types to primitives and is known as unboxing.

Before you can try out this simple example, you must install and set the environment variables 'path' and 'classpath' for J2SE 5.0.

The example is quite trivial and you could try compiling it with an earlier version of J2SE, to see the compilation errors flagged out.

public class BoxingUnBoxing
  public static void main(String[] args)
    // Boxing
    int var = 10;
    Integer wInt = var;
    int result = var * wInt;
    System.out.println("Value of result = " + result);

    // Unboxing
    int conv = wInt;
    if (conv < 100)

Boxing and Unboxing save us the bother of converting from a primitive to it's wrapper and vice-versa. This feature is definitely a time-saver :) :)

No comments: