java - what is the special case that make `str1 == str2` a logical error? -
this question has answer here:
- how compare strings in java? 23 answers
i know java stores string literals
in common pool
, 2 string literals having same text refer same place in common pool. take below code:
string str1 = "amir"; string str2 = "amir";
now both str1
, str2
refer same place in common pool. know must use equals() compare these 2 strings , str1.equals(str2)
true
.
now read here says str1 == str2
true becuase strings both have same address (sounds pretty logical) states logical error so.
my question special case may cuase trouble , inconsistency code if use str1 == str2
?
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
string str1 = "amir"; string = "am"; string ir = "ir"; string str2 = + ir; system.out.println(str1.equals(str2)); // true system.out.println(str1 == str2); // false
basically, any time string created @ runtime instead of being fully-formed @ compile-time, default new string
object, , not ==
equivalent string
object.
Comments
Post a Comment