The Plain Picture#
Two identical twins: are they "the same person"? No. Are they "equal" in looks? Yes. Two different questions — and Java makes you pick which one you're asking.
The Real Names#
==asks identity: "are these two references pointing to the same object?" (For primitives, it compares values.)equals(...)asks equality: "do these two objects represent the same value?"Every class inherits a default
equalsfrom Java's root classObject— and the defaultequalsis just==.String,Integerand the collection classes replace it with a content comparison. Your own classes don't, until you write one.
Student a = new Student("Priya", 200);
Student b = new Student("Priya", 200);
a == b // false — two objects
a.equals(b) // ALSO false — Student hasn't defined equals, so it's still identityHow to write equals correctly — and its partner hashCode, and the contract between them that HashMap depends on — needs inheritance,
so it's in Object-Oriented Programming (and why it matters for hash maps is in Collections, From the Inside).
toString — how an object prints#
Printing an object calls its toString() method. The default one prints the class name and a hash code — useless:
System.out.println(new Plain()); // Demo$Plain@8c3b9dDefine your own and printing becomes readable (the @Override marker is explained in Object-Oriented Programming):
@Override
public String toString() {
return name + "(" + score + ")";
}
// System.out.println(priya); → Priya(200)Readable toString methods make debugging and logs far easier. Records (Ch 5) generate one for you.
Check yourself
3 questions== vs equals in one sentence each.
Show answerHide answer
== checks whether two references point to the same object; equals checks whether two objects are logically equal.
For your own class with no equals method, what does a.equals(b) do?
Show answerHide answer
The same as a == b — the inherited default from Object.
What does printing an object with no toString show?
Show answerHide answer
The class name, @, and a hex hash code, like Demo$Plain@8c3b9d.