Java Reference
In-Depth Information
The solution is to embed what are known as escape sequences in the string literals.
Escape sequences are two-character sequences that are used to represent special char-
acters. They all begin with the backslash character ( \ ). Table 1.3 lists some of the
more common escape sequences.
Table 1.3
Common Escape Sequences
Sequence
Represents
tab character
\t
new line character
\n
quotation mark
\"
backslash character
\\
Keep in mind that each of these two-character sequences actually stands for just a
single character. For example, consider the following statement:
System.out.println("What \"characters\" does this \\ print?");
If you executed this statement, you would get the following output:
What "characters" does this \ print?
The string literal in the println has three escape sequences, each of which is two
characters long and produces a single character of output.
While string literals themselves cannot span multiple lines (that is, you cannot use
a carriage return within a string literal to force a line break), you can use the \n
escape sequence to embed newline characters in a string. This leads to the odd situa-
tion where a single println statement can produce more than one line of output.
For example, consider this statement:
System.out.println("This\nproduces 3 lines\nof output.");
If you execute it, you will get the following output:
This
produces 3 lines
of output.
The println itself produces one line of output, but the string literal contains two
newline characters that cause it to be broken up into a total of three lines of output.
To produce the same output without newline characters, you would have to issue
three separate println statements.
This is another programming habit that tends to vary according to taste. Some people
(including the authors) find it hard to read string literals that contain \n escape
sequences, but other people prefer to write fewer lines of code. Once again, you
should make up your own mind about when to use the newline escape sequence.
 
Search WWH ::




Custom Search