I ran into a bug at the customer, which reminded me that there are still confusion about how to compare objects and specially Strings in Java.
You can use several methods to compare objects, == test references and .equals for value equality.
Consequently, if you actually want to test whether two strings have the same value you should use .equals()
. ==
is for testing whether two strings are the same object.
// These two have the same value
new String("test").equals("test") is true
// ... but they are not the same object
new String("test") == "test" is false
// ... neither are these
new String("test") == new String("test") is false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" is true
// concatenation of string literals happens at compile time,
// also resulting in the same object
"test" == "te" + "st" is true
// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) is false
==
is much cheaper than equals()
(a pointer comparison instead of a loop), so if you are in situations where you can guarantee that you are only dealing with interned strings it will be a performance improvement.