Search code examples
javaintegerwrapperunboxing

Why doesn't Integer objects Unbox when compared with `==` operator?


Because sometimes it gets confusing. Lets say:

Integer start=new Integer(10);
Integer mid=new Integer(10);
Integer end=new Integer(20);
System.out.println(start<end); // gives true
System.out.println(start!=end); // gives true
System.out.println(start==mid); // BAM! gives false

The Objects get unboxed in the first two lines, but the last one works the same way, it compares the reference. Shouldn't it Unbox the objects too. This would only make things simpler(it would, right?), or am I missing something here ?


Solution

  • In Java 1.4, there was no unboxing and so you could write

    Integer x = new Integer (10);
    Integer y = new Integer (10);
    System.out.println(x == y); // false;
    System.out.println(x != y); // true;
    

    And so when they added boxing, and unboxing this code had to work the same way, otherwise they would break backward compatibility.