Tutorials / Tech blog / Geek Zone

Latest Posts

Sunday, April 16, 2017

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)

4 comments:

  1. Thanks, finally I understood what difference does it make, cause I had thought before that its similar things! By the way most of the useful information about Java I read in this service, that have very nice and understandable articles, for example about transient keyword java https://explainjava.com/java-transient/ so if you are beginner you should try it)

    ReplyDelete
  2. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head.
    I am highly impressed with your blog. It is very nicely explained.
    Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.

    ReplyDelete