Initializing wrapper objects

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
niiels93
Posts: 5
Joined: Thu Aug 06, 2020 3:41 pm
Contact:

Initializing wrapper objects

Post by niiels93 »

Hi all,

i have a question about initializing wrapper objects. According to the book this can be done in three ways:
1. by a constructor
2. valueOf() method
3. Autoboxing

If i understand correct:
The first way always makes a new wrapper object and the second and third may make a new wrapper object if its not already available on the heap.

so why does this comparison return false? in my perspective in the code below is first a new Integer object created on the heap and then on the second line i1 should be a cached object and refer to the same location in memory. which should result in a true?

Code: Select all

Integer i2 = new Integer(10);
	Integer i1 = 10;
	
	System.out.println(i2==i1);
tnx in advance!

admin
Site Admin
Posts: 10053
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Initializing wrapper objects

Post by admin »

Actually, the book explains in detail at the beginning itself (section 1.6) that all objects are always created on the heap.
What you seem to be referring to is "cache". The book explains in section 3.4.2 that new creates a new object, while valueOf and autoboxing may return a cached object.

In your example, new Integer(10) is a new object (not in cache). The cache is still empty at this point. When you do i1 = 10, another Integer object is created and put in the cache. If you do another i3 = 10; then the cached Integer object will be returned and i1 = i3 will return true.
If you like our products and services, please help us by posting your review here.

niiels93
Posts: 5
Joined: Thu Aug 06, 2020 3:41 pm
Contact:

Re: Initializing wrapper objects

Post by niiels93 »

Oké so to confirm my thoughts:when the valueOf method or autoboxing is used and there is no cached object available on the heap it creates a new object en store it in the cache. So the next time when valueOf or autobox method is used with the same parameter value, the object is picked from the cache. The autobox method and valueOf method are using the same cache, im i correct?


Code: Select all

    
    Integer i1 = new Integer(10);   	// creates a new object
    Integer i2 = 10;                	// creates a new object and store it in the cache
    Integer i3 = Integer.valueOf(10);	// returns object from the cache
	
    System.out.println(i1==i2); 	// false
    System.out.println(i2==i3);    	// true

tnx

admin
Site Admin
Posts: 10053
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Initializing wrapper objects

Post by admin »

That is correct.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 41 guests