What are the differences between == and equals() in Java?

When we think about object equality then immediately == or equals() comes in our mind. It is really important to know about the differences between these two. Improper use of these two methods will lead us to erroneous code. Let us understand the differences from the point of view of Object and String.

From Object class point of view:

  • If the class does not override equals() method, then it defaults to the equals(Object o) method of the closest parent class that has overridden equals() method
  • If none of the parent classes provide an override, then it defaults to the ultimate parent class, Object. So it will use the Object#equals(Object o) method. According to the Object API this is the same as ==. It returns true if and only if both variables refer to the same object. It will test for object equality and not functional equality.
  • You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable. (Joshua Bloch)
  • Object class equals() method

        public boolean equals(Object obj) {
            return (this == obj);
        }
       

From String class point of view:

  • The equals() method compares the "value" inside two String instances irrespective of the two object references refer to the same String instance or not. If two object references refer to the same String instances then it will return true. If two object references refer to the different String instances then it will still return true.
  • The “==” operator compares the value of two object references to see whether they refer to the same String instance. The result would be “true” if both the object references “refer to” the same String instance with same value. The result would be false if both the object references “refer to” the different String instance even after having same value.
  • String class equals() method

        public boolean equals(Object anObject) {
            if (this == anObject) {
                return true;
            }
            if (anObject instanceof String) {
                String aString = (String)anObject;
                if (coder() == aString.coder()) {
                    return isLatin1() ? StringLatin1.equals(value, aString.value)
                                      : StringUTF16.equals(value, aString.value);
                }
            }
            return false;
        }