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


this question has answer here:

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 , str2refer 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 

live copy

string str1 = "amir"; string = "am"; string ir = "ir"; string str2 = + ir; system.out.println(str1.equals(str2)); // true system.out.println(str1 == str2);      // false 

live copy (thank jlrishe)

basically, any time string created @ runtime instead of being fully-formed @ compile-time, default new string object, , not == equivalent string object.


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -