The difference between == and equals()
by, 04-26-2012 at 07:31 PM (359 Views)
The == operator:
References are compared by == operator, of the 2 objects which are present in memory. When these 2 objects are pointing similar memory location, then it returns true. It shall be remembered that in java strings are immutable therefore if string variables “str1” is present along with “abc” value and then another variable along with other value is created, instead of new string variable creation with same value, then Java simply would be pointing str2 to similar location of memory which has value of str1.
In such a case,“str1==str2” returns true as both of str1 as well as str2 refer the similar object present in memory.
The equals() method:
Text content and string variable’s value is compared by the equals method. Both of the variables having similar value, in that case, equal() method would be returning true, otherwise false. Hence str1.equals(str2) and str1.equals(str3) and str2.equals(str3), all would be returned true.