Home » Java » Java Character Escape Sequences With Examples

Java Character Escape Sequences With Examples

In Java, characters that are impracticable to enter directly, various escape sequences allow you to enter the character you need. The following is the list of Java character escape sequences with examples:

Java Character Escape Sequences

\ddd   - Octal Character (ddd)
\uxxxx - Hexadecimal Unicode Character
\'     - Single Quote
\"     - Double Quote
\\     - Backslash
\r     - Cariage Return
\n     - New Line or Line Feed
\f     - Form Feed
\t     - Tab
\b     - Backspace

Examples

Below are the examples of each character escape sequence.

\ddd

public class charEscSeq {
    public static void main(String args[]) {
        System.out.println("Result for \\ddd is: " + "2");
    }
}

Output

Result for \ddd is: j

\uxxxx

public class charEscSeq {
    public static void main(String args[]) {
        System.out.println("Result for \\uxxxx is Japenese Katakana character: " + "\ua432");
    }
}

Output

Result for \uxxxx is Japenese Katakana character: ꐲ

\'

public class charEscSeq {
    public static void main(String args[]) {
        System.out.println("What is your pet\'s name?");
    }
}

Output

What is your pet's name?

\"

public class charEscSeq {
    public static void main(String args[]) {
        System.out.println("This is in double \"quotes\".");
    }
}

Output

This is in double "quotes".

\\

public class charEscSeq {
    public static void main(String args[]) {
        System.out.println("The file x.txt is in the folder D:\\my_files\\");
    }
}

Output

The file x.txt is in the folder D:\my_files\

\r

public class charEscSeq {
    public static void main(String args[]) {
        System.out.println("Carriage Return" + "\rEnter Pressed");
    }
}

Output

Enter Pressed

\n

public class charEscSeq {
    public static void main(String args[]) {
        System.out.println("First line.\nSecond line.");
    }
}

Output

First line.
Second line.

\f

public class charEscSeq {
    public static void main(String args[]) {
        System.out.println("Used for printers to start a new page from here.\f Some more text.");
    }
}

Output

Used for printers to start a new page from here. Some more text.

\t

public class charEscSeq {
    public static void main(String args[]) {
        System.out.println("Between \ttab key pressed.");
    }
}

Output

Between 	tab key pressed.

\b

public class charEscSeq {
    public static void main(String args[]) {
        System.out.println("Between \bbackspace key pressed.");
    }
}

Output

Betweenbackspace key pressed.

See also: