Tag Archives: unboxing

java.lang.Byte, Short, Integer, Long, Character (boxing and unboxing)

by Mikhail Vorontsov

In this article we will discuss how boxing and unboxing is implemented in Java 1.5+ and what implications has such implementation. There are no differences between Java 6 and 7 implementations.

Boxing is a process of conversion of primitive type variable into java.lang.Number subclass (Java.lang.Byte, Short, Integer, Long, Float, Double). Boxing is done via valueOf method. For example, for Integer it is:

1
static Integer valueOf( int i )
static Integer valueOf( int i )

Unboxing can be done from any of java.lang.Number subclasses to any primitive type. This is done via set of methods defined in java.lang.Number:

1
2
3
4
5
6
7
8
9
10
public abstract int intValue();
public abstract long longValue();
public abstract float floatValue();
public abstract double doubleValue();
public byte byteValue() {
    return (byte)intValue();
}
public short shortValue() {
    return (short)intValue();
}
public abstract int intValue();
public abstract long longValue();
public abstract float floatValue();
public abstract double doubleValue();
public byte byteValue() {
    return (byte)intValue();
}
public short shortValue() {
    return (short)intValue();
}

Implications on performance

There is a common mistake done while converting String to a primitive value type. Which method is better to use: parse*(String) or valueOf(String)? The answer is parse* (parseInt, parseLong and so on). It returns a primitive value. Remember that all valueOf methods return an Object (though it may be cached sometimes – see below).

Continue reading