'==' operator : we can use this operator for comparing two objects or to compare primitives. It is not recommended to use it to compare objects as while comparing the objects our focus is on actual equality of objects than the memory location.'==' operator compares the memory location.
Example : String str="Hello";
String str2="Java";
here, str==str2 will return false as both objects are stored at different location.
again, say String str="Java";
String str2="Java";
here, str==str2 will return true, as both references are pointing to same object.
equals() method: This method compares the content of two objects. This is overridden method from Object class.Generally, equals method is used to compare two string objects.String class has already overridden equals(), so we can directly use it, but if you wish to compare two objects other than string class then you have to override equals() method. The default implementation of equals() in object class is same as '==' operator.
Example : String str="Hello";
String str2=new String("Hello");
here, str.equals(str2) will return true.
again, say : String str="Hello";
String str2="Java";
here, str.equals(str2) will return false.
Example : String str="Hello";
String str2="Java";
here, str==str2 will return false as both objects are stored at different location.
again, say String str="Java";
String str2="Java";
here, str==str2 will return true, as both references are pointing to same object.
equals() method: This method compares the content of two objects. This is overridden method from Object class.Generally, equals method is used to compare two string objects.String class has already overridden equals(), so we can directly use it, but if you wish to compare two objects other than string class then you have to override equals() method. The default implementation of equals() in object class is same as '==' operator.
Example : String str="Hello";
String str2=new String("Hello");
here, str.equals(str2) will return true.
again, say : String str="Hello";
String str2="Java";
here, str.equals(str2) will return false.
You can not use equals() to compare primitives and it is recommended that you use equals() to compare objects and '==' to compare primitives.
No comments:
Post a Comment