67

I switched lecturers today and he stated using a weird code to me. (He said it's better to use .equals and when I asked why, he answered "because it is!")

So here's an example:

if (o1.equals(o2))
{
 System.out.println("Both integer objects are the same");
}

Instead of what I'm used to:

if (o1 == o2)
{
  System.out.println("Both integer objects are the same");
}

What's the difference between the two. And why is his way (using .equals) better?

Found this on a quick search but I can't really make sense of that answer:

Peter O.
  • 32,158
  • 14
  • 82
  • 96
OVERTONE
  • 11,797
  • 20
  • 71
  • 87

11 Answers11

113

In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.

However, the equals method can be overridden - so two distinct objects can still be equal.

For example:

String x = "hello";
String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' });

System.out.println(x == y); // false
System.out.println(x.equals(y)); // true

Additionally, it's worth being aware that any two equal string constants (primarily string literals, but also combinations of string constants via concatenation) will end up referring to the same string. For example:

String x = "hello";
String y = "he" + "llo";
System.out.println(x == y); // true!

Here x and y are references to the same string, because y is a compile-time constant equal to "hello".

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    What about not generic classes, where the equals wasn't overrided. will the equals method be the same as "==" and simply check if the two instances of the class refer to the same object? thanks. – Numerator Sep 09 '11 at 21:54
  • 3
    @Nir: Yes. In classes, unless you override Equals, it will always mean reference equality. – Jon Skeet Sep 09 '11 at 22:04
  • Horrible wording here. The '==' tests whether two objects point to the same memory location, i.e. they are pointers to one-in-the-same object. The 'equals ()' method compares object state, i.e. given the same type are all internals such as instance variables the same. – ingyhere Oct 26 '12 at 17:23
  • 7
    @ingyhere: *objects* don't point to anything. `==` tests whether two *references* refer to the same object. If you're going to complain about "horrible wording", you need to make sure you use correct terminology. As for whether `equals()` compares object state - it *can*, but it doesn't have to, and it certainly doesn't automatically. (And it may consider whether *some* variables are equal, but not others.) – Jon Skeet Oct 26 '12 at 20:08
  • @Jon Skeet: "Does Java pass by reference or pass by value?" ( http://tinyurl.com/9jxg9f9 ) What is being compared with '==' are not "two references" but memory location of the objects (note lowercase). That's simply it, and why two Strings with the same internals produce FALSE for '=='. You are correct that equals does not always compare state. Default behavior in the Object class is a one-liner '==' comparison. In cases of most java.lang primitive wrappers, like Integer, the Object equals () method is overridden to compare internals. This is exactly what source for java.lang.String reveals. – ingyhere Oct 28 '12 at 20:42
  • 3
    @ingyhere: Um, I fail to see how that article is relevant. That's talking about parameter passing. The values being compared are *exactly* references. They needn't be memory locations exactly - they're whatever form of references the JVM wants to use for references. The value of a reference type variable *is* a reference. That's why in this context, `==` is the *reference equality operator*. See section 15.21.3 of the Java Language Specification: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.21.3. This is very well-defined terminology, and I'm using it correctly. – Jon Skeet Oct 28 '12 at 20:46
  • The Java Virtual Machine Specification in section 3.2 states explicitly, "Values of type reference can be thought of as pointers to objects." (See http://tinyurl.com/8msrn3u .) My point is that hand waving with nice terminology does not reflect the core memory comparisons. – ingyhere Oct 30 '12 at 06:18
  • 2
    @ingyhere: "Can be thought of" in many situations, yes - but not all. *That's* the hand-waving. A JVM could certainly be implemented where reference values were *not* direct memory locations, but entries into a large lookup table for example. Your point seems to have changed over time though, from accusing me of using the word "reference" incorrectly. Do you now accept that my use of the word reference is *entirely* in line with the JLS, and that the values being compared *are* references? – Jon Skeet Oct 30 '12 at 06:46
  • @JonSkeet : I tried to add string literal case in your answer, so anyone refers to this answer does not miss out that point. Kindly fill in the gaps if you feel. – rohan-patel Jan 07 '14 at 20:05
21

The == operator compares if the objects are the same instance. The equals() oerator compares the state of the objects (e.g. if all attributes are equal). You can even override the equals() method to define yourself when an object is equal to another.

Sylar
  • 2,273
  • 2
  • 18
  • 26
  • 9
    Note that the default implementation of `equals()` in `Object` falls back to effectively `this == other`. That's a common source of confusion, since you won't see a difference unless you're using a class that actually implement `equals()` in a meaningful way. – Joachim Sauer Oct 29 '09 at 11:43
  • 1
    Right, I should have mentioned that. The questioner can look at the JDK itself, there are numerous classes he can take as example. – Sylar Oct 29 '09 at 12:41
14

If you and I each walk into the bank, each open a brand new account, and each deposit $100, then...

  1. myAccount.equals(yourAccount) is true because they have the same value, but
  2. myAccount == yourAccount is false because they are not the same account.

(Assuming appropriate definitions of the Account class, of course. ;-)

joel.neely
  • 30,725
  • 9
  • 56
  • 64
  • 4
    That would be a really really bad implementation of equals. – user44242 Oct 29 '09 at 12:41
  • 5
    It was also a really, really bad explanation of the difference between == and equals. – jarnbjo Oct 29 '09 at 13:08
  • 2
    I like this comparison lol it shows why you shouldn't code `==` for strings as the wrong person may get your money or you may not get your money at all. (who would store money as a string anyways LOL) but it's a good example to scare programmers. – SSpoke Aug 16 '11 at 00:44
2

== is an operator. equals is a method defined in the Object class

== checks if two objects have the same address in the memory and for primitive it checks if they have the same value.equals method on the other hand checks if the two objects which are being compared have an equal value(depending on how ofcourse the equals method has been implemented for the objects. equals method cannot be applied on primitives(which means that if a is a primitive a.equals(someobject) is not allowed, however someobject.equals(a) is allowed).

prashant
  • 1,382
  • 1
  • 13
  • 19
0

== operator compares two object references to check whether they refer to same instance. This also, will return true on successful match.for example

public class Example{
public static void main(String[] args){
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2)     //true
test(s1 == s3)      //false
}}

above example == is a reference comparison i.e. both objects point to the same memory location

String equals() is evaluates to the comparison of values in the objects.

   public class EqualsExample1{
   public static void main(String args[]){
   String s = "Hell";
   String s1 =new string( "Hello");
   String s2 =new string( "Hello");
   s1.equals(s2);    //true
    s.equals(s1) ;   //false
    }}

above example It compares the content of the strings. It will return true if string matches, else returns false.

punitha
  • 9
  • 3
-1

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. EX:

String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1 == obj2)
   System.out.println("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

Even though the strings have the same exact characters (“xyz”), The code above will actually output: obj1==obj2 is FALSE

Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.

String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1.equals(obj2))
   System.out.printlln("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

This code will output the following:

obj1==obj2 is TRUE

  • It will typically check whether the objects reside at the same place in memory, but that's an implementation detail. It would be possible for a concurrent garbage-collector to set a write-trap at an object's present location, copy the object to a new location, then update one reference to refer to the new copy, and then finally update the other reference. The `==` operator would have to return `true` at all times, even between the two updates, since both references would *identify* the same object, but that wouldn't imply that they identified the same piece of memory. – supercat Apr 09 '15 at 23:25
-1
public static void main(String[] args){
        String s1 = new String("hello");
        String s2 = new String("hello");

        System.out.println(s1.equals(s2));
        ////
        System.out.println(s1 == s2);

    System.out.println("-----------------------------");

        String s3 = "hello";
        String s4 = "hello";

        System.out.println(s3.equals(s4));
        ////
        System.out.println(s3 == s4);
    }

Here in this code u can campare the both '==' and '.equals'

here .equals is used to compare the reference objects and '==' is used to compare state of objects..

Ammy
  • 369
  • 2
  • 8
-2

The equals( ) method and the == operator perform two different operations. The equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:

// equals() vs ==
class EqualsNotEqualTo {
     public static void main(String args[]) {
          String s1 = "Hello";
          String s2 = new String(s1);
          System.out.println(s1 + " equals " + s2 + " -> " +
          s1.equals(s2));
          System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
     }
}

The variable s1 refers to the String instance created by “Hello”. The object referred to by s2 is created with s1 as an initializer. Thus, the contents of the two String objects are identical, but they are distinct objects. This means that s1 and s2 do not refer to the same objects and are, therefore, not ==, as is shown here by the output of the preceding example:

Hello equals Hello -> true
Hello == Hello -> false
Jainendra
  • 24,713
  • 30
  • 122
  • 169
  • 1
    The question didn't actually refer to strings. While the equals method often refers to the "inside" of an object, it is in no obligation to. Many objects .equals() method just use the memory address (i.e. are equavalent to ==) – Richard Tingle Jul 01 '13 at 19:33
  • 1
    In Java, there are a small number of primitive types and *one* "reference" type. The `==` operator tests whether its operands are the *same*. Since the "value" of a reference type is the *identity* of an object, operands are only considered the same if they refer to the same object. Nothing about the object itself matters; indeed, the comparison is done without even looking at it. – supercat Jul 02 '13 at 14:57
-2

Lets say that "==" operator returns true if both both operands belong to same object but when it will return true as we can't assign a single object multiple values

public static void main(String [] args){
    String s1 = "Hello";
    String s1 = "Hello";  // This is not possible to assign multiple values to single object
    if(s1 == s1){
      // Now this retruns true
   }
}

Now when this happens practically speaking, If its not happen then why this is == compares functionality....

gparyani
  • 1,958
  • 3
  • 26
  • 39
-2

(1) == can be be applied for both primitives and object types, but equals() method can be applied for only object types.

(2) == cannot be overridden for content comparison, but equals method can be overridden for content comparison(ex; String class, wrapper classes, collection classes).

(3) == gives incomparable types error when try to apply for heterogeneous types , where as equals method returns false.

-2

Here is a simple interpretation about your problem:

== (equal to) used to evaluate arithmetic expression

where as

equals() method used to compare string

Therefore, it its better to use == for numeric operations & equals() method for String related operations. So, for comparison of objects the equals() method would be right choice.

ersks
  • 1,409
  • 2
  • 16
  • 23