What is Autoboxing?

Autoboxing is a new feature offered in the Tiger (1.5) release of Java SDK. In short auto boxing is a capability to convert or cast between object wrappers (Integer, Long, etc) and their primitive types.

Previously when placing primitive data into one of the Java Collection Framework object we have to wrap it to an object because the collection cannot work with primitive data. Also, when calling a method that requires an instance of object rather than an int or long, we have to convert it too.

Now, starting from version Java 1.5 we have a new feature in the Java Language which automate this process, its call the Autoboxing. When we place an int value into a collection, such as List, it will be converted into an Integer object behind the scene. When we read it back, it will automatically convert to the primitive type. In most way this simplifies the way we code, no need to do an explicit object casting.

Here an example how it will look like using the Autoboxing feature:

package org.kodejava.basic;

import java.util.HashMap;
import java.util.Map;

public class Autoboxing {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();

        // Here we put an int into the Map, and it accepted
        // as it will be autoboxed or converted into the wrapper
        // of this type, in this case the Integer object.
        map.put("Age", 25);

        // Here we can just get the value from the map, no need
        // to cast it from Integer to int.
        int age = map.get("Age");

        // Here we simply do the math on the primitive type
        // and got the result as an Integer.
        Integer newAge = age + 10;
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.