== tests for reference equality..equals() tests for value equality.equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects!. That means, the contents of the objects. Whereas the == operator is expected to check the actual object instances are same or not.
Example
Consider two different reference variables
str1 and str2 str1 = new String("abc");
str2 = new String("abc");
if you use the
equals()System.out.println((str1.equals(str2))?"TRUE":"FALSE");
You will get the output as
TRUE
if you use
==System.out.println((str1==str2)?"TRUE":"FALSE");
Now you will get the
FALSE as output because both str1 and str2 are pointing to two different objects even though both of them share the same string content. It is because of new String() everytime a new object is created.
Comments
Post a Comment