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 input, 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
for (i = 0; i < tableSize; i++)
if (table[i] == unique)
return i;
// it's not there--add it in
table[i] = unique;
tableSize++;
return i;
}
All the strings stored in the table array are the result of an intern invocation. The table is searched for a
string that was the result of an intern invocation on another string that had the same contents as the key. If
this string is found, the search is finished. If not, we add the unique representative of the key at the end.
Dealing with the results of intern makes comparing object references equivalent to comparing string
contents, but much faster.
Any two strings with the same contents are guaranteed to have the same hash codethe String class
overrides Object.hashCodealthough two different strings might also have the same hash code. Hash
codes are useful for hashtables, such as the HashMap class in java.utilsee "HashMap" on page 590.
13.2.4. Making Related Strings
Several String methods return new strings that are like the old one but with a specified modification. New
strings are returned because String objects are immutable. You could extract delimited substrings from
another string by using a method like this one:
public static String delimitedString(
String from, char start, char end)
{
int startPos = from.indexOf(start);
int endPos = from.lastIndexOf(end);
if (startPos == -1) // no start found
return null;
else if (endPos == -1) // no end found
return from.substring(startPos);