Java Reference
In-Depth Information
It is very important to note that the compareTo() method compares two strings based on the Unicode values of
their characters. The comparison may not be the same as the dictionary order comparison. This is fine for English
and some other languages in which the Unicode values for characters are in the same order as the dictionary order
of characters. This method should not be used to compare two strings in languages where the dictionary order of
characters may not be the same as their Unicode values. To perform language-based string comparisons, you should
use the compare() method of the java.text.Collator class instead. Please refer the “Locale-Insensitive String
Comparison” section in this chapter to learn how to use java.text.Collator class.
The program shown in Listing 11-2 demonstrates the string comparisons.
Listing 11-2. Comparing Strings
// StringComparison.java
package com.jdojo.string;
public class StringComparison {
public static void main(String[] args) {
String apple = new String("Apple") ;
String orange = new String("Orange") ;
System.out.println(apple.equals(orange));
System.out.println(apple.equals(apple));
System.out.println(apple == apple);
System.out.println(apple == orange);
System.out.println(apple.compareTo(apple));
System.out.println(apple.compareTo(orange));
}
}
false
true
true
false
0
-14
String Pool
Java maintains a pool of all string literals in order to minimize the memory usage and for better performance. It
creates a String object in the string pool for every string literal it finds in a program. When it encounters a string
literal, it looks for a string object in the string pool with the identical content. If it does not find a match in the string
pool, it creates a new String object with that content and adds it to the string pool. Finally, it replaces the string literal
with the reference of the newly created String object in pool. If it finds a match in the string pool, it replaces the string
literal with the reference of the String object found in the pool.
Let's discuss this scenario with an example.
String str1 = new String("Hello");
 
Search WWH ::




Custom Search