0

Below code,

package AutoBoxing;

/*
 * When a wrapper type is initialized do you get a new object created?
 * Answer: It depends!!!!
 * 1) If you use a constructor then a new instance will be created.
 * 2) If you use boxing('Integer i = 127'), and the value being boxed is a 
 * boolean, byte, char in the range \u0000 to \u007f, int or short in the 
 * range -128 to 127 then there is a single object. Technical phrase is 'interned'  
 */
public class Example2 {

    public static void main(String[] args) {
        Integer i = 127, j = 127;
        Integer k = new Integer(127);
        System.out.println(i == j); // unboxed values are compared
        System.out.println(i == k); // memory addresses are compared

    }

}

gives

true
false

as output.

true because objects are unboxed and values are compared(127 == 127).

false because memory addresses are compared.

Why unboxing is not done in second case? Because kis also of type wrapper class to primitive?

overexchange
  • 15,768
  • 30
  • 152
  • 347
  • 1
    "true because objects are unboxed and values are compared" - nope, that's not what's happening here. – Jon Skeet Jul 22 '15 at 10:55
  • @JonSkeet memory addresses are compared in first case as well? – overexchange Jul 22 '15 at 10:56
  • Yes. read the duplicate question. – Jon Skeet Jul 22 '15 at 10:57
  • There is no unboxing involved in the first comparison. It is just that when you do `Integer i = 127;`, it's compiled into `Integer i = Integer.valueOf(127);` and hence fetch the instance from the cache (the class has a cache of instances by default from -128 to 127), thus they are the same instances. Try with `Integer i = 128, j = 128; Integer k = new Integer(128);` and you see that it'll output: `false false` – Alexis C. Jul 22 '15 at 10:57

0 Answers0