Search code examples
javaparseintautoboxing

Java using Integer.parseInt for comparison


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.


Solution

  • 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