FAQ

Java

JSP

Servlet


Advertisement



Why does the autoboxing conversion sometimes return the same reference?

Although Java programming language is an object-oriented language, in a lot of cases that you would need to deal with primitive types. Before J2SE 5.0, working with primitive types required the repetitive work of conversion between the primitive types and their wrapper classes. In this FAQ, you will see how the new autoboxing feature in J2SE 5.0 handles conversions -- for example, between values of type int and values of type Integer. For example,

class Program { 
public static void main(String[] args) {
Integer i1 = 20;
Integer i2 = 20;
Integer i3 = 201;
Integer i4 = 201;
System.out.println(i1 == i2);
System.out.println(i3 == i4);
}
}

The output is

true
false

What we have discovered is that for small integral values, the objects are cached in a pool much like String pool, refer to XyzWs Java FAQ: What is String literal pool?. When i1 and i2 have the value of 20, they both point to a single object in the cache pool. While i3 and i4 have the value of 201, two separate objects are referenced.

In order to save memory, two instances of the following wrapper objects will always be == when their primitive values are the same (5.1.7 Boxing Conversion in Java Language Specification 3rd Edition):

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Autoboxing is guaranteed to return the same object for integral values in the range [-128, 127], but an implementation may, at its discretion, cache values outside of that range. It would be bad style to rely on this caching in your code. Also, The Java Language Specification does not explicitly guarantee this behavior for long values within the range of a byte.

Creating a wrapper object by using keyword new will return different reference. For example,

class Program { 
public static void main(String[] args) {
Integer i1 = 20;
Integer i2 = new Integer(20);
Integer i3 = new Integer(20);
System.out.println(i1 == i2);
System.out.println(i1 == i3);
}
}

The output is

false
false


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |