Java Interview Question - Difference between == and .equals

The function .equal() checks the actual contents of the object, whereas == operator checks whether the references to the objects are same.

Lets take an example

String str 1 = new String("abc");
String str 2 = new String("abc");

So if you have to compare content of str 1 and str 2 , we should do it using str1.equals(str2) which will return true in this case.

str1==str2 will be false as str1 and str2 pointing to 2 different objects in memory.

Now if we do 


then str1 will point to the same object which str2 is pointing, So if(str1==str2) will be true.

Now Lets see another example -

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

Now If you try to do if (str1==str2) , it will return true as well as str1.equal(str2)

** equals is the method of object class and hence applicable to all objects and not just String object.

200 Core Java Interview Question and Answers