Page 1 of 1

[HD Pg 0, Sec. 3.4.2 - creating-wrapper-objects]

Posted: Sun Dec 29, 2019 3:36 pm
by amannur
Let's say :

Line 1 : int i = 100;
Line 2 : Integer i1 = i;
Line 3 : Integer i2 = 100;

On line 2, will the object be created in heap, with value 100? and this both i1 and i2 will point to the same object?

Thanks
Aniruddha

Re: [HD Pg 0, Sec. 3.4.2 - creating-wrapper-objects]

Posted: Mon Dec 30, 2019 12:22 am
by admin
1. Objects are always created on heap.
2. Reference variable can only point to objects (not to primitives). (Go through Object and References section from the book carefully. Both these points are explained there in detail.)

Since i1 is a reference variable, it can only point to an object (or be null). Therefore, an Integer object containing 100 will be created due to autoboxing on the heap at line 2.
3. Due to caching of Integer objects, i1 and i2 will point to the same object.

Re: [HD Pg 0, Sec. 3.4.2 - creating-wrapper-objects]

Posted: Sun Jan 05, 2020 10:25 am
by amannur
Thank you. It makes sense.