wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Difference between == and .equals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Difference between == and .equals" Watch "Difference between == and .equals" New topic
Author

Difference between == and .equals

balajee annamalai
Ranch Hand

Joined: May 09, 2007
Posts: 31
Can someone expain me the difference between Difference between == and .equals
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 688

Welcome to the Java Ranch,

The operator, ==, tests to see if two object reference variables refer to the exact same instance of an object.

The method, .equals(), tests to see if the two objects being compared to each other are equivalent -- but they need not be the exact same instance of the same object.

Example #1:

Integer i = new Integer(10);
Integer j = i;

in the above code. i == j is true because both i and j refer to the same object.

Example #2:

Integer i = new Integer(10);
Integer j = new Integer(10);

In the above code, i == j is false because, although they both have the value 10, they are two different objects.

Also, in the above code, i.equals(j) is true because although they are two different objects, they are equivalent in the fact that they represent the same number, 10.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Welcome to JavaRanch!

The == operator is a simple comparison of values. For object references, the values are the references (as Kaydell explained above), so x == y returns true if x and y reference the same object.

The equals method can compare two different objects for equality. But here, "equal" is defined by the programmer when they override the method for a specific class. For example, if you are writing a Car class and all you care about is color, then you could implement equals to return true if both cars are the same color. It's probably not the best way to compare cars, but the point is it's up to the programmer to decide what "equals" means.

(Note: Be careful when comparing Strings to each other, and when comparing autoboxed wrapper instances to each other. Under certain situations, these use "pools." See Strings, Literally and JLS - 5.1.7 Boxing Conversion.)


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 688

marc's comments made me wonder whether my examples were correct or not so I verified that they are correct:



I acknowledge marc's point that the programmer has to define the equals() method because it defaults to be the same as the operator, ==. In my example, the class Integer is defined in the Java API and the equals() method is overridden there. As marc pointed out, for classes that you develop, you have to override equals() yourself.
[ February 19, 2008: Message edited by: Kaydell Leavitt ]
balajee annamalai
Ranch Hand

Joined: May 09, 2007
Posts: 31
Thanks a Lot
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3420
    
  12
Originally posted by Kaydell Leavitt:
marc's comments made me wonder whether my examples were correct or not so I verified that they are correct:


Your examples were correct because you used new to create your Integers. If you had used the autoboxing feature of Java 1.5, you could have written
and this would have printed true, because certain Integer values are pooled.
I can't remember off the top of my head the range of values that are pooled, but the Java Language Specification will tell you.

Edit : Just been reading the JLS. Integers in the range -128 to 127 are pooled, so the above code would print true for int literals between those two values. Int literals outside these values may also print true, but this is optional and can vary from one JVM to another. See section 5.1.7 of the JLS for details.
[ February 20, 2008: Message edited by: Joanne Neal ]

Joanne
Srinivas Redd
Greenhorn

Joined: Mar 23, 2006
Posts: 17
I have the below code.





I am expecting "Both objects are equal" as the response but I am getting "unequal objects ". Can someone explain why ?

[edit]Add code tags. CR[/edit]
[ September 02, 2008: Message edited by: Campbell Ritchie ]

Srinvasa Reddy Thamma,<br />Chennai,India.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18510
    
  40

I am expecting "Both objects are equal" as the response but I am getting "unequal objects ". Can someone explain why ?


Because you didn't override the equals() method, hence, it is using the default equals() method (from the Object class), which only checks if they are physically the same object.

BTW, how do you expect Java to magically determine equality?

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

The default implementation of equals() -- the one your class inherits from java.lang.Object -- looks like this:



In other words, by default, == and equals() behave exactly the same. It's only when a class overrides equals() that the behavior is any different. You'll get the behavior you were expecting if you add a method like:



If you override equals(), you always should override hashCode(), too, so that the return values of hashCode() are equal for objects for which equals() returns true.


[Jess in Action][AskingGoodQuestions]
Thomas Thevis
Ranch Hand

Joined: Sep 02, 2008
Posts: 87
Hello Srinivas,

you are creating two instances of your class. As default behavior, 'equals()' uses '==' for comparison. To change that behavior, you have to override 'equals()' (and don't forget to override 'hashCode()' as well).

Regards,
Thomas


SCJP 5.0, SCJD in progress
Thomas Thevis
Ranch Hand

Joined: Sep 02, 2008
Posts: 87
Seems I'm way too slow...
Srinivas Redd
Greenhorn

Joined: Mar 23, 2006
Posts: 17
Thank you all for quick response. I thought equals() and == are different by default. Came to know from your responses that I am wrong.

Thanks again.
Debapriya Mukherjee
Greenhorn

Joined: Mar 07, 2012
Posts: 4
Slight Different from this Context but felt like Posting

if you do,

String s1 = "abc"
String s2 = "abc"

and do

if (s1==s2)
{System.out.print("True");}

You always get an output "True"

This is possible becuase of String Interning.

In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.
The single copy of each string is called its 'intern' and is typically looked up by a method of the string class, for example String.intern() in Java. All compile-time constant strings in Java are automatically interned using this method.


Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7529
    
  18

Srinivas Redd wrote:Thank you all for quick response. I thought equals() and == are different by default.

The general rule of thumb is:

NEVER use '==' to compare objects; always, always, always use .equals(). That way, you can never go wrong, even if the class doesn't override equals() itself.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Nitin Singla
Greenhorn

Joined: Oct 05, 2011
Posts: 15

Hey that helps a lot. But i have one more query:
suppose in the same class testToString, suppose we have the below code also
Integer i=new Integer(4);
Integer y=new Integer(4);

if( i.equals(y))
System.out.println(" Both objects(i & y) are equal");
else
System.out.println(" Unequal objects(i & y) ");

Now also we are not overriding equals() method, but it is showing that i & y are equals(Both objects(i & y) are equal).
Can someone helps me?


Srinivas Redd wrote:I have the below code.





I am expecting "Both objects are equal" as the response but I am getting "unequal objects ". Can someone explain why ?

[edit]Add code tags. CR[/edit]
[ September 02, 2008: Message edited by: Campbell Ritchie ]
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Nitin Singla wrote:
Now also we are not overriding equals() method


What we do in our class is irrelevant. The Integer class is the one whose equals() method is being called, and it does override equals(), as you can see if you look at its javadocs.
(⇒)java.lang.Integer(⇐)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37958
    
  22
String interning and the apparently strange behaviour of the == operator on Strings is explained nicely here.
Tarun Oohri
Ranch Hand

Joined: Feb 20, 2013
Posts: 172
Kaydell Leavitt wrote:marc's comments made me wonder whether my examples were correct or not so I verified that they are correct:

Hi, can you please explain me the equals() method overridden in the Integer class. It is given as follows:

public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}

Que1 : Why do we need to down cast " (Integer)obj " ?
Que2 : The == here is suppose to compare the address but here its comparing the int values of "this.value & obj ".
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37958
    
  22
Welcome to the Ranch
You would appear to have used the quote tags wrongly; I have corrected them.
What nobody appears to have noticed in the method quoted, is that the instanceof operator can only be relied on in Integer because it is a final class. I don’t think Integer was a very good example, because it is final.
You need to cast the other reference to the same type as the class you are using; the tests preceding this cast ensure it will complete safely.
No, you are not comparing the locations of the references at all with the == operator. You are comparing the two ints in the objects.
Tarun Oohri
Ranch Hand

Joined: Feb 20, 2013
Posts: 172
Campbell Ritchie wrote:Welcome to the Ranch
You would appear to have used the quote tags wrongly; I have corrected them.
What nobody appears to have noticed in the method quoted, is that the instanceof operator can only be relied on in Integer because it is a final class. I don’t think Integer was a very good example, because it is final.
You need to cast the other reference to the same type as the class you are using; the tests preceding this cast ensure it will complete safely.
No, you are not comparing the locations of the references at all with the == operator. You are comparing the two ints in the objects.
Integer i = Integer.valueOf(123);
Integer j = Integer.valueOf(234);
System.out.println(i.equals(j)); // == operator tests 123 == 234



Hi Ritchie , Thanks for your reply. But i still have a doubt regarding this . It is usually said that == operator checks if the 2 reference variable refers to the same object or not. And equals() checks if the 2 objects formed in the heap are same or not (in value)..right till now ? But equals() contains == operator for comparison, then how can equals() compare the 2 objects , it should rather compare the two reference. variables . Here in above code 123, 234 are the int type objects which are being compared by == , But == compares the reference variables not the objects....CONFUSING!!!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37958
    
  22
You are still using the quote tags wrongly. Don’t delete [\quote]
You have not read the code quoted correctly. You are not comparing the references at all. You are comparing the two ints inside the Integer objects. What I would have written is something like this:-You can test whether they are the same object (line 3) which compares the references, or later (line 5) on test whether the two ints called value (the Integer class’ only field) are equal. The test whether the two references are the same allows you to short‑circuit the remainder of the equals() method. Remember if they are the same object, then equals must return true. Every object is equal to itself.
That equals method was probably written 18 years ago, and I would not use that as a paradigm for good coding. Remember instanceof works correctly in this case because the Integer class is final.
Tarun Oohri
Ranch Hand

Joined: Feb 20, 2013
Posts: 172
Campbell Ritchie wrote:You are still using the quote tags wrongly. Don’t delete [\quote]
You have not read the code quoted correctly. You are not comparing the references at all. You are comparing the two ints inside the Integer objects. What I would have written is something like this:-You can test whether they are the same object (line 3) which compares the references, or later (line 5) on test whether the two ints called value (the Integer class’ only field) are equal. The test whether the two references are the same allows you to short‑circuit the remainder of the equals() method. Remember if they are the same object, then equals must return true. Every object is equal to itself.
That equals method was probably written 18 years ago, and I would not use that as a paradigm for good coding. Remember instanceof works correctly in this case because the Integer class is final.


Hi Ritchie, Thank you so much. I got it I am fresher in java so have to dig hard to get the concepts right . If you do not recommend equals method to compare then what do you use to compare instead of it ?
You say Integer class is not good example because we can not override the equals method in our class if we are instantiating Integer type in our class ( as we can not access the parametrized constructor of Integer class from our class because its private ) ?
What is the need of using instanceof in equals method ? As every time it is going to give true value.
Now , i got to know what you meant by " correct your quote "
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37958
    
  22
You have misunderstood me, I am afraid.
Yes, you use the equals() method to compare objects for equality.
No, I was saying that there are neater ways to write an equals() method than that. I would never have used intValue() when I could have got access to the value field directly.
Tarun Oohri
Ranch Hand

Joined: Feb 20, 2013
Posts: 172
Campbell Ritchie wrote:You have misunderstood me, I am afraid.
Yes, you use the equals() method to compare objects for equality.
No, I was saying that there are neater ways to write an equals() method than that. I would never have used intValue() when I could have got access to the value field directly.


What is the need of using instanceof in equals method ? As every time it is going to give true value.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 2991
    
    9
Tarun Oohri wrote:What is the need of using instanceof in equals method ? As every time it is going to give true value.

No, not necessarily. The signature says equals(Object), so the method needs to handle any possible Object, or null - not just an Integer.

This code should print false, twice. No exceptions thrown, no "true".
Tarun Oohri
Ranch Hand

Joined: Feb 20, 2013
Posts: 172
Mike Simmons wrote:
Tarun Oohri wrote:What is the need of using instanceof in equals method ? As every time it is going to give true value.

No, not necessarily. The signature says equals(Object), so the method needs to handle any possible Object, or null - not just an Integer.

This code should print false, twice. No exceptions thrown, no "true".


Oh ok got it...Thank you so much
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37958
    
  22
Well done, explaining it better than I did.
ankush deshpande
Greenhorn

Joined: Mar 17, 2013
Posts: 2
== compares if 2 references point to the same memory location and equals compares content.
if this does not help i guess this link will solve your doubt.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7529
    
  18

Tarun Oohri wrote: Oh ok got it...Thank you so much

The fact is that if that, indeed, is the actual implementation of Integer.equals() (and dammit, it IS; at least for version 6), they've forgotten a very important check - and the first one you should make if you ever write an equals() method yourself:I leave you to work out why.

Winston

PS: I'm amazed that such a crappy equals() method still exists - and in a wrapper class no less.
Well spotted Tarun.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

ankush deshpande wrote:== compares if 2 references point to the same memory location


In practice that's probably what most implementations end up doing. It's not specified that way in the JLS however. A better way to think of it is that both references have the same value; or that they both point to the same object or are both null.


if this does not help i guess this link will solve your doubt. http://www.youtube.com/watch?v=7RG8HGIiuPY


That video is rather confusing. It spends too much time talking about the constant pool, which isn't relevant for the heart of understanding == vs. equals(). The comments describing the examples did not match the example code. Overall I would recommend against using that video to try to understand anything about Java.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7529
    
  18

Jeff Verdegan wrote:That video is rather confusing...

Erm...having just watched it with a nice glass of beer in my hand, I think "confusing" is an understatement.

It's not only confusing in delivery (it sounded like the guy had just taken a line or two), it doesn't explain why references might be equal.

@Tarun: You should ALWAYS use equals() to compare objects that are not null. For more information, read the AvoidTheEqualityOperator page.

Forget that video. It's crap.

Winston
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37958
    
  22
Winston Gutkowski wrote: . . . Forget that video. It's crap.

Winston
Isn’t it. It is full of errors.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Difference between == and .equals
 
Similar Threads
== and .equals()
what is the difference between == and .equals() method????
Difference between '==' & equals()
difference between equals() and == and compareTo()
loop trouble