Card 04/ 09
= vs == vs equals in Java
Assigning, comparing identity and comparing contents look alike, and only one of them is what you usually mean.
= assigns a value to a variable. == asks whether two variables hold the same thing, which for objects means the very same object. equals asks whether two objects count as equal by the rules of their class. For comparing the contents of two objects, such as two strings, equals is the one you want.
Beginners are told these three are nearly the same, and they are not. Mixing up the first two produces a compiler error; mixing up the second two produces a bug that ships.
| Written | Asks or does | Answer for objects |
|---|---|---|
a = b | Put what b holds into a | Both names now hold the same address |
a == b | Do these two hold the same thing? | Same address: the very same object |
a.equals(b) | Are these two objects equal? | Whatever the class decided equal means |
For a primitive, a variable such as an int that holds its value directly, there is no distinction to draw: == compares the values, and that is the only question there is. For a reference variable, one that holds the address of an object, == asks whether two variables point at one object, which is almost never the question you have.
String typed = new String("yes");
String literal = "yes";
System.out.println(typed == literal);
System.out.println(typed.equals(literal));false
trueSo == on objects is a question about identity, not content. A string comparison that works on text typed into the source and fails on text read from a user or a file is usually this. Reach for equals whenever you mean "the same value", and keep == for numbers and for null.
← → move through sections and cards