File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference between == and .equals

 
balajee annamalai
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone expain me the difference between Difference between == and .equals
 
Kaydell Leavitt
Ranch Hand
Posts: 689
Eclipse IDE Firefox Browser Mac OS X
  • 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.)
 
Kaydell Leavitt
Ranch Hand
Posts: 689
Eclipse IDE Firefox Browser Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a Lot
 
Joanne Neal
Rancher
Pie
Posts: 3742
16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Srinivas Redd
Greenhorn
Posts: 17
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Henry Wong
author
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Thomas Thevis
Ranch Hand
Posts: 87
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Thomas Thevis
Ranch Hand
Posts: 87
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Seems I'm way too slow...
 
Srinivas Redd
Greenhorn
Posts: 17
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 9497
50
Eclipse IDE Hibernate Ubuntu
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Nitin Singla
Greenhorn
Posts: 15
Eclipse IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6109
6
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47300
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String interning and the apparently strange behaviour of the == operator on Strings is explained nicely here.
 
Tarun Oohri
Ranch Hand
Posts: 189
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47300
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 189
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47300
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 189
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47300
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 189
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3028
10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 189
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47300
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done, explaining it better than I did.
 
ankush deshpande
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== 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
Pie
Posts: 9497
50
Eclipse IDE Hibernate Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6109
6
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 9497
50
Eclipse IDE Hibernate Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47300
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic