About Java memory management [duplicate]
-
25-06-2021 - |
Question
Possible Duplicate:
Integer wrapper objects share the same instances only within the value 127?
I have a question about the memory management in Java.
When I try the following code:
Integer a = 1;
Integer b = 1;
System.out.println(a==b); // this gives "true"
However,
Integer a = 256;
Integer b = 256;
System.out.println(a==b); //this gives "false"
Why?
Thanks very much.
Solution
That is because "autoboxing" uses Integer.valueOf
, and Integer.valueOf
keeps a cache of Integer
objects for small integer values. Here's what the JLS says:
"If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2." JLS 5.1.7.
When you use the ==
operator to compare a pair of Integer
objects, it is actually comparing the object references. So your get true
if boxing gave you the same cached Integer
object, and false
if it didn't. Note that the JLS guarantees this behaviour for the ranges stated, but it also permits an implementation of the valueOf
method to cache a wider range of values.
The bottom line is that you should use equals(Object)
to compare Integer
objects ... unless you are really trying to test if they are the same object.
According to what I read, "Integer" should create an "object" in the heap, thus the two objects should be the same.
If your code explicitly does a new Integer(...)
, it is guaranteed to create a new Integer
object. However, autoboxing uses Integer.valueOf(...)
, and that is where the caching behaviour is implemented.
OTHER TIPS
You shouldn't use reference equality (==
) for objects. It's printing true in your first example because the first 128 Integer
objects are cached by the Integer
class. Use .equals()
When the values greater than range of data representation, they are different object because they are wrapped. You are now coparing like object ids.
You are comparing objects' addresses