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 - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -