Search code examples
javaintegerboxingunboxing

How the comparisons are taking place in the code below


public class Application {
    public static void main(String[] args) {
        Integer a = new Integer(10);
        Integer b = new Integer(10);
        int x = new Integer(10);
        int y = new Integer(10);
        int p = 10;
        int q = 10;

        System.out.println(a == b);
        System.out.println(a == x);
        System.out.println(x == p);
        System.out.println(b == q);
        System.out.println(y == q);
        System.out.println(x == y);

    }
}

The above code produces the output:

false
true
true
true
true
true
  1. Please explain the process of primitive type getting compared to a reference type using == ?
  2. how int x = new Integer(10); getting evaluated internally?

Solution

  • Integer a = new Integer(10);
    Integer b = new Integer(10);
    

    a==b ---> Reference variable a is compared to the reference variable b. Not the object they point to. And those two reference variables are indeed, different. Hence, false. Use .equals() to compare objects.

    a==x ---> auto-unboxing. x contains the value 10. during comparison, Integer is compared to int. When wrapper is compared to premitive, auto-unboxing occurs. a becomes an int. And so, effectively 10 is compared to 10. Hence true.

    x==p,b==q,y==q,x==y --> Same. Auto-unboxing, taking effect. Hence all true.

    Whenever Java compares a wrapper class variable with a primitive variable, it unboxes the wrapper class variable into a primitive, and then compares them.

    Compile this with SDK previous to Java 5, and I doubt if it would compile at all. Java introduced this feature from Java 5. If I can remember correctly..