Special Characters
In short: Characters in a String literal that have a special meaning and therefore have to be “escaped” with a backslash — e.g. \n (line break), \t (tab), \" (quote mark within the string).
In more detail: Without escaping, for example, a quote mark within a string couldn’t be distinguished from its end: "He said \"Hello\"". A literal backslash also needs escaping (\\), since a single backslash would otherwise be interpreted as the start of an escape sequence.
In Depth
System.out.println("Line 1\nLine 2"); // line break
System.out.println("Name\tAge"); // tab
System.out.println("He said \"Hello\""); // quote mark within the string
System.out.println("C:\\Users\\Document.txt"); // literal backslash
System.out.println("Unicode: \u00e4"); // ä via Unicode escapeThe most important escape sequences in Java: \n (line break), \t (tab), \" (double quote mark), \' (single quote mark), \\ (backslash), and \uXXXX (any Unicode character via its four-digit hex code). Since Java 15, there are additionally text blocks ("""..."""), which allow multi-line text with no \n escapes and no escaping of normal quote marks — handy for embedded HTML, JSON, or SQL directly in the code:
String html = """
<html>
<body>Hello</body>
</html>
""";A common beginner mistake: writing a Windows file path as "C:\Users\Document.txt" — the compiler interprets \U, \D as invalid escape sequences and reports an error, because every single backslash has to be doubled.
Further escape sequences
Besides the common ones, there’s also \b (backspace), \f (form feed, practically unused today), \r (carriage return — common together with \n as a line ending on Windows), and \0 (null character). A line break that looks correct on all operating systems is therefore often not hardcoded as \n, but obtained via System.lineSeparator(), since Windows internally expects \r\n, while Unix-like systems expect only \n.
Escaping in RegEx vs. strings — two levels at once
An especially confusing case arises when a regular expression is written as a string literal: regex has ITS OWN escaping (e.g. \d for a digit, \. for a literal dot), which exists INDEPENDENTLY of Java’s own string escaping. A dot that’s meant literally in a regex therefore has to be escaped twice — once for Java, once for the regex engine:
String pattern = "\\d+\\.\\d+"; // Java string: \d+\.\d+ | regex: a number with a decimal point
boolean isNumber = "3.14".matches(pattern); // trueSince Java 15, text blocks help exactly here: since they don’t need to escape normal quote marks, at least this one level of nesting goes away, even though \d still retains its regex-specific meaning.