Skip Top Navigation Bar

Formatting Output with Escape Sequences

There are different ways to format program output. In this tutorial, we will explore using escape sequences to format output.

Escape Sequences

Sometimes we want to print out characters that already have a specified meaning in a String literal. For example, the double quote is used at the start and end of a String literal. How do we let the compiler know that we want to print the double quote instead of simply ending the String literal? We use an escape sequence. An escape sequence is comprised by a backslash (\) followed by a character. The backslash tells the compiler to treat the next character as special. The following is a list of some common escape sequences you might find useful.

Escape Sequence Explanation Example Example Result
\n Creates a new line characater "line one\nline two"

line one

line two

\" Inserts a double quote character in text "She said, \"Hi\"" She said, "Hi"
\' Inserts a single quote character in text "She\'s Great!" She's Great!
\\ Inserts a backslash character in text "Use a / for division not a \\" Use a / for division not a \
\t Creates a tab characater "column one\tcolumn two" column one   column two

Your Turn

Example 1

  • Predict the output of the code segement.
  • Check your prediction by running the code.

Resources

Next Learn Tutorial