What is difference between == and equals() in java?


== operator is used to compare the references of the objects.

public boolean equals(Object o) is the method provided by the Object class. The default implementation uses ==
operator to compare two objects.

But since the method can be overridden like for String class. equals() method can be used to compare the values of two
objects.

String str1 = new String("MyName");
String str2 = new String("MyName");

if(str1 == str2){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}

if(str1.equals(str2)){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}

Output:
Objects are not equal
Objects are equal

Lets look at other snippet:

String str2 = "MyName";
String str3 = str2;

if(str2 == str3){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}

if(str3.equals(str2)){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}

Objects are equal
Objects are equal

18 thoughts on “What is difference between == and equals() in java?

  1. I thinks u r wrong

    String str1 = “MyName”;
    String str2 = “MyName”;

    if(str1 == str2) // also true

    1. Thanks for pointing the mistake.
      its a typo error.
      I have changed it to
      String str1 =new String( “MyName”);
      String str2 = new String(“MyName”);

    2. String str1 = “MyName”;
      String str2 = “MyName”;

      if(str1 == str2) // also true
      yes it gives true but these are INTERNED String.
      i.e. both str1 and str2 having the same reference.because in pool only one String Litteral r defined to storage and same reference r given to both str1 and str2.

Leave a comment