Java Reference
In-Depth Information
The classes
String
,
StringBuilder
, and
StringBuffer
are used for processing
strings.
Key
Point
A
string
is a sequence of characters. Strings are frequently used in programming. In many
languages, strings are treated as an array of characters, but in Java a string is treated as an
object. This chapter introduces the classes for processing strings.
A
String
object is immutable: Its content cannot be changed once the string is
created.
Key
Point
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.
9.2.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 simplicity, the term
string
will often be used to refer to
String
variable,
String
object, and string value.
String
variable,
String
object, string value
9.2.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