differences between the == operator and the equals() method in Java

Equals method compare values of the receiver and sender object. It returns true if the values are same. While ‘==’ operator is a fundamental operator, it compares reference of the sender and receiver object. E.g.

String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3);// false
System.out.println(s1.equals(s2));// true
System.out.println(s1.equals(s3));// true

From the example, we can see that reference and value for s1 & s2 are same. At the same time s3 is a newly created instance which has same value as of s1 and s2 but reference is different.

Related Post

String.intern in Java
Static in java
Differences between ArrayList and LinkedList
Differences between Vector and ArrayList
java.util.ConCurrentModificationException

Comments

Leave a Reply