46

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

user2864740
  • 54,112
  • 10
  • 112
  • 187
  • 4
    The C# version is: http://stackoverflow.com/questions/772953/what-is-the-difference-between-equals-and . Let me go try to hunt up a Java version... – Michael Myers Jun 09 '09 at 19:36
  • 2
    Astonishingly, the Java version does not seem to have been asked before, at least not directly. The closest I can find is http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java . – Michael Myers Jun 09 '09 at 19:39
  • 4
    Probably because it is documented and readily available. – Ed S. Jun 10 '09 at 00:32
  • 1
    One checks to see if they *represent* the same object (equals), and the other checks to see if they *are* the same object (==) – Matt Poush Jun 09 '09 at 19:15
  • Eric Lippert has a great [blog post](http://blogs.msdn.com/ericlippert/archive/2009/04/09/double-your-dispatch-double-your-fun.aspx) on this. He speaks specifically about C#, but I'd imagine the reasons for java would be the same or quite similiar. – Nathan Koop Jun 09 '09 at 19:21
  • Except that you can't overload operators in Java. – Jon Skeet Jun 09 '09 at 19:22
  • 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 value – elfekz Oct 27 '17 at 11:36

11 Answers11

51

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

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
  • 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) – Pablo Fernandez Jun 09 '09 at 19:30
  • 1
    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". – Scott Stanchfield Jun 09 '09 at 19:36
  • 1
    @Pablo: Try overriding Object.getClass(). – Jon Skeet Jun 09 '09 at 19:46
  • @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. – Jon Skeet Jun 09 '09 at 19:48
  • @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' – Pablo Fernandez Jun 09 '09 at 20:39
  • 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. – Pablo Fernandez Jun 09 '09 at 20:40
  • @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. – Jon Skeet Jun 09 '09 at 21:15
  • @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. – Ashwin May 27 '12 at 14:03
  • 1
    @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. – Jon Skeet May 27 '12 at 18:44
  • Shouldn't one of the the last "a.equals(b) or a.equals(b)" be a.Equals(b)? – mflodin Sep 18 '12 at 14:20
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
TStamper
  • 28,864
  • 10
  • 63
  • 72
  • 5
    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 ==) – Orion Edwards May 31 '10 at 20:32
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.

Soner Gönül
  • 91,172
  • 101
  • 184
  • 324
SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896
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
Soner Gönül
  • 91,172
  • 101
  • 184
  • 324
Nicolas Dorier
  • 7,257
  • 11
  • 54
  • 72
1

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

subhashis
  • 4,173
  • 7
  • 35
  • 49
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.

mcabral
  • 3,427
  • 1
  • 23
  • 41
uncleO
  • 7,997
  • 2
  • 20
  • 37
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.

ЯegDwight
  • 23,615
  • 10
  • 43
  • 51
akkhatri
  • 1
  • 4
  • 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`. – nikeee Sep 27 '12 at 10:12
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.

Amit
  • 306
  • 3
  • 9
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.

markus
  • 38,729
  • 23
  • 95
  • 139
Ravi K.
  • 231
  • 3
  • 3
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

mcabral
  • 3,427
  • 1
  • 23
  • 41
-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.

Kumar KL
  • 15,086
  • 9
  • 36
  • 57