[java] What's the difference between ".equals" and "=="?

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:

This question is related to java equals

The answer is


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.


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

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


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.


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


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


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


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


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


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