Java - Difference between == and .equals()

"equals" is the method of object class which is supposed to be overridden to check object equality, whereas "==" evaluate to see if the object handlers on the left and right are pointing to the same object in memory.

x.equals(y) means the references x and y are holding objects that are equal. x==y means that the references x and y have same object.

String str1 = new String("String1");

String str2 = new String("String1");

System.out.println(str1 == str2); // prints false

System.out.println(str1.equals(str2));// prints true

str1 = str2; // Now str1 holding the same object as str2

System.out.println(str1 == str2); // prints true 

Subscribe to Java News and Posts. Get latest updates and posts on Java from
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus