0Pricing
Java Academy · Lesson

this & toString/equals/hashCode

Use this to refer to the current object, write helpful toString, and implement equals and hashCode correctly.

this & toString/equals/hashCode is a free Java Academy lesson on CoddyKit — lesson 1 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The this keyword

this refers to the current object. Use it to access fields or call another constructor. It helps when parameter names are the same as field names, making your intention clear.

Readable toString

toString() returns a human friendly summary of an object. Override it to show key fields like id and name. This makes logs and debug prints much easier to understand.

equals vs ==

equals checks logical equality, while == checks if two references point to the same object. Most domain classes should override equals to compare by content, not by memory address.

hashCode matches equals

hashCode must be consistent with equals: if a.equals(b) is true, then a.hashCode() must equal b.hashCode(). This rule is required for HashSet and HashMap to work correctly.

Tips and pitfalls

Choose stable fields for equality, like id or email, and keep toString short. Avoid using mutable collections inside equals and hashCode. When unsure, generate methods with your IDE and review them.

Code: this, equals, hashCode

The demo creates two persons with the same content. equals returns true, hash codes match, and a HashSet can find the second object.

public class Main {
  // Simple Person class to demo this, toString, equals, hashCode
  static class Person {
    private int id;
    private String name;

    // Constructor uses this to set fields
    Person(int id, String name) {
      this.id = id;       // this.id refers to the field
      this.name = name;   // name comes from the parameter
    }

    // Human friendly string
    @Override
    public String toString() {
      return "Person{id=" + id + ", name=" + name + "}";
    }

    // Logical equality: same id and same name
    @Override
    public boolean equals(Object o) {
      if (this == o) return true;                 // same reference
      if (o == null || getClass() != o.getClass()) return false;
      Person other = (Person) o;
      if (this.id != other.id) return false;
      // Compare names safely (null aware)
      if (this.name == null) return other.name == null;
      return this.name.equals(other.name);
    }

    // Hash code consistent with equals
    @Override
    public int hashCode() {
      int result = Integer.hashCode(id);
      result = 31 * result + (name == null ? 0 : name.hashCode());
      return result;
    }
  }

  public static void main(String[] args) {
    // Create two persons with the same content
    Person a = new Person(1, "Ada");
    Person b = new Person(1, "Ada");

    // toString shows readable info
    System.out.println(a);

    // equals compares content, not memory address
    System.out.println("a == b ? " + (a == b));           // false (different objects)
    System.out.println("a.equals(b) ? " + a.equals(b));   // true (same content)

    // hashCode must match for equal objects (useful in hash collections)
    System.out.println("hash(a) = " + a.hashCode());
    System.out.println("hash(b) = " + b.hashCode());

    // Example with HashSet: contains works because equals and hashCode agree
    java.util.Set<Person> set = new java.util.HashSet<>();
    set.add(a);
    System.out.println("set contains b ? " + set.contains(b)); // true
  }
}

Contract check

Quick check: If you override equals, what else should you do and why?

Recap

Recap: this clarifies field access, toString helps debugging, equals compares content, and hashCode keeps collections consistent.

Frequently asked questions

Is the “this & toString/equals/hashCode” lesson free?

Yes — the full text of “this & toString/equals/hashCode” is free to read here on the web, and the Java Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “this & toString/equals/hashCode”?

Use this to refer to the current object, write helpful toString, and implement equals and hashCode correctly. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “this & toString/equals/hashCode” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. this & toString/equals/hashCode
  2. Object Composition
  3. Modeling a Domain (UML→Code)
← Back to Java Academy