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 uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?