0

How is Integer x1 = 5; different than Integer x1 = new Integer(5);

Integer x1 = 5; // created through boxing
Integer x2 = 5;
Integer x3 = new Integer(5); // no boxing
Integer x4 = new Integer(5);
if (x1 == x2) System.out.println("Same object"); //prints
if (x3 == x4) System.out.println("Same object"); //doesn't print

This code displays doesn't display Same object twice, as I had expected. Why?

PS: The rule is: in order to save memory, two instances of the following wrapper objects will always be == when their primitive values are the same: Boolean; Byte; Characterfrom \u to \u007f; Short and Integer from -128 to 127

Samy
  • 465
  • 1
  • 10
  • 25
  • 1
    Take a look at http://stackoverflow.com/questions/1514910/how-to-properly-compare-two-integers-in-java – G.S May 29 '15 at 09:49
  • 3
    How can `new Integer(5)` return an already existing object (which it needs to do if you want the same object)? It is called `new` for a reason. – Thilo May 29 '15 at 09:50
  • `Integer x1 = 5;` get compiled to `Integer x1 = Integer.valueOf(5);` – Binkan Salaryman May 29 '15 at 09:50
  • If you are comparing two Integers, use .equals, if you want to make your inequalities clear, write the cast in explicitly: if ((int)x1 < (int)x4) ... ; You can also do: x1.compareTo(x2) < 0 // === x1 < x2 – Shane_Yo May 29 '15 at 09:55
  • for bonus points, also try with `Integer x1 = 5555`. – Thilo May 29 '15 at 11:11

1 Answers1

2
// Prints because of autoboxing ie it converts to integer value.
if (x1 == x2) System.out.println("Same object"); 
/* 
 * Doesn't prints because of creating an object(x3) using Integer wrapper class 
 * which is different from other object x4. ie both are different object 
 * pointing to different memory location in memory.
 */
if (x3 == x4) System.out.println("Same object"); 
Mena
  • 47,782
  • 11
  • 87
  • 106
Shriram
  • 4,343
  • 8
  • 37
  • 64