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?
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.
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?
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