Java Reference
In-Depth Information
Display 1.5 String Indexes
The 12 characters in the string "Java is fun." have indexes 0 through 11 .
0
1
2
3
4
5
6
7
8
9
10
11
J
a
v
a
i
s
f
u
n
.
Notice that the blanks and the period
count as characters in the string.
Escape Sequences
A backslash, \ , preceding a character tells the compiler that the character following
the \ does not have its usual meaning. Such a sequence is called an escape sequence
or an escape character . The sequence is typed in as two characters with no space
between the symbols. Several escape sequences are defined in Java.
If you want to put a backslash, \ , or a quote symbol, " , into a string constant, you
must escape the ability of the " to terminate a string constant by using \" , or the abil-
ity of the \ to escape, by using \\ . The \\ tells the compiler you mean a real backslash,
\ , not an escape sequence, and \" means a quote character, not the end of a string con-
stant. A list of escape sequences is given in Display 1.6.
It is important to note that each escape sequence is a single character, even though
it is spelled with two symbols. So, the string "Say \"Hi\"!" contains 9 characters ( 'S' ,
'a' , 'y' , the blank character, '\"' , 'H' , 'i' , '\"' , and '!' ), not 11 characters.
Including a backslash in a quoted string is a little tricky. For example, the string
"abc\def" is likely to produce the error message “Invalid escape character.” To include
a backslash in a string, you need to use two backslashes. The string "abc\\def" , if out-
put to the screen, would produce
backslash \
escape
sequence
abc\def
Display 1.6 Escape Sequences
\" Double quote.
\' Single quote.
\\ Backslash.
\n New line. Go to the beginning of the next line.
\r Carriage return. Go to the beginning of the current line.
\t Tab. White space up to the next tab stop.
 
Search WWH ::




Custom Search