Card 04/ 09
All 9 cards
ConceptDifficulty: Beginner1 min
Assigning, Comparing Identity, and Comparing Contents
Three things a beginner is told are nearly the same thing and 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 there is no distinction to draw: == compares the values, and that is the only question there is. For anything with a capital letter, == 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, and a test that passes on short strings and fails on long ones is usually this. Reach for .equals whenever you mean "the same value", and keep == for numbers and for null.