-
2
-
-
-
-
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.
-
1
-
-
-
-
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
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 ]
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
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
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.
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.
-
1
-
-
-
-
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
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
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 ]
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(⇐)
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 ".

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.
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


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.
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

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 "

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.
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.
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".
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
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.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
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.
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
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
