Java Reference
In-Depth Information
This does not compare the contents of the two strings. It compares one
object reference ( str ) to another (the string object representing the lit-
eral "¿Peña?" ). Even if str contains the string "¿Peña?" this == expression
will almost always yield false because the two strings will be held in dif-
ferent objects. Using == on objects only tests whether the two references
refer to the same object, not whether they are equivalent objects.
However, any two string literals with the same contents will refer to
the same String object. For example, == works correctly in the following
code:
String str = "¿Peña?";
// ...
if (str == "¿Peña?")
answer(str);
Because str is initially set to a string literal, comparing with another
string literal is equivalent to comparing the strings for equal contents.
But be carefulthis works only if you are sure that all string references
involved are references to string literals. If str is changed to refer to a
manufactured String object, such as the result of a user typing some in-
put, the == operator will return false even if the user types ¿Peña? as the
string.
To overcome this problem you can intern the strings that you don't know
for certain refer to string literals. The intern method returns a String
that has the same contents as the one it is invoked on. However, any
two strings with the same contents return the same String object from
intern , which enables you to compare string references to test equality,
instead of the slower test of string contents. For example:
int putIn(String key) {
String unique = key.intern();
int i;
// see if it's in the table already
 
Search WWH ::




Custom Search