2.1 The Elements of Java Programs | 53
Don’t worry if you don’t understand everything shown here. This code includes some elements
of Java that we have not yet explained. By the end of the chapter, it should all be clear to you.
The StringClass Whereas a value of type charis limited to a single character, a string(in the
general sense) is a sequence of characters, such as a word, name, or sentence, enclosed in
double quotes. In Java, a string is an object, an instance of the Stringclass. For example, the
following are strings in Java:
“Introduction to “ “Programming and Problem Solving” “ with Java “ “.”
A string must be typed entirely on one line. For example, the string
“This string is invalid because it
is typed on more than one line.”
is not valid because it is split across two lines before the closing double quote. In this situa-
tion, the Java compiler will issue an error message at the first line. The message may say some-
thing like QUOTE EXPECTED, depending on the particular compiler.
The quotes are not considered to be part of the string but are simply there to distin-
guish the string from other parts of a Java class. For example,”amount”(in double quotes) is
the character string made up of the letters a,m,o,u,n, and tin that order. On the other hand,
amount(without the quotes) is an identifier, perhaps the name of a place in memory. The
symbols ” 12345 ”represent a string made up of the characters 1 , 2 , 3 , 4 , and 5 in that order. If
we write 12345 without the quotes, it is an integer quantity that can be used in calculations.
A string containing no characters is called the empty string. We write the empty string us-
ing two double quotes with nothing (not even spaces) between them:
“”
The empty string is not equivalent to a string of spaces; rather, it is a special string that con-
tains no characters.
To write a double quote within a string, we use another escape sequence,\”. Here is a
string containing both quotation marks and the escape sequence for a backslash:
“She said, \”Don’t forget that \ is not the same as the / character.\””
The value of this string is
She said, “Don’t forget that \ is not the same as the / character.”
Notice that within a string we do not have to use the escape sequence \’to represent a sin-
gle quote. Similarly, we can write the double quote as a value of type char(’”’) without us-
ing an escape sequence. In contrast, we have to use \to write a backslash as a charvalue
or within a string.