Saturday, February 24, 2007

Autoboxing/Unboxing

This is how you would create an Integer with the int value 34 and then convert it back into an int before Java 1.5.

J2SE 1.4.2 code:
public class Boxing {
    public static void main(String[] args) {
        Integer i = new Integer(34);
        int j = i.intValue();
        System.out.println(j); // 34 
    }
}

With Java 1.5, you simply do not worry about the details anymore...

J2SE 1.5.0 (Tiger) code:
public class Boxing {    
    public static void main(String[] args) {
        Integer i = 34;
        int j = i;
        System.out.println(j); // 34
    }
}
The above program is "syntactic sugar" that translates into:
public class Boxing {    
    public static void main(String[] args) {
        Integer i = Integer.valueOf(34);
        int j = i.intValue();
        System.out.println(j); // 34
    }
}

Notice the public static Integer valueOf(int i) method, introduced in Java 1.5, is used instead of the Integer() constructor. The public static Integer valueOf(int i) method is a static factory method. A static factory method is a static method that returns an instance of the class (Bloch 2001:5). Creation and reclamation of small objects is cheap (Bloch 2001:15). Integers are not heavyweight objects — they are extremely lightweight. But this is probably done to avoid creating many duplicate objects. And creating duplicate objects should be avoided (Bloch 2001:13). So Integer caches values.

The following does not work:

public class Boxing {
    public static void main(String[] args) {
        Integer i = 73;
        Long l = i; // error: incompatible types
    }
}

No comments: