Java Reference
In-Depth Information
After executing String s = "Java";
After executing s = "HTML";
This string object is
now unreferenced
s
: String
: String
s
String object for "Java"
String object for "Java"
Contents cannot be changed
: String
String object for "HTML"
F IGURE 10.15
Strings are immutable; once created, their contents cannot be changed.
Because strings are immutable and are ubiquitous in programming, the JVM uses a unique
instance for string literals with the same character sequence in order to improve efficiency
and save memory. Such an instance is called an interned string . For example, the following
statements:
interned string
String s1 = "Welcome to Java" ;
s1
: String
s3
String s2 = new String( "Welcome to Java" );
Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java" ;
s2
: String
System.out.println( "s1 == s2 is " + (s1 == s2));
System.out.println( "s1 == s3 is " + (s1 == s3));
A string object for
"Welcome to Java"
display
s1 == s2 is false
s1 == s3 is true
In the preceding statements, s1 and s3 refer to the same interned string— "Welcome to
Java" —so s1 == s3 is true . However, s1 == s2 is false , because s1 and s2 are two
different string objects, even though they have the same contents.
10.10.3 Replacing and Splitting Strings
The String class provides the methods for replacing and splitting strings, as shown in
Figure 10.16.
java.lang.String
+replace(oldChar: char,
newChar: char): String
+replaceFirst(oldString: String,
newString: String): String
+replaceAll(oldString: String,
newString: String): String
+split(delimiter: String):
String[]
Returns a new string that replaces all matching characters in this
string with the new character.
Returns a new string that replaces the first matching substring in
this string with the new substring.
Returns a new string that replaces all matching substrings in this
string with the new substring.
Returns an array of strings consisting of the substrings split by the
delimiter.
F IGURE 10.16
The String class contains the methods for replacing and splitting strings.
 
 
Search WWH ::




Custom Search