Escape Characters
In Java (and many other programming languages), escape characters are used to represent special characters or to produce characters that are difficult to type directly in the code. Escape characters are prefixed by a backslash (\
). Here are some commonly used escape characters in Java:
\n
: Newline
Represents a newline character.
System.out.println("Line 1\nLine 2");
\t
: Tab
Represents a tab character.
System.out.println("Column 1\tColumn 2");
\b
: Backspace
Represents a backspace character.
System.out.println("Back\bSpace"); // Outputs: BacSpace
\r
: Carriage Return
Represents a carriage return character.
System.out.println("Carriage\rReturn"); // Outputs: Returniage
\\
: Backslash
Represents a literal backslash.
System.out.println("C:\\Users\\Username\\Documents");
\'
: Single Quote
Represents a literal single quote.
System.out.println("He said, \'Hello!\'");
\"
: Double Quote
Represents a literal double quote.
System.out.println("She said, \"Hi!\"");
\uXXXX
: Unicode Escape
Represents a Unicode character whereXXXX
is the Unicode code point in hexadecimal.
System.out.println("\u03B1"); // Outputs: α
These escape characters are useful when you need to include special characters in strings or format text output. For example, when working with file paths, newline-separated text, or when including quotes within a string.
Remember that the backslash itself is an escape character, so if you want to include a literal backslash in a string, you need to use \\
.
System.out.println("C:\\Program Files\\Java");
Understanding and using escape characters correctly is important for creating well-formatted and readable code.