| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
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
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 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):
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 |