Java – Comparing Primitive to Wrapper Object with == Behavior Explained

boxingequalityequalsjava

I have a piece of code which I need to understand:

public static void main(String[] args) {
    Character c = new Character('a');
    Character cy = new Character('a');
    char cx = 'a';

    System.out.println(c == cx);
    System.out.println(cx == cy);
    System.out.println(c == cy);
}

Output:

true
true
false

I am unable to understand why only the third statement is failing.

EDIT: This question is different to the .equals vs == question as this about primitive versus object comparison.

Best Answer

c and cy refer to different instances of the Character class (each time you invoke a constructor, you create a new instance), so comparing these references returns false.

On the other hand, when you compare either of them to the primitive cx, they are unboxed to char, and the char comparison returns true.

Had you used Character.valueOf('a') instead of new Character('a'), you would have gotten the same instance in both calls, and the reference comparison would have returned true (since valueOf returns a cached Character instance if the argument <= 127).