Java Reference
In-Depth Information
other character of a Java identifier, a whitespace character (e.g. blank, tab, or
new line), and a space character. These functions can come in handy when you
are processing strings of characters in some fashion.
5.2
Classes String and StringBuffer
A string is a sequence of characters enclosed in quotes. For example, we show
below a string of 16 characters, three of which are the blank character:
Lesson
page 5-3
"this is a string"
In this section, we discuss two classes that are used for holding and manipulat-
ing strings, classes String and StringBuffer , and write a few programs that
illustrate how strings can be processed. We begin by looking at how we write
such strings in Java.
5.2.1
String literals
In Java, a string like "it is" is called a literal of class-type String . Its length
is the number of characters in it, in this case, 5. The example in this paragraph
shows that the single-quote character ' and the blank character can appear in lit-
erals. In fact, almost any character can be written in a string literal. But some of
them have to be written in a special way.
To place a double-quote in a string literal, precede it by the escape charac-
ter \ . For example, the following literal contains a blank, a double-quote char-
acter, and the digit 2 : " \"2" .
The sequence of characters \" is known as an escape sequence . Below, we
list other escape sequences and explain what they represent:
Activity
5-3.1
backslash character \
\\
double-quote character "
\"
single-quote character '
\'
new-line character
\n
carriage-return character
\r
tab character
\t
form feed character
\f
backspace character
\b
The new-line and carriage-return characters are used in operating systems to
indicate the start of a new line. There are three major operating systems:
Windows, Macintosh, and Unix. One of them uses the new-line character, one of
them uses the carriage-return character, and one of them uses both. Such is life.
Many programs process strings of characters. For example, a text editor
does, and so does the Java compiler. But often, strings are used simply to anno-
tate output. For example, below, we write statements that print a value in the Java
console:
Search WWH ::




Custom Search