Escape Sequences in Java

In Java, special characters can be represented using escape sequences. They start with a backslash (\) and are mainly used in char and String literals to represent characters that are otherwise hard to type or have special meaning.


  • Escape sequences allow you to insert special characters like newline, tab, quotes, or backslash into strings.

  • They are written using a backslash (\) followed by a character or Unicode code.

Common Escape Sequences

Escape Sequence Unicode Description
\b\u0008Backspace
\t\u0009Horizontal Tab
\n\u000aNewline
\f\u000cFormfeed
\r\u000dCarriage Return
\'\u0027Single Quote
\"\u0022Double Quote
\\\u005cBackslash
Example: Using Escape Sequences
Test.java Copy Code
class Test {
    public static void main(String []arg) {
        System.out.print("C Prowess");
        System.out.print("\tC++ Prowess");
        System.out.print("\nJava Prowess");
    }
}
    

Output:

C Prowess        C++ Prowess
Java Prowess
More Examples

1. Newline (\n) inserts a new line:

String newLine = "Hello\nWorld";
System.out.println(newLine);
// Output:
// Hello
// World

2. Tab (\t) inserts horizontal spacing:

String tab = "Java\tProgramming";
System.out.println(tab);
// Output: Java    Programming

3. Backslash (\\) inserts a backslash:

String backslash = "C:\\Program Files\\Java";
System.out.println(backslash);
// Output: C:\Program Files\Java

4. Single Quote (\'):

String singleQuote = "It\'s raining";
System.out.println(singleQuote);
// Output: It's raining

5. Double Quote (\"):

String doubleQuote = "He said, \"Hello\"";
System.out.println(doubleQuote);
// Output: He said, "Hello"

6. Carriage Return (\r):

String carriageReturn = "Hello\rWorld";
System.out.println(carriageReturn);
// Output: World

7. Unicode (\uXXXX):

String unicode = "\u00A9 2023";
System.out.println(unicode);
// Output: ยฉ 2023
Notes
  • Escape sequences are always introduced by \.
  • They are useful for formatting text and inserting special characters.
  • You can also use Unicode escapes (\uXXXX) for any character.

Next: Java Operators



๐Ÿš€ Quick Knowledge Check

Topic: Escape-sequences | Language: Java

Q1. What will be the output of this code?
System.out.println("Hello\nWorld");
Q2. What will this code print?
System.out.println("Java\tRocks");
Q3. What will be the output?
System.out.println("She said, \"Java is fun!\"");
Q4. What will this code output?
System.out.println("C:\\Program Files\\Java");
Q5. Predict the output:
System.out.println("ABC\bD");