Reputation: 212
When I write:
Integer i = 5;
Integer i = new Integer(5);
Are these two lines equal?
In the memory the type i
will be allocated in the heap as the same way in those two lines? And if yes, how all of this happens in the memory?
Upvotes: 0
Views: 393
Reputation: 338416
The Answer by Andy Turner is correct, and should be accepted. I can add a couple more thoughts and a diagram.
Integer
constructor to be removedBe aware that the constructors for all the primitive wrapper classes ( Integer
, Long
, Float
, etc.) are not only deprecated, as of Java 16 & 17 they are marked for eventual removal. See JEP 390: Warnings for Value-Based Classes.
So, while interesting technically, this Question is moot practically.
new
means newTo sum up Turner’s Answer: new
means new. Calling the constructor via new
always results in a new object being instantiated. This means a bit more memory taken to hold each new object.
Integer
objectsThe other two avenues, using a numeric literal or calling Integer.valueOf
, may reuse an existing object cached by the JVM. Using a cache conserves memory.
Here is a decorated screenshot of a debugger showing the result of calling toString
on each of these three approaches. We can see that x
(numeric literal) and y
(valueOf
factory method) both point to the same object. Meanwhile, z
(new
constructor) points to a different object.
(The 42
& 7
were added for dramatic effect, to emphasize that the cache is a pool of possibly many objects. This actual code as shown would not have produced those objects.)
Upvotes: 1
Reputation: 140319
Are these two lines equal?
No.
The first line is the same as
Integer i = Integer.valueOf(5);
The compiler rewrites the code to that, which is known as autoboxing.
Refer to the Javadoc for Integer.valueOf
:
If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
So, Integer.valueOf(5) == Integer.valueOf(5)
(it's the same instance returned each time) whereas new Integer(5) != new Integer(5)
(a new instance is created each time).
But in all cases - as with all objects in Java - the Integer object is on the heap.
Upvotes: 10