JAVA :: difference between "==" vs equals()

Java's equality operator "= =" is used for reference comparison. It checks if the both the references point to the same memory location.

In the above example while creating literal String (i.e. s1 & s2), JVM first searches for the occurence of that literal in String pool. If found a match, the same reference will be provided to the new string.

Hence the expression is evaluated as (s1 == s2) ==> True

However for new String("Hello"), the new string will be created in heap memory (and not in String pool) with a new reference.

Hence the expression is evaluated as (s1 == s3) ==> False

Whereas, equals method compares the content of the objects.

Usage of equals() is always recommended. Steps performed during equals() check is performed.

  • First, reference equality is checked (i.e. using "==" Equality operator). if the references match, then no further checks are performed.
  • However, if the reference match (e.g. 2 String references) fails, then the length is compared. If lengths differ, then we know for sure that equality check will fail. Hence no further checks are performed.
  • Only at this point, will actual content comparison take place. It is a short-hand comparison (i.e not all the characters will be compared)