Card 04/ 09

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.

Three operations that look alike and ask different questions
WrittenAsks or doesAnswer for objects
a = bPut what b holds into aBoth names now hold the same address
a == bDo 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.

java
String typed = new String("yes");
String literal = "yes";

System.out.println(typed == literal);
System.out.println(typed.equals(literal));
text
false
true

So == 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.