Java Reference
In-Depth Information
String Concatenation Operator (+)
You will often use the + operator to concatenate a strings, and a primitive type value or an object to another string.
For example,
String str = "X" + "Y" + 12.56;
If concatenation were performed by creating intermediate string objects, the concatenation operation would
create a big overhead. To optimize the string concatenation operation, the compiler replaces the string concatenation
by a statement, which uses a StringBuilder . Because a StringBuilder object is modifiable, only one StringBuilder
object needs to be created. The compiler replaces the above statement with the following one:
String str = new StringBuilder().append("X").append("Y").append(12.56).toString();
Note the use of the toString() method at the end of this statement. It is used to convert the final content of a
StringBuilder to a String . It is also important to note that such cascaded method calls are possible because the
append() method of StringBuilder returns a reference to itself.
Language-Sensitive String Comparison
The String class compares strings based on the Unicode values of their characters. Sometimes you may want to
compare strings based on the dictionary order instead.
Use the compare() method of the java.text.Collator class to perform language-sensitive (dictionary order)
string comparisons. The method takes two strings to be compared as arguments. It returns 0 if two strings are the
same, 1 if the first string comes after the second, and -1 if the first string comes before the second. Listing 11-6
illustrates the use of the Collator class.
Listing 11-6. Language-Sensitive String Comparisons
// CollatorStringComparison.java
package com.jdojo.string;
import java.text.Collator;
import java.util.Locale;
public class CollatorStringComparison {
public static void main(String[] args) {
// Create a Locale object for US
Locale USLocale = new Locale("en", "US");
// Get collator instance for US
Collator c = Collator.getInstance(USLocale);
String str1 = "cat";
String str2 = "Dog";
int diff = c.compare(str1, str2);
System.out.print("Comparing using Collator class: ");
print(diff, str1, str2);
 
Search WWH ::




Custom Search