When is a == b
is true but a.equals(b)
is false, or vice versa?
I know that equals()
is used to compare the values of the Strings and the =
= to check if two variables point at the same instance of a String object.
But in which case will these two be different ?
Consider this code,
String str1 = "ABC";
String str2 = new String("ABC");
System.out.println(str1==str2); // false
System.out.println(str1.equals(str2)); //true
The reason for this is that when you write String str1="ABC"
this string is kept in string pool and String str2 = new String("ABC")
creates the new object in heap and it won't check the string pool if it is already present. But as contents of the both string are same, equals method returns true.