Java Reference
In-Depth Information
10.10 The String Class
A String object is immutable: Its content cannot be changed once the string is
created.
Key
Point
Strings were introduced in Section  4.4. You know strings are objects. You can invoke the
charAt(index) method to obtain a character at the specified index from a string, the
length() method to return the size of a string, the substring method to return a substring
in a string, and the indexOf and lastIndexOf methods to return the first or last index of a
matching character or a substring. We will take a closer look at strings in this section.
The String class has 13 constructors and more than 40 methods for manipulating strings.
Not only is it very useful in programming, but it is also a good example for learning classes
and objects.
VideoNote
The String class
10.10.1 Constructing a String
You can create a string object from a string literal or from an array of characters. To create a
string from a string literal, use the syntax:
String newString = new String(stringLiteral);
The argument stringLiteral is a sequence of characters enclosed inside double quotes.
The following statement creates a String object message for the string literal "Welcome
to Java" :
String message = new String( "Welcome to Java" );
Java treats a string literal as a String object. Thus, the following statement is valid:
string literal object
String message = "Welcome to Java" ;
You can also create a string from an array of characters. For example, the following state-
ments create the string "Good Day" :
char [] charArray = { 'G' , 'o' , 'o' , 'd' , ' ' , 'D' , 'a' , 'y' };
String message = new String(charArray);
Note
A String variable holds a reference to a String object that stores a string value.
Strictly speaking, the terms String variable , String object , and string value are
different, but most of the time the distinctions between them can be ignored. For sim-
plicity, the term string will often be used to refer to String variable, String object,
and string value.
String variable, String
object, string value
10.10.2 Immutable Strings and Interned Strings
A String object is immutable; its contents cannot be changed. Does the following code
change the contents of the string?
immutable
String s = "Java" ;
s = "HTML" ;
The answer is no. The first statement creates a String object with the content "Java" and
assigns its reference to s . The second statement creates a new String object with the content
"HTML" and assigns its reference to s . The first String object still exists after the assign-
ment, but it can no longer be accessed, because variable s now points to the new object, as
shown in Figure 10.15.
 
 
 
Search WWH ::




Custom Search