Java Reference
In-Depth Information
if (one == piecedTogether) {
System.out.println("The string contain the same value
using == ");
}
// Comparison is equal
if (one.compareTo(var1) == 0){
System.out.println("One is equal to var1 using
compareTo()");
}
Results in the following output:
String one equals var1 using equals
String one equals var1 using ==
String two equals var2 using equalsIgnoreCase
Trying to use == on Strings that are pieced together
The strings contain the same value using equals
One is equal to var1 using compareTo()
How It Works
One of the trickier parts of using a programming language can come when attempting
to compare two or more values. In the Java language, comparing strings can be fairly
straightforward, keeping in mind that you should not use the == for string comparison.
This is because the comparison operator ( == ) is used to compare references, not values
of strings. One of the most tempting things to do when programming with strings in
Java is to use the comparison operator, but you must not because the results can vary.
Note Java uses interning of strings to speed up performance. This means that the
JVM contains a table of interned strings, and each time the intern() method is called
on a string, a lookup is performed on that table to find a match. If no matching string
resides within the table, the string is added to the table and a reference is returned. If the
string already resides within the table, the reference is returned. Java will automatically
intern string literals, and this can cause variation when using the == comparison operat-
or.
Search WWH ::




Custom Search