Page 118 - Introduction to Programming with Java: A Problem Solving Approach
P. 118
84 Chapter 3 Java Basics
\t move the cursor to the next tab stop
\n newline—go to first column in next line \r return to first column in current line
\" print a literal double quote \' print a literal single quote \\ print a literal backslash
Figure 3.9 Common escape sequences
If you print the tab character (\t), the computer screen’s cursor moves to the next tab stop. The com- puter screen’s cursor is the position on the screen where the computer prints next. If you print the newline character (\n), the computer screen’s cursor moves to the beginning of the next line.
Here’s an example of how you could print two column headings, BALANCE and INTEREST, sepa- rated by a tab, and followed by a blank line:
System.out.println("BALANCE" + '\t' + "INTEREST" + '\n');
Note that escape sequences are indeed characters, so to print the tab and newline characters, we’ve sur- rounded them with single quotes.
Normally the compiler interprets a double quote, a single quote, or a backslash as a control character. A control character is in charge of providing special meaning to the character(s) that follows it. The double
Apago PDF Enhancer
quote control character tells the computer that the subsequent characters are part of a string literal. Like- wise, the single quote control character tells the computer that the subsequent character is a char literal. The backslash control character tells the computer that the next character is to be interpreted as an escape sequence character.
But what if you’d like to print one of those three characters as is and bypass the character’s control functionality? To do that, preface the control character (double quote, single quote, backslash) with a back- slash. The initial backslash turns off the subsequent character’s control functionality and thus allows the subsequent character to be printed as is. If that doesn’t make sense, all you really have to know is this:
To print a double quote, use \". To print a single quote, use \'. To print a backslash, use \\.
Suppose you’d like to print this message:
"Hello.java" is stored in the c:\javaPgms folder.
Here’s how to do it:
System.out.println('\"' + "Hello.java" + '\"' +
" is stored in the c:" + '\\' + "javaPgms folder.");
Embedding an Escape Sequence within a String
Write a print statement that generates this heading for a computer-specifications report:
HARD DISK SIZE
RAM SIZE ("MEMORY")