Video in progress

Junior ☕ Core Java

What is the difference between == and equals()?

== compares values for primitives, and for objects it compares references: whether both are the very same object. equals() compares the contents of objects, if the class overrides it correctly.

📖 Answer

String a = new String("java");
String b = new String("java");

a == b;        // false: two different objects
a.equals(b);   // true: the text is the same

By default Object.equals works the same as ==. String, Integer, LocalDate and records override it. If you don't override it in your own class, two "identical" objects won't be equal.

When == is right:

  • primitives: int, long, char;
  • enum values: status == Status.PAID (each value is unique);
  • when you need to check that it's the very same object.

Be careful with null: name.equals("Ali") throws an NPE if name is null. The safe forms are "Ali".equals(name) or Objects.equals(name, "Ali").