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.
| Escape Sequence | Unicode | Description |
|---|---|---|
| \b | \u0008 | Backspace |
| \t | \u0009 | Horizontal Tab |
| \n | \u000a | Newline |
| \f | \u000c | Formfeed |
| \r | \u000d | Carriage Return |
| \' | \u0027 | Single Quote |
| \" | \u0022 | Double Quote |
| \\ | \u005c | Backslash |
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
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
\.\uXXXX) for any character.Topic: Escape-sequences | Language: Java
System.out.println("Hello\nWorld");System.out.println("Java\tRocks");System.out.println("She said, \"Java is fun!\"");System.out.println("C:\\Program Files\\Java");System.out.println("ABC\bD");