Java Reference
In-Depth Information
(a name)
"John Q. Doe"
(a street address)
"9999 Main Street"
(a city and state)
"Waltham, Massachusetts"
(a telephone number)
"(201) 555-1212"
A string may be assigned to a
String
reference. The declaration
String color =
"blue"
;
initializes
String
variable
color
to refer to a
String
object that contains the string
"blue"
.
Performance Tip 14.1
To conserve memory, Java treats all string literals with the same contents as a single
String
object that has many references to it.
Class
String
is used to represent strings in Java. The next several subsections cover many
of class
String
's capabilities.
Class
String
provides constructors for initializing
String
objects in a variety of ways. Four
of the constructors are demonstrated in the
main
method of Fig. 14.1.
1
// Fig. 14.1: StringConstructors.java
2
// String class constructors.
3
4
public class
StringConstructors
5
{
6
public
static
void
main(String[] args)
7
{
8
char
[] charArray = {
'b'
,
'i'
,
'r'
,
't'
,
'h'
,
' '
,
'd'
,
'a'
,
'y'
};
9
String s =
new
String(
"hello"
);
10
11
// use String constructors
String s1 =
new
String();
String s2 =
new
String(s);
String s3 =
new
String(charArray);
String s4 =
new
String(charArray,
6
,
3
);
12
13
14
15
16
17
System.out.printf(
18
"s1 = %s%ns2 = %s%ns3 = %s%ns4 = %s%n"
, s1, s2, s3, s4);
19
}
20
}
// end class StringConstructors
s1 =
s2 = hello
s3 = birth day
s4 = day
Fig. 14.1
|
String
class constructors.