Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 3 ■ DATA TYPES


// which will produce this: ' is my favorite character
// (my actual favorite character is ;)

// And now the backslash itself
// The following line throws an error because it's missing a closing "
// (The compiler takes \" as a literal " and then can't find an end to the string.)
System.out.println("I want a \");
// so the line has to be
System.out.println("I want a \\");
// which will produce this: I want a \

Java also supports several special escape sequences (all beginning with a backslash). Table 3-3
shows each escape sequence and describes its effect. It begins with the three we already covered.

Table 3-3. Escape sequences

Escape Sequence Effect

\' Create a single quotation mark

\" Create a double quotation mark

\\ Create a backslash character

\n Create a new line (often called the newline character)

\t Create a tab

\b Create a backspace character (which might delete the preceding character,
depending on the output device)

\r Return to the start of the line (but do not make a new line)

\f Form feed (move to the top of the next page for printers)

\a The alert (or bell) character

The newline character (\n) sees a lot of use for things like creating readable error messages,
separating lines in files, and other output. Tabs are less common but still sometimes used (to line up
pieces of output to make things easier to read). The others are much more rarely used, because software
developers hardly ever create unstructured output these days. When programmers used punch cards for
input and line printers for output, programmers made extensive use of the form feed and start-of-line
characters. We still produce plenty of output, of course, but it's usually HTML, XML, or some other
structured format.
In addition to being possible values for variables of type char, String objects can also contain
escape sequences. Many String objects contain a newline sequence or two. Listing 3-4 shows a short
example.
Free download pdf