In this tutorial, we will discuss what are escape sequences or escape characters, why we need escape sequence, what is the length of the escape sequence, escape Octal and Unicode characters, and code examples. Let's dive deep into the topic:
Read Also: String Interview Questions in Java
What are Escape Sequences in JavaAccording to Java docs,
In java, a character with a backslash(\) just before it is called an escape character or escape sequence.
There are a total of 8 escape characters or escape sequences in java. Please find them below:
Why we need Escape SequenceIn Java, a String represents a sequence of characters. These characters can be alphabets, numerals, punctuation marks, etc.
The main point while creating a String in Java is that the entire sequence of characters must be placed in quotation marks. For example:
Alive is awesome!!
But what if the requirement is that String must contain quotation marks i.e quotes within quotes.
For example: " Alive is "awesome"!! "
As you might have guessed compiler gets confused while interpreting the interior quotes of the String i.e "awesome"
To make things simple for compiler we need to let it know when a quotation mark is a command (create a String)
when it is simply a character(display the word "awesome" along with quotation marks).
To solve the above problem we need character escaping. This is achieved using a special symbol \ (backslash) as shown in red color.
Let's try to print the quotes within quotes example again i.e " Alive is "awesome"!! " using \ backslash.
Alive is "awesome"!!
What is the Length of the Escape SequenceAn escape sequence is a single character in Java, so its length is 1. For example:
Escape Octal and Unicode CharactersOctal escapes from \0 to \377 can be shown using escape sequences.
Unicode escapes can be shown in the form \uXXXX, where \uXXXX represents \u0000 to \uFFFF
Examples of Escape Sequences in JavaPlease find below the examples of escape sequences in Java.
That's all for today, please mention in comments in case you have any questions related to escape sequences in Java with examples.