Java Reference
In-Depth Information
This is actually a
String
literal with a capital
S
— in other words, a constant object of the class
String
that the compiler creates for use in your program.
As I mentioned in Chapter 2, some characters can't be entered explicitly from the keyboard so you can't
include them directly in a string literal. You can't include a newline character by pressing the Enter key be-
cause doing so moves the cursor to a new line. You also can't include a double quote character as it is in
a string literal because this is used to indicate where a string literal begins and ends. You can specify all of
these characters in a string in the same way as you did for
char
constants in Chapter 2 — you use an escape
sequence. All the escape sequences you saw when you looked at
char
constants apply to strings. The state-
ment
System.out.println("This is \na string constant!");
produces the output
This is
a string constant!
because
\n
is interpreted as a newline character. Like values of type
char
, strings are stored internally as
Unicode characters. You can also include Unicode character codes in a string as escape sequences of the
form
\unnnn
where
nnnn
are the four hexadecimal digits of the Unicode coding for a particular character.
The Greek letter π, for example, is
\u03C0
.
WARNING
When you want to display Unicode characters, the environment in which they are
toappearmustsupportdisplayingUnicode.IfyoutrytowriteUnicodecharacterssuchasthat
for
π
to the command line under MS Windows, for example, they will not display correctly.
You recall from my preliminary discussion of classes and objects in Chapter 1 that a class usually con-
tains data members and methods, and naturally, this is true of the
String
class. The sequence of characters
in the string is stored in a data member of the
String
object and the methods for the
String
object enable
you to process the data in a variety of ways. I will go into the detail of how a class is defined in Chapter 5, so
in this chapter I concentrate on how you can create and use objects of the class
String
without explaining
the mechanics of why things work the way that they do. You already know how to define a
String
literal.
The next step is to learn how you declare a
String
variable and how you create
String
objects.
Creating String Objects
Just to make sure there is no confusion in your mind, a
String
variable is simply a variable that stores a ref-
erence to an object of the class
String
. You declare a
String
variable in much the same way as you define
a variable of one of the basic types. You can also initialize it in the declaration, which is generally a good
idea:
String myString = "My inaugural string";
This declares the variable
myString
as type
String
and initializes it with a reference to a
String
object
encapsulating the string
"My inaugural string"
. You can store a reference to another string in a
String