Java Reference
In-Depth Information
sense, producing the result 69 . That number is then concatenated with the string,
producing a larger string that gets printed.
We revisit this type of situation later in this chapter when we formalize the
precedence rules that define the order in which operators get evaluated.
Escape Sequences
Because the double quotation character ( " ) is used in the Java language to
indicate the beginning and end of a string, we must use a special technique to
print the quotation character. If we simply put it in a string ( """ ), the compiler
gets confused because it thinks the second quotation character is the end of
the string and doesn't know what to do with the third one. This results in a
compile-time error.
To overcome this problem, Java defines several escape sequences
to represent special characters. An escape sequence begins with the
backslash character (\), which indicates that the character or char-
acters that follow should be interpreted in a special way. Figure 2.1
lists the Java escape sequences.
The program in Listing 2.4, called Roses , prints some text resembling a poem. It
uses only one println statement to do so, despite the fact that the poem is several
lines long. Note the escape sequences used throughout the string. The \n escape
sequence forces the output to a new line, and the \t escape sequence represents a
tab character. The \" escape sequence ensures that the quote character is treated
as part of the string, not the termination of it, which enables it to be printed as
part of the output.
VideoNote
Example using strings
and escape sequences.
KEY CONCEPT
An escape sequence can be used to
represent a character that would oth-
erwise cause compilation problems.
Escape Sequence
Meaning
\b
\t
\n
\r
\"
\'
\\
backspace
tab
newline
carriage return
double quote
single quote
backslash
FIGURE 2.1
Java escape sequences
 
Search WWH ::




Custom Search