Difference between Equals/equals and == operator?
Asked Answered
N

11

46

What is the difference between a == b and a.Equals(b)?

Nahshu answered 9/6, 2009 at 19:13 Comment(7)
One checks to see if they represent the same object (equals), and the other checks to see if they are the same object (==)Candelabrum
Eric Lippert has a great blog post on this. He speaks specifically about C#, but I'd imagine the reasons for java would be the same or quite similiar.Deeann
Except that you can't overload operators in Java.Calan
The C# version is: #773453 . Let me go try to hunt up a Java version...Flitch
Astonishingly, the Java version does not seem to have been asked before, at least not directly. The closest I can find is #514332 .Flitch
Probably because it is documented and readily available.Overdress
With working objects; == operator interests whether their references are same or not, but you should modify equals function according to your object and it compares value by valueRunyan
C
50

Assuming the types of a and b are reference types:

  • In Java, == will always compare for identity - i.e. whether the two values are references to the same object. This is also called reference equality. Java doesn't have any user-defined operator overloading.

  • In C# it depends. Unless there's an overloaded operator which handles it, == will behave like Java (i.e. comparing for reference equality). However, if there's an overload which matches the compile-time types of a and b (e.g. if they're both declared as strings) then that overload will be called. That can behave how it wants, but it typically implements value equality (i.e. a and b can refer to different but equal values and it would still return true).

In both languages, a.Equals(b) or a.equals(b) will call the virtual Equals/equals method declared by Object, unless a more specific overload has been introduced by the compile-time type of a. This may or may not be overridden in the execution-time type of the object that a refers to. In both .NET and Java, the implementation in Object also checks for identity. Note that this depends on the execution-time type rather than the compilation-time type that overload resolution depends on.

Of course, if a is null then you'll get a NullReferenceException/NullPointerException when you try to call a.equals(b) or a.Equals(b).

Calan answered 9/6, 2009 at 19:19 Comment(10)
There are no virtual methods in java, well no 'virtual' keyword really, every method is what .net call's virtual (can be overridden by a subclass)Algonquian
To be more precise, == compares the values of two expressions, regardless of whether the expressions are primitive typed or pointers. If those expressions are pointers like "Dog d" or "new Dog()", then what you're testing is "do the expressions point to the same object". The .equals() method is intended to be used to check for semantic equality; do two objects have the same "meaning".Chichihaerh
@Pablo: Try overriding Object.getClass().Calan
@Scott: The trouble is things become trickier when you bring in autoboxing etc. If a and b are the same type and no overloads are involved, I agree.Calan
@Jon: I meant that there's no concept of virtual in Java, some Java programmers might be confused by that. In Java every method is virtual, unless you state otherwise (with 'final'). C# does exactly the opposite, every method is final unless declared 'virtual'Algonquian
At least this phrase "In both languages, a.Equals(b) or a.equals(b) will call the virtual Equals/equals method" might sound confusing for any non-net programmer.Algonquian
@Pablo: I just regard the virtual/final bit as a matter of different defaults. How the default isn't picked doesn't change the concept. I've always considered non-final methods in Java to be virtual.Calan
@JonSkeet : you said that "In Java, == will always compare for identity - i.e. whether the two values are references to the same object" . For eg int a=1; int b=1; In this case a and b both have the same value but but are two primitive objects right? that means they do not point to the same objects.Lectionary
@Ashwin: You missed the "Assuming the types of a and b are reference types" at the very start of the answer, which isn't true in your example.Calan
Shouldn't one of the the last "a.equals(b) or a.equals(b)" be a.Equals(b)?Mayenne
L
13

The == operator checks to see if two objects are exactly the same object which is not the way to go in most cases. The Equals method will be able to compare both the object internally

Example:

class Mycar
{
  string color;
  Mycar(string str)
 {
   color = str;
 }
}   

Mycar a = new Mycar("blue");
Mycar b = new Mycar("blue");
a==b // Returns false
a.Equals(b) // Returns true
Longshore answered 9/6, 2009 at 19:16 Comment(1)
Which language is this? In C#, unless you write your own Equals method, the default one will use reference equality (it's the same as ==)Cybill
S
3

It depends on the types of a and b.

In particular, Equals is a virtual method, so that its behavior doesn't depend on the compile-time types of a and b.

In Java, == will always compare by reference, which is not necessarily what you want, especially for strings.

In C#, == can be overloaded, but is not virtual (it's a static method). Therefore, if a or b are declared as object, it will compare by reference, even if their actual type overloads operator ==.

Also, a.Equals(b) will throw a NullReferenceException (NullPointerException in Java) if a is null.

Selfexistent answered 9/6, 2009 at 19:17 Comment(1)
== can't be overridden - it can be overloaded.Calan
A
2
String a = "toto".Substring(0, 4);
String b = "toto";
Object aAsObj = a;
Assert.IsTrue(a.Equals(b));
Assert.IsTrue(a == b);
Assert.IsFalse(aAsObj == b);
Assert.IsTrue(aAsObj.Equals(b));

This test pass in .NET, the trick is that Equals is a method, whereas == is a static method, so aAsObj == b use

static bool Object.operator==(object a, object b) //Reference comparison

whereas a == b use

static bool String.operator==(string a, string b) //String comparison

but a.Equals(b) or aAsObj.Equals(b) always use :

bool String.Equals(Object obj) //String comparison
Absorptance answered 9/6, 2009 at 19:28 Comment(0)
N
2

== is a fundamental operator in the language. The operator == tests to see if two object reference variables refer to the exact same instance of an object.

equals () is an instance method which is fundamentally defined by the java.lang.Object class. 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.

The == operator always gives you the same result, but the equals () method gives you output according to your implementation (implemented logic).Proper overriding of equals: Considerations’ whenever overriding equals () method.

1. Reflexive: For any non-null reference x, x.equals(x) should return true.

2. Symmetric: For any non-null reference x and y, if x.equals(y) is true then y.equals(x) must return true.

3. Transitive: For any non-null reference x , y and z, if x.equals(y) is true, y.equals(z) is true then x.equals(z) must return true.

4. Consistent: For any non-null reference x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, without changing the information provided for the equals comparisons.

5. For any non-null reference x, x.equals (null) must return false. NOTE: If o1.equals (o2) is true then o1.hashcode () ==o2.hashcode (), but the reverse may or may not be true.

Examples:

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.

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. But i.equals (j) will return true.

Using Auto-boxing

Integer i = 10;
Integer j = 10;
Boolean b = (i == j);
System.out.println (b);

This will return TRUE because integers between ranges -127 to 128 be pooled, so in this case both are same objects (JVM not going to create a new object it will retrieve it from pool).

String class overrides the equals method, so here is an example of equals vs. == String s1 = new String ("abc"); String s2 = new String ("abc");

NOTE: Strings are created in String constant pool so when we create like String s=”abc” it will check the pool by invoking the native method intern (), for its existence in the existing pool if it did not found any String then it will create new one but if we invoke new operator then it will create one new String irrespective of checking the pool for existence.

  public class StringEqualityTest {
    public static void main(String []a){

    String s1=new String("abc");
    String s2=new String("abc");

     System.out.print("s1.equals(s2)  :"+s1.equals(s2)+"  s1==s2   :");
     System.out.println(s1==s2);

     String s3="abc";
     String s4="abc";

     System.out.print("s3.equals(s4)  :"+s1.equals(s2)+"  s3==s4   :");
     System.out.println(s3==s4);

       }

       }

OUTPUT: s1.equals(s2) :true s1==s2 :false s3.equals(s4) :true s3==s4 :true

Nashoma answered 4/12, 2013 at 15:11 Comment(0)
D
1

a == b returns true if the references contain the same value, i.e., they point to the same object, or they are both null.

The equals() method can be overridden to compare objects. For example, on Strings, the method returns true if the strings contain the same string, even if they are different string objects. You can do similar things with your own objects.

o.equals() will throw an exception if o is a null reference.

Destroyer answered 9/6, 2009 at 19:25 Comment(0)
W
0

== uses the reference of an object, or if an integer/float etc, then it compares the actual number. Technically it just compares what in the memory location. Whereas .equals uses a method inside the object class to compare objects, it can be overridden for your individual classes. Also as arrays also deal with references, its also helpful not to use array1[i] = array2[i], use arraycopy or clone(). I think .equals can also be used with arrays

Winded answered 10/6, 2009 at 0:30 Comment(0)
B
0

== checks the Object reference, basically it compares the hashcodes. Equals uses the contents in the object. Remember, we have to override the .equals method accordingly in our class.

Blouin answered 3/9, 2011 at 7:17 Comment(0)
K
0

Suppose we have a and b or two different objects and we want to compare these two object references. Then we use the == operator and when using a.equals(b), it compares the string values.

Kingery answered 30/8, 2012 at 10:49 Comment(1)
AFAIK == and Equals() will do the same thing. The object reference will only be compared when using the ReferenceEquals-Function. Also, if a is null, a.Equals(b) will throw a NullReferenceException.Aeciospore
S
0

== checks if references are pointing to the same object in the memory

Now,

although the code of equals method in object class is nothing but checking == for the references, it can be overridden to add your own equality checks.

In classes like String, the overridden method checks if the string literals are correct or not. So basically it can be used to check if value is same or not.

Salacious answered 17/10, 2014 at 12:28 Comment(0)
E
-1

==, It only returns a value of hash code according to their addresses so the different addresses even though the strings or any data which r similar also it returns false....THis s help full for the conditions ,returns boolean value.

Evangelista answered 20/1, 2012 at 5:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.