The equals- and hashCode-methods are used by the Collections Framework . For instance, when you add an item to a Set, the equals method will be used to determine if the item is already in the Set, so it isn't added again. Comparator and Comparable deal with sorting / defining an order, whereas the equals-method just compares whether two objects are equal. You must use the equals method in your code if you want to compare objects instead of references, see the guide on String comparison from the sidebar. You need to override the equals- and hashCode-methods when you want multiple instances of your class to represent the same thing, if you use collections or call equals yourself. Answer from Robyt3 on reddit.com
🌐
W3Schools
w3schools.com › java › ref_string_equals.asp
Java String equals() Method
Java Examples Java Videos Java ... · Compare strings to find out if they are equal: String myStr1 = "Hello"; String myStr2 = "Hello"; String myStr3 = "Another String"; System.out.println(myStr1.equals(myStr2)); // Returns ...
🌐
Baeldung
baeldung.com › home › java › core java › java equals() and hashcode() contracts
Java equals() and hashCode() Contracts | Baeldung
January 8, 2024 - As a result, every Java class implicitly has these two methods.: ... Money income = new Money(55, "USD"); Money expenses = new Money(55, "USD"); boolean balanced = income.equals(expenses) We would expect income.equals(expenses) to return true, ...
🌐
SitePoint
sitepoint.com › blog › java › how to implement java’s equals method correctly
How to Implement Java's equals Method Correctly — SitePoint
November 13, 2024 - It is, in fact, the implementation of the equals method in Java that determines “sameness”. The equals method is defined in Object and since all classes inherit from it, all have that method. The default implementation used in Object checks identity (note that identical variables are equal as well), but many classes override it with something more suitable. For strings, for example, it compares the character sequence and for dates it makes sure that both point to the same day.
🌐
Medium
medium.com › @AlexanderObregon › javas-objects-equals-method-explained-3a84c963edfa
Java’s Objects.equals() Method Explained | Medium
5 days ago - Explore Java's Objects.equals() method, a null-safe solution for object comparison. Learn how it prevents NullPointerException and simplifies your code.
🌐
Stack Overflow
stackoverflow.com › questions › 75521849 › how-to-properly-define-method-equals
java - How to properly define method equals()? - Stack Overflow
... Copypublic class Employee { ... if (o == null || getClass() != o.getClass()) return false; Employee employee = (Employee) o; return id == employee.id && Objects.equals(name, employee.name); }...
🌐
Reddit
reddit.com › r/javahelp › when is the .equals() method actually used in java?
r/javahelp on Reddit: When is the .equals() method actually used in Java?
November 7, 2019 -

This may seem like a basic question, but looking online I haven't been able to actually understand when the .equals() method of a class is actually used, and when you should override it.

It is said you override it to determine logic for identifying when two objects are equal, but when I look at places where we actually compare objects - Comparator and Comparable, these both require you to implement compare()/compareTo() methods (or using the static comparing() method in Java 8) that handle the comparisons, so equals() is never used in them.

I'm trying to understand when I actually need to override the .equals() method, but I can't find an example that shows where it is actually used when overridden!

🌐
Scaler
scaler.com › home › topics › java › what is equals() method in java?
What is equals() Method in Java? | Scaler Topics
January 8, 2024 - “==” operator is a binary equality operator used to compare the primitive data types in Java (like int, short, long, char, boolean, double, float and byte). It also compares the memory location or the references of the two objects stored ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › difference-between-and-equals-method-in-java
Difference Between == Operator and equals() Method in Java - GeeksforGeeks
January 4, 2025 - The main difference is that string equals() method compares the content equality of two strings while the == operator compares the reference or memory location of objects in a heap, whether they point to the same location or not. Example: Java ·
Find elsewhere
Top answer
1 of 11
164
//Written by K@stackoverflow
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<Person> people = new ArrayList<Person>();
        people.add(new Person("Subash Adhikari", 28));
        people.add(new Person("K", 28));
        people.add(new Person("StackOverflow", 4));
        people.add(new Person("Subash Adhikari", 28));

        for (int i = 0; i < people.size() - 1; i++) {
            for (int y = i + 1; y <= people.size() - 1; y++) {
                boolean check = people.get(i).equals(people.get(y));

                System.out.println("-- " + people.get(i).getName() + " - VS - " + people.get(y).getName());
                System.out.println(check);
            }
        }
    }
}

//written by K@stackoverflow
public class Person {
    private String name;
    private int age;

    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        if (obj.getClass() != this.getClass()) {
            return false;
        }

        final Person other = (Person) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }

        if (this.age != other.age) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 53 * hash + this.age;
        return hash;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Output:

run:

-- Subash Adhikari - VS - K false

-- Subash Adhikari - VS - StackOverflow false

-- Subash Adhikari - VS - Subash Adhikari true

-- K - VS - StackOverflow false

-- K - VS - Subash Adhikari false

-- StackOverflow - VS - Subash Adhikari false

-- BUILD SUCCESSFUL (total time: 0 seconds)

2 of 11
29

Overloading vs Overriding

Introducing a new method signature that changes the parameter types is called overloading:

public boolean equals(People other){

Here People is different than Object.

When a method signature remains the identical to that of its superclass, it is called overriding and the @Override annotation helps distinguish the two at compile-time:

@Override
public boolean equals(Object other){

Without seeing the actual declaration of age, it is difficult to say why the error appears.

🌐
Software Testing Help
softwaretestinghelp.com › home › java › how to use .equals method in java – tutorial with examples
How To Use .equals Method In Java - Tutorial With Examples
April 1, 2025 - Java has provided equality and relational operators for comparison between two operands. ‘==’ is an Equality Operator provided in Java to compare if two operands are equal. “==”, “!=”, must be used for testing equality between 2 primitive values. For Example, as seen in the below sample program, two integer operand values i.e.
🌐
Javatpoint
javatpoint.com › java-string-equals
Java String equals()
Java String equals and equalsIgnoreCase methods with method signature and examples of concat, compare, touppercase, tolowercase, trim, length, equals, split, string equals in java etc.
🌐
GeeksforGeeks
geeksforgeeks.org › java › equals-hashcode-methods-java
equals() and hashCode() methods in Java - GeeksforGeeks
July 23, 2025 - Shallow comparison: The default implementation of equals method is defined in Java.lang.Object class which simply checks if two Object references (say x and y) refer to the same Object. i.e. It checks if x == y.
🌐
Codecademy
codecademy.com › docs › java › strings › .equals()
Java | Strings | .equals() | Codecademy
August 27, 2025 - Returns true if two strings are equal in value and false otherwise.
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Implementing equals
Example 1 · The simplest case for implementing equals (and hashCode) is to not use primitive fields or array fields. This is usually not an onerous restriction, because: in general, Collections are preferred over arrays · since only objects can be null, objects are preferred over primitives for modeling optional data · import java.time.LocalDate; import java.util.List; import java.util.Objects; import java.util.Set; /** With respect to implementing equals and hashCode, the simplest case is to simply never use primitive fields or array fields.
🌐
Programiz
programiz.com › java-programming › library › string › equals
Java String equals()
... class Main { public static void main(String[] args) { String str1 = "Learn Java"; String str2 = "Learn Java"; String str3 = "Learn Kolin"; boolean result; // comparing str1 with str2 result = str1.equals(str2); System.out.println(result); // true // comparing str1 with str3
🌐
Medium
medium.com › @AlexanderObregon › understanding-the-difference-between-equals-and-in-java-10a075326720
Understanding the Difference Between equals() and == in Java
April 24, 2024 - String str1 = new String("Hello"); String str2 = new String("Hello"); String str3 = str1; System.out.println(str1.equals(str2)); // Output: true System.out.println(str1.equals(str3)); // Output: true · In this example, str1 and str2 are different ...
🌐
Educative
educative.io › answers › what-is-objectsequals-in-java
What is Objects.equals in Java?
The method should return true, as both the input objects are null. import java.util.Objects; public class main { public static void main(String[] args) { boolean equalityCheck = Objects.equals(null, null); System.out.println("The Objects.equals() ...
🌐
Reddit
reddit.com › r/learnjava › == vs. .equals()??
r/learnjava on Reddit: == vs. .equals()??
July 3, 2020 -

I'm on MOOC.fi and I'm a little confused on why you can't use .equals() when comparing two objects. And on part 5_12.Song programming exercise, I'm confused on why the parameter takes an Object parameter instead of a "Song" type, and then why do we have to typecast the object to compare it?

Top answer
1 of 16
762

In general, the answer to your question is "yes", but...

  • .equals(...) will only compare what it is written to compare, no more, no less.
  • If a class does not override the equals method, then it defaults to the equals(Object o) method of the closest parent class that has overridden this method.
  • If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you're left with the Object#equals(Object o) method. Per the Object API this is the same as ==; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality.
  • Always remember to override hashCode if you override equals so as not to "break the contract". As per the API, the result returned from the hashCode() method for two objects must be the same if their equals methods show that they are equivalent. The converse is not necessarily true.
2 of 16
140

With respect to the String class:

The equals() method compares the "value" inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn't make a difference. Its the "value" (that is: the contents of the character array) inside each String instance that is being compared.

On the other hand, the "==" operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references "refer to" the same String instance then the result of the boolean expression would be "true"..duh. If, on the other hand, the value of both object references "refer to" different String instances (even though both String instances have identical "values", that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be "false".

As with any explanation, let it sink in.

I hope this clears things up a bit.

🌐
Tutorialspoint
tutorialspoint.com › home › java/lang › java object equals method
Java Object Equals Method
September 1, 2008 - In this example, we've created an Integer object with value of 50 and a Float object with same value. Now using equals() method, we compared both the objects and result is printed.