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.
new Object() == new Object()
false? – Bactericide==
does reference comparison; once you recognize that, the answer is trivial. – Astairec
is a reference butc == cx
doesn't do a reference comparison. The question is not the same. – Trophozoitec == cy
returnsfalse
, not whyc == cx
returnstrue
. Granted the OP may be confused on the latter point, but that could have been researched or asked if they applied the knowledge about reference comparison toc == cy
, instead of wrongly assuming that the other comparisons implied it should betrue
. – Astaire