Java String Special Characters
Some characters cannot be typed directly inside a String because they would confuse the compiler, such as a double quote inside double-quoted text. Java solves this with escape sequences: a backslash followed by a character that carries a special meaning.
Why Escape Characters Exist
A String begins and ends with a double quote. If you try to put a double quote in the middle of the text, Java thinks the String has ended early and reports an error. To include such characters safely, you escape them with a backslash so Java treats them as ordinary text.
Escaping a double quote
String quote = "She said \"hello\" to me.";
System.out.println(quote); // She said "hello" to me.Common Escape Sequences
The table below lists the escape sequences you will use most often. Each one starts with a backslash. They let you insert quotes, backslashes, and invisible formatting characters like tabs and new lines.
New lines and tabs
System.out.println("Name:\tAda\nRole:\tPioneer");
// Name: Ada
// Role: PioneerShowing a File Path
File paths on Windows use backslashes, so you must double each one inside a String. Otherwise Java would read the single backslash as the start of an escape sequence and likely fail to compile.
A Windows path
String path = "C:\\Users\\Ada\\notes.txt";
System.out.println(path); // C:\Users\Ada\notes.txt- Every escape sequence starts with a backslash (\).
- Use \n to break a line and \t to align columns of text.
- Double the backslash (\\) whenever you need a literal backslash.
- Escape sequences count as a single character inside the String.