Difference Between equals() and == in Java

The equals() method and == operator in Java perform two different operations. The equals() method is used to compare two string values. On the other hand == operator is used to compare two primitive datatype variables or to compare references of two objects. Below is a sample program that shows difference between equals() and == in Java.

 

 

Output

Difference Between equals() and == in Java

In first case we are comparing the values or content of String objects str1 and str2 using equals() method. The result is true because there values are equal.

In the second case we are comparing the references of String objects str1 and str2 using == operator. The result is false because there references are not equal as both the objects are different.

 

2 thoughts on “Difference Between equals() and == in Java

  1. Thuy

    This is not correct in Java 8. Equal and “==” is same when compare String objects in Java 8.
    This issue just happen in past

    Reply
    1. Admin Post author

      I dont think so, can u give any example that give two different results in Java 8 and previous versions.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *