Escape Sequences in Java
Escape sequences in Java are special character combinations used inside strings and characters to represent whitespace characters, special symbols, or non-printable characters. They begin with a backslash (\
) followed by a specific character.
List of Common Escape Sequences in Java
Escape Sequence | Meaning |
---|---|
\b |
Backspace |
\t |
Tab (horizontal tab) |
\n |
Newline (moves cursor to the next line) |
\r |
Carriage return (moves cursor to the beginning of the line) |
\f |
Form feed (used in printers, not common in Java) |
\' |
Single quote (used inside character literals) |
\" |
Double quote (used inside string literals) |
\\ |
Backslash (used to represent \ itself) |
Examples of Escape Sequences in Java
1. Using Escape Sequences in Strings
public class EscapeExample {
public static void main(String[] args) {
System.out.println("Hello\nWorld!"); // Newline
System.out.println("Hello\tWorld!"); // Tab space
System.out.println("She said, \"Java is awesome!\""); // Double quote
System.out.println("This is a backslash: \\"); // Backslash
}
}
Output:
Hello
World!
Hello World!
She said, "Java is awesome!"
This is a backslash: \
2. Using Escape Sequences in File Paths
Since Windows file paths use backslashes (\
), you need to escape them:
public class FilePathExample {
public static void main(String[] args) {
System.out.println("C:\\Users\\John\\Documents\\file.txt");
}
}
Output:
C:\Users\John\Documents\file.txt
3. Printing Special Characters
public class SpecialChars {
public static void main(String[] args) {
System.out.println("Single quote: \' ");
System.out.println("Double quote: \" ");
}
}
Output:
quote: '
Double quote: "
4. Using \r
and \b
(Carriage Return and Backspace)
public class BackspaceExample {
public static void main(String[] args) {
System.out.println("Hello\b World!"); // Removes 'o'
System.out.println("Java\rPython"); // Overwrites "Java" with "Python"
}
}
Output:
Hell World!
Python
Key Takeaways
Escape sequences start with
\
and represent special characters.
\n
, \t
, and \"
are commonly used in Java.
Backslashes (
\
) must be escaped when used in file paths.
Leave a comment