Java Reference
In-Depth Information
// Concatenated string will not be added to the string pool
String s2 = varStr + " is not pooled";
After executing the above snippet of code, "Constant is pooled" == s1 will return true , whereas
"Variable is not pooled" == s2 will return false .
Tip
all string literals and string literals resulting from compile-time constant expressions are added to the string pool.
You can add a String object to the string pool using its intern() method. The intern ( ) method returns the
reference of the object from string pool if it finds a match. Otherwise, it adds a new String object to the string pool
and returns the reference of the new object. For example, in the previous snippet of code, s2 refers to a String object,
which has the content "Variable is not pooled" . You can add this String object to the string pool by writing
// Will add the content of s2 to the string pool and return the reference
// of the string object from the pool
s2 = s2.intern();
Now "Variable is not pooled" == s2 will return true because you have already called the intern() method
on s2 and its content has been pooled.
the String class maintains a pool of strings internally. all string literals are added to the pool automatically. You
can add your own strings to the pool by invoking the intern() method on the String objects. You cannot access the pool
directly. there is no way to remove string objects from the pool, except exiting and restarting the app.
Tip
String Operations
This section describes some of the frequently used operations on String objects.
Getting the Character at an Index
You can use the charAt() method to get a character at a particular index from a String object. The index starts at zero
as depicted in Table 11-1 .
Table 11-1. Index of a Character in a String Object
Index ->
0
1
2
3
4
Character ->
H
E
L
L
O
 
Search WWH ::




Custom Search