What’s the difference between equals() and ==?

Before discussing the difference between “==” and the equals() method, it’s important to understand that an object has both a location in memory and a specific state depending on the values that are inside the object.

The “==” operator

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location. A very simple example will help clarify this:


String obj1 = new String("xyz");

String obj2 = new String("xyz");

if(obj1 == obj2)
   System.out.println("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");
    

Take a guess at what the code above will output. Did you guess that it will output obj1==obj2 is TRUE? Well, if you did, then you are actually wrong. Even though the strings have the same exact characters (“xyz”), The code above will actually output:

 obj1==obj2 is FALSE

The “==” operator compares the objects’ location(s) in memory

Are you confused? Well, let us explain further: as we mentioned earlier, the “==” operator is actually checking to see if the string objects (obj1 and obj2) refer to the exact same memory location. In other words, if both obj1 and obj2 are just different names for the same object then the “==” operator will return true when comparing the 2 objects. Another example will help clarify this:

String obj1 = new String("xyz");

// now obj2 and obj1 reference the same place in memory
String obj2 = obj1;

if(obj1 == obj2)
   System.out.printlln("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

Note in the code above that obj2 and obj1 both reference the same place in memory because of this line: “String obj2 = obj1;”. And because the “==” compares the memory reference for each object, it will return true. And, the output of the code above will be:

obj1==obj2 is TRUE

The equals() method

Now that we’ve gone over the “==” operator, let’s discuss the equals() method and how that compares to the “==” operator. The equals method is defined in the Object class, from which every class is either a direct or indirect descendant. By default, the equals() method actually behaves the same as the “==” operator – meaning it checks to see if both objects reference the same place in memory. But, the equals method is actually meant to compare the contents of 2 objects, and not their location in memory.


So, how is that behavior actually accomplished? Simple – the equals class is overridden to get the desired functionality whereby the object contents are compared instead of the object locations. This is the Java best practice for overriding the equals method – you should compare the values inside the object to determine equality. What value you compare is pretty much up to you. This is important to understand – so we will repeat it: by default equals() will behave the same as the “==” operator and compare object locations. But, when overriding the equals() method, you should compare the values of the object instead.

An example of the equals() method being overriden

The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal. Here is an example that will help clarify this:

String obj1 = new String("xyz");

String obj2 = new String("xyz");

if(obj1.equals(obj2))
   System.out.printlln("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");


This code will output the following:

obj1==obj2 is TRUE

As we discussed, Java’s String class overrides the equals() method to compare the characters in a string. This means that the comparison between the 2 String objects returns true since they both hold the string “xyz”. It should now be clear what the difference is between the equals() method and the “==” operator.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

FOLLOW Varoon Sahgal, Author of ProgrammerInterviewon

39 Responses to “Java: What’s the difference between equals() and ==?”

  1. Ankita Monga Sharma says:

    Awsome piece of text superlike

  2. Neha says:

    Sometimes == gives illusions of comparing String values, in following cases

    String a=”Test”;
    String b=”Test”;
    if(a==b) ===> true

    This is a because when you create any String literal, JVM first searches for that literal in String pool, if it matches, same reference will be given to that new String, because of this we are getting

    (a==b) ===> true

    String Pool
    b —————–> “test” false

  3. Gopinath M B says:

    Please note that for primitive variables we must always use ‘==’ because they are not associated with any class or object. Primitive variables will not have any class to associated with it so no question of any ‘equals()’ method to it.
    int x;
    (x % 100) ===> will be some integer value and hence u cant like if(10.equals(0)) // Compiler error since we can call methods only on objects!!!
    If you really wnat to use equals() method then you should go for wrapper classes i.e for int it is java.lang.Integer class
    I think u got it :)

  4. venky says:

    You couldn’t pick more wrong example to explain the difference between ==, and equals().

  5. Das says:

    Awesome explanation. Thanks dude

  6. crime_master_gogo says:

    this is awesome explanation. kudos

  7. Salma Hassan says:

    Thank you very much for this helpful article , but I have a question please :

    I used to use == always like
    if ( x % 100 == 0 )
    so why I didn’t have any errors ?!

    and another question please I still didn’t understand well when I should use == or equal() ?!

    Thank you again!

  8. Deepak Rastogi says:

    mr.artem So what java using string pool so if u have a 2 object then string pooll another using new pool making.
    and let us consider carefully
    if u have first obj1,and second obj2 then the jvm using diffrent diffrent string pool.

    check it now JVM

  9. Muhammad Shahrukh Khan says:

    False

  10. Arundev Puthenpurayil says:

    String s1=new String(“xyz”);
    String s2=new String(“xyz”);

    sop(s1==s2) will print false

    you can make s2==s2 true only if you call the intern() method

    String s1=new String(“xyz”).intern();
    String s2=new String(“xyz”).intern();

    sop(s1==s2) will print true.

  11. Abhi says:

    Yes it is supposed to be false

  12. Nikhil says:

    Great Job done…Thanks a Ton

  13. yo sign says:

    thanks

  14. prasanth says:

    awesome man

  15. Amit says:

    thanks :-) good example..

  16. Mariam says:

    Good explanation…Thanks!

  17. bashu says:

    This is a very good explanation. Thanks Dude

  18. Siqi Liu says:

    do you mean

    “but
    S.o.p(s1==s2))->>>>false? “?

  19. rahul says:

    true,because here create only reference of String not provide memory (because memory provided by new operator) so "run time" the s1 will be compare with s2's content and here the content are same so both s1 and s2 refer to same memory address
    if
    String s1=new String("xyz");
    String s2=new String("xyz");
    S.o.p(s1.equals(s2));->>>>true
    but
    S.o.p(s1==s2))->>>>true

  20. Marcelo Aravena says:

    Hello Artem, this is because Java use an String Pool since you didn't use new, so then Java use this pool and put the literal "xyz" that's why when comparing with == in fact it is the same memory location.
    Please read these examples in this site for a more clear explanation: http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3

  21. sac says:

    thnx varoon18…it helped me a lot

  22. james says:

    <a href=¨http://stringpool.com¨>Nice post Sir, Thanks a lot !!!</a>

  23. Artem says:

    However.
    String s1 = "xyz";
    String s2 = "xyz";
    System.out.print(s1==s2) ->>> True

  24. bern says:

    Lets say first input is Hi and 2nd input is also Hi .. what I dont understand is when I input 2 strings and and compare them using result=a.compareTo(b), I dont know if how "if(a<0){print("a is less than b")}" respond to this comparison, and lets say that the output is "a is less than b" .. why is that?

  25. Kas says:

    Have better idea.. thanks

  26. varoon10 says:

    Will do that soon, thanks Shady!

  27. varoon10 says:

    Thanks Prakash!

  28. varoon10 says:

    Thanks Teju!

  29. varoon10 says:

    Thanks Anand!

  30. varoon10 says:

    Thanks Naidu!

  31. Anand says:

    superb Example

  32. k ashok says:

    helped a lot

  33. Teju says:

    too good

  34. Praksh says:

    Thks,

  35. Shady says:

    this method , please give more examples.

  36. S Roopesh says:

    Thanks a lot

  37. Naidu says:

    Thaks, I got clear idea now.

Leave a Reply

*