2
Integer x1 = Integer.parseInt("4");
Integer y1 = Integer.parseInt("4");
Integer x2 = Integer.parseInt("444");
Integer y2 = Integer.parseInt("444");

System.out.println(x1==y1); // true
System.out.println(x2==y2); // false ???

Integer a1 = Integer.valueOf("4");
Integer b1 = Integer.valueOf("4");
Integer a2 = Integer.valueOf("444");
Integer b2 = Integer.valueOf("444");

System.out.println(a1==b1); // true
System.out.println(a2==b2); // false

I understand why the third and fourth output print true and false. This is because valueOf returns an object, and wrapper classes cache objects that have values in the range of -128 to 127. If valueOf is passed any value in that range, it should reuse the object in the cache. Otherwise, it will create a new object.

Now, why does the second output print out false? I thought parseInt returns a primitive, not an object like valueOf does.

Sujatha Girijala
  • 1,141
  • 8
  • 20
  • 1
    because you are auto-boxing it to an `Integer`... – Eugene Jul 31 '18 at 10:59
  • @TimBiegeleisen. I disagree this is a duplicate of that one. It does explain you should compare the `.intValue()` of the Integer-objects, and also gives additional information about it in general. But it fails to answer the actual question asked by the OP. I've therefore voted to re-open. – Kevin Cruijssen Jul 31 '18 at 11:06
  • @KevinCruijssen Refer to the added link discussing the Integer constant pool, which explains the above question. This gets asked over and over again. – Tim Biegeleisen Jul 31 '18 at 11:08
  • As to answer the question. In the [source code of `Integer`](http://developer.classpath.org/doc/java/lang/Integer-source.html) the `.valueOf` method does the following: `return new Integer(parseInt(s, 10, false));`. As you can see, it uses `.parseInt` internally, and putting it in an `Integer`-constructor to create an `Integer`-instance. `.parseInt` does indeed return a primitive: `return parseInt(s, 10, false);`. However, since you save it in an `Integer` field, autoboxing occurs, which implicitly behaves somewhat something similar to the use of the constructor in the `.valueOf` method. – Kevin Cruijssen Jul 31 '18 at 11:11

1 Answers1

3

I thought parseInt returns a primitive, not an object like valueOf does.

parseInt returns an int but you assign it to an Integer variable, which causes auto-boxing. Since an int whose value is 444 is being auto-boxed two times, each time a new Integer instance is created (since the Integer cache cannot be used for that value), so comparing them with == returns false.

If you'll assign the output of parseInt to an int, the comparisons will return true in both cases:

int x1 = Integer.parseInt("4");
int y1 = Integer.parseInt("4");
int x2 = Integer.parseInt("444");
int y2 = Integer.parseInt("444");

System.out.println(x1==y1); // true
System.out.println(x2==y2); // true
Eran
  • 387,369
  • 54
  • 702
  • 768