“You will face many defeats in life, but never let yourself be defeated” Maya Angelou
There are some characters in computers that don’t have a written symbol which makes them non-printable.
For example:
-
White-space: Tab, backspace, newline, space.
-
Form feed
Also because we use single quotations when want to assign characters to a variable typed char. We can’t use the single quotation itself as the value to be stored in a char-variable.
For example:
//WRONG
char character = ''';
Likewise the use of double quotation as the value of a variable of type String is not allowed.
//WRONG
String str = """;
When a compiler tries to compile this statement, it will get confused about where the first and last quotation marks are! And so it will stop compiling and returns error instead.
But the Java language brought an alternative to these characters which is called escape-sequence. They allow us to use these non-printable characters as well as special symbols like single and double quotation marks as the value for variables of type char and String in a program.
The effect of using these escape-sequence is exactly the same as if we’re using those especial characters.
List of Escape Sequences in Java:
| Sequence | Meaning |
|---|---|
| b | Backspace |
| f | Form feed |
| n | Newline |
| r | Carriage return |
| t | Horizontal tab |
| \ | Backslash () |
| ‘ | Single quote (‘) |
| “ | Double quote (“) |
Example of Escape sequence:
char character = ''';
Now because we used the escape-sequence of the single-quotation mark, the character variable can store the single-quotation mark and the compiler will not complain about this statement any more.
Another escape sequence example:
public class Simple {
public static void main(String[] args){
System.out.println("tt"+" John Doe");
}
}
Output:
John Doe
In this example we’ve added two tab via t escape sequence to the message that we sent to the output stream.