Java Reference
In-Depth Information
System.out.print("Comparing using String class: ");
diff = str1.compareTo(str2);
print(diff, str1, str2);
}
public static void print(int diff, String str1, String str2) {
if (diff > 0) {
System.out.println(str1 + " comes after " + str2);
}
else if (diff < 0) {
System.out.println(str1 + " comes before " + str2);
}
else {
System.out.println(str1 + " and " + str2 + " are the same.");
}
}
}
Comparing using Collator class: cat comes before Dog
Comparing using String class: cat comes after Dog
The program also shows the comparison of the same two strings using the
String
class. Note that the word
"cat"
comes before the word
"Dog"
in the dictionary order. The
Collator
class uses their dictionary orders to compare
them. However, the
String
class compares the Unicode value of the first character of
"cat"
, which is 99, and the
first character of
"Dog"
, which is 68. Based on these two values, the
String
class determines that
"Dog"
comes before
"cat"
. The output confirms the two different ways of comparing strings.
Summary
In this chapter, you learned about
String
,
StringBuilder
, and
StringBuffer
classes. A
String
represents an
immutable sequence of characters whereas a
StringBuilder
and
StringBuffer
represent a mutable sequence of
characters.
StringBuilder
and
StringBuffer
work the same way, except the latter is thread-safe and the former is not.
The
String
class provides several methods to operate on its content. Whenever you obtain a part of the content
from a
String
, a new
String
object is created. The
String
class compares two strings based on the Unicode values of
their characters. Use
java.text.Collator
class to compare strings in dictionary order. From Java 7 and on, you can
use strings in a
switch
statement.