Escape sequences are used to signal an alternative interpretation of a series of characters. In Java, a character preceded by a backslash (\) is an escape sequence.
The Java compiler takes an escape sequence as one single character that has a special meaning.
Below are some commonly used escape sequences in Java.
\t
: Inserts a tabThis sequence inserts a tab in the text where it’s used.
\n
: Inserts a new lineThis sequence inserts a new line in the text where it’s used.
\r
: Inserts a carriage returnThis sequence inserts a carriage return in the text where it’s used. It’s expected to move the cursor back to the beginning of the line without moving down the line.
Note: Its output depends on the console being used. You may see the cursor moving down the line, or not moving at all.
\'
: Inserts a single quoteThis sequence inserts a single quote character in the text where it’s used.
\"
: Inserts a double quoteThis sequence inserts a double quote character in the text where it’s used.
\\
: Inserts a backslashThis sequence inserts a backslash character in the text where it’s used.
In the example below, the above escape sequences are shown in action:
class EscapeSequences{public static void main( String args[] ){// Add a tab between Edpresso and shotSystem.out.println( "Edpresso\tshot" );// Add a new line after EdpressoSystem.out.println( "Edpresso\nshot" );// Add a carriage return after EdpressoSystem.out.println( "Edpresso\rshot" );// Add a single quote between Edpresso and shotSystem.out.println( "Edpresso\'shot" );// Add a double quote between Edpresso and shotSystem.out.println( "Edpresso\"shot" );// Add a backslash between Edpresso and shotSystem.out.println( "Edpresso\\shot" );}}
Every output matches the description provided above, except one. The expected result in the case of a \r
sequence is:
shotesso
But we get:
Edpressoshot
because this sequence depends on the console being used.