Backslash codes are characters that cannot be entered from the keyboard and are nonprinting characters. It can be used anywhere you can use a normal character. It is also referred to as escape sequences.
The single most important backslash code is \n. It is also referred to as a newline character.
Note that the backslash codes are character constants. To assign backslash character to a character variable, you must enclose it within single quotes.
Example of Assigning backslash code to a character variable
char = ch;
ch = '\'';
Below are the Backslash Codes available in java.
Backslash Code | Description |
\t | tab character ('\u0009') |
\n | new line or line feed character ('\u000A') |
\r | carriage-return character ('\u000D') |
\f | form-feed character ('\u000C') |
\a | alert or bell character ('\u0007') |
\e | escape character ('\u001B') |
\cx | control character corresponding to x |
\\ | backslash character |
\0n | character with octal value 0n (0 <= n <= 7) |
\0nn | character with octal value 0nn (0 <= n <= 7) |
\0mnn | character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7) |
\xhh | character with hexadecimal value 0xhh |
\uhhhh | character with hexadecimal value 0xhhhh |
Examples of Backslash Codes
Example 1 : Program that displays use of tab character
class TabCharDemo
{
public static void main(String args[])
{
System.out.println("Program of \t - " + \t + "character.");
}
}
Output
Program of \t - character.
Example 2 : Program that displays use of newline character
class NewLineCharDemo
{
public static void main(String args[])
{
System.out.print("This is first line.\n");
System.out.print("This is second line.");
System.out.print("This is third line.");
}
}
Output
This is first line.
This is second line.This is third line.