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, abyte, acharin the range \u0000 to \u007f, or anintorshortnumber 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
Most Recent java Faqs
- How to avoid an java.util.ConcurrentModificationException with ArrayList?
- How to convert a given array to a list in Java?
- How to make Java objects eligible for garbage collection?
- What are local variables in Java?
- What are instance variables in Java?
- How many backslashes?
- What are class variables in Java?
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(24745)
- What is runtime polymorphism in Java?(18326)
- How to add BASIC Authentication into HttpURLConnection?(16083)
- What is String literal pool?(14754)
- Can the run() method be called directly to start a thread?(13991)
- What does Class.forname method do?(10593)
- Can transient variables be declared as 'final' or 'static'?(10445)