Escape sequences – special characters

Escape sequences in Java are used to represent special characters within string literals. These sequences are formed by a backslash (\) followed by a character or a series of characters. Escape sequences allow the inclusion of characters that are otherwise difficult to express directly in strings, such as newlines, tabs, or quotes.

Table of Escape Sequences

Escape SequenceDescription
\\Backslash
\'Single quote
\"Double quote
\nNewline
\tHorizontal tab
\rCarriage return
\bBackspace
\fForm feed
\uXXXXUnicode character with 16-bit hex value XXXX

Example 1: Using Escape Sequences for Special Characters

public class EscapeSequenceExample {

    public static void main(String[] args) {
        // Example 1: Using escape sequences for special characters
        String message = "Hello,\n\tJava!\nI hope you're learning a lot.\n\nThis is a backslash: \\\nAnd this is a double quote: \"";

        System.out.println(message);
    }
}

Explanation:

  • \n is used for a newline character. It moves the cursor to the next line.
  • \t is used for a tab character. It adds a tab space.
  • \\ is used to insert a literal backslash \. In Java strings, a single backslash \ is used to escape special characters, so \\ is necessary to display a single backslash.
  • \" is used to insert a double quote character " within a string that is already enclosed in double quotes. This escapes the character to prevent the string from being prematurely terminated.

Output: When you run the code, the output will be:

Hello,
    Java!
I hope you're learning a lot.

This is a backslash: \
And this is a double quote: "

In this example:

  • The string message contains multiple lines of text separated by \n for newlines and \t for tabs.
  • It also includes examples of \\ to display a single backslash and \" to include double quotes within a string enclosed by double quotes.

Example 2: Using Unicode Escape Sequence

public class UnicodeEscapeExample {

    public static void main(String[] args) {
        // Example 2: Using Unicode escape sequence
        String unicodeString = "\u0048\u0065\u006C\u006C\u006F, \u4E16\u754C!";

        System.out.println(unicodeString);
    }
}

Explanation:

  • \uXXXX is the Unicode escape sequence where XXXX represents the hexadecimal code of the Unicode character.
  • In this example, \u0048 corresponds to the Unicode character ‘H’, \u0065 corresponds to ‘e’, \u006C corresponds to ‘l’, \u006F corresponds to ‘o’, \u4E16 corresponds to the Chinese character ‘世’, and \u754C corresponds to ‘界’.
  • When the program is executed, it prints: Hello, 世界!.