Skip to main content
Engineering LibreTexts

9.6: Escape Sequences

  • Page ID
    15212
  • It is possible to display multiple lines of output in just one line of code. You just have to tell Java where to put the line breaks.

    public class Hello {
    
        public static void main(String[] args) {
            System.out.print("Hello!\nHow are you doing?\n");
        }
    }
    

    The output is two lines, each ending with a newline character:

    Hello!
    How are you doing?
    

    The \n is an escape sequence, which is a sequence of characters that represents a special character. The backslash allows you to “escape” the string’s literal interpretation. Notice there is no space between \n and How. If you add a space there, there will be a space at the beginning of the second line.

    Table 1.6.1: Common escape sequences
    \n newline
    \t tab
    \" double quote
    \\ backslash

    Another common use of escape sequences is to have quotation marks inside of strings. Since double quotes indicate the beginning and end of strings, you need to escape them with a backslash.

    System.out.println("She said \"Hello!\" to me.");
    

    The result is:

    She said "Hello!" to me.