Primitive und Klassentypen

exercise No. 253

F:

We consider an Integer to Long comparison:

Code
final Integer x = 44;
final Long    y = 44L;
System.out.println("x.equals(y): " + (x.equals(y)));

final int  a = x;
final long b = y;
System.out.println("     a == b: " + (a == b));
Result
x.equals(y): false
     a == b: true

Answer the following questions:

  1. Why do we get x.equals(y): false ?

  2. Why do we a get a == b: true resulet despite the comparison on the defining variables x and y yields false ?

Hints:

  • How is equals() being implemented with respect to instances of other classes?

  • How do the assignments a = x and b = y actually work?

A:

  1. Instances of different classes will generally return false when being compared by equals(...): A typical equals(...) implementation for a given class X reads:

    publix class X {
      public boolean equals(Object other) {
          if (! other instanceOf X) {
             return false;
          } else {...}
    }

    The result might be true if the two classes in question are being reated by inheritance. But besides sharing the common Number ancestor this is not the case for Integer and Long.

  2. The two assignments and b = y use the unboxing mechanism:

    a = x

    Convert an instance of Integer to its corresponding primitive intValue().

    b = y

    Convert an instance of Long to its corresponding primitive longValue().