Amir Ziarati Amir Ziarati - 1 month ago 9
Java Question

what is the special case that make `str1 == str2` a logical error?

I know that java stores

String Literals
in
Common Pool
and two string literals having the same text will refer to the same place in Common Pool. take below code:

String str1 = "Amir";
String str2 = "Amir";


now both
str1
and
str2
refer to the same place in the Common Pool. so from what all we know we must use equals() to properly compare these two strings and obviously
str1.equals(str2)
will be
true
.

now from what i read here it says that the
str1 == str2
will be true becuase the strings both have the same address (sounds pretty logical) but it also states that its a logical error to do so.

my question is what is that special case that may cuase trouble and inconsistency to my code if I use
str1 == str2
?

Answer

Not special cases, common cases:

String base = "Amir123";
String str1 = base.substring(0, 4);
String str2 = "Amir";
System.out.println(str1.equals(str2)); // true
System.out.println(str1 == str2);      // false

Live Copy

String str1 = "Amir";
String am = "Am";
String ir = "ir";
String str2 = am + ir;
System.out.println(str1.equals(str2)); // true
System.out.println(str1 == str2);      // false

Live Copy (thank you JLRishe)

Basically, just about any time a string is created at runtime instead of being fully-formed at compile-time, by default it will be a new String object, and so not == another equivalent String object.