Escape Sequences

🙋 Need help? Ask an expert now!

Escape sequences allow you to get out of the String to print characters that cannot exist within the string itself. The three escape sequences are \ , \" and \n. Let's see if we can decipher what each one does by looking the code below.
package exlcode;

public class EscapeSequenceExample {

  public static void main(String[] args) {
    // without the second backslash, a syntax error will occur
    // without the backslash, a syntax error will occur
    System.out.println("\"Hello World!\"");
    // \n prints "Java" on a new line
    System.out.println("Hello World!" + "\nJava");
  1. \\

    Permits a '\' to be included in the String. One '\' is used to escape the string, and the second '\' is added into the string.

  2. \"

    Using one \" on each side of characters and enclose them in quotations when printing. Since the double-quotations are used to denote a String in the source code, we need to use something else, the backslashes, to tell the program to print "" in the output.

  3. \n

    Makes a new line, so anything in the String after the "\n" prints on a new line. In the example above, "Java" is printed on a new line because there is an "\n" directly before it in the code.

Keep these useful tools in mind when working with strings.

Application Question

Which of the following statements show the correct use of an escape sequence?