How do I compare strings in Java? -


i've been using == operator in program compare strings far. however, ran bug, changed 1 of them .equals() instead, , fixed bug.

is == bad? when should , should not used? what's difference?

== tests reference equality (whether same object).

.equals() tests value equality (whether logically "equal").

objects.equals() checks nulls before calling .equals() don't have (available of jdk7, available in guava).

consequently, if want test whether 2 strings have same value want use objects.equals().

// these 2 have same value new string("test").equals("test") // --> true   // ... not same object new string("test") == "test" // --> false   // ... neither these new string("test") == new string("test") // --> false   // ... these because literals interned  // compiler , refer same object "test" == "test" // --> true   // ... should call objects.equals() objects.equals("test", new string("test")) // --> true objects.equals(null, "test") // --> false 

you always want useobjects.equals(). in rare situation know you're dealing interned strings, can use ==.

from jls 3.10.5. string literals:

moreover, string literal refers same instance of class string. because string literals - or, more generally, strings values of constant expressions (§15.28) - "interned" share unique instances, using method string.intern.

similar examples can found in jls 3.10.5-1.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -