Chapter 3
Formatted Printing
Escape Sequences
Escape sequences are groups or characters that allow you to format output within a string. They begin with a backslash character.
- \n inserts a new line
- \" creates a double quote (") symbol within a string (and \' creates a single quote)
- \\ creates a backslash (note the need for the second backslash to indicate that an actual backslash character is desired)
- \t creates a tab
For example,
System.out.println("This\nis how \"escape sequences\" work");
produces
This
is how "escape sequences" work
because the \n moves to a new line and the \" creates a double quote (note that if the " were written without the backslash, it would end the string prematurely).
The printf method
You will often want to format decimal values so that they round to a certain number of places. For that, you can use the printf method of System.out, as follows. Note that you first define the format as a string inside " ", then write a comma, then the value(s) to be printed (separated by commas for multiple values). The % symbol in this context indicates a placeholder, i.e., that a value is to be printed. For %f, The number following the decimal point indicates the number of decimal places to round to, and the f indicates a ffloat (i.e., a number with a decimal point)
System.out.printf("%.2f", 42.34626); //2 is the number of decimal places
System.out.println(); //needed to go to the next line of the console
//You can combine fixed text (e.g. "Pi is about") with format specifiers, like so
System.out.printf("Pi is about: %.3f", 3.1415926);
outputs
42.35
Pi is about: 3.142
printf can also specify integers (by using %d) and Strings (using %s). A new line is created with %n, rather than the \n escape sequence that print and println use. Also notice in the example the use of more than one placeholder in the format string.
//using other format specifiers
System.out.printf("Her name is %s%n and her number is %d", "Kiera",35);
outputs
Her name is Kiera
and her number is 35
More on printf is here.