What are escape sequences in Java?

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.

Common escape sequences

Below are some commonly used escape sequences in Java.

\t: Inserts a tab

This sequence inserts a tab in the text where it’s used.

\n: Inserts a new line

This sequence inserts a new line in the text where it’s used.

\r: Inserts a carriage return

This 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 quote

This sequence inserts a single quote character in the text where it’s used.

\": Inserts a double quote

This sequence inserts a double quote character in the text where it’s used.

\\: Inserts a backslash

This sequence inserts a backslash character in the text where it’s used.

Implementation

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 shot
System.out.println( "Edpresso\tshot" );
// Add a new line after Edpresso
System.out.println( "Edpresso\nshot" );
// Add a carriage return after Edpresso
System.out.println( "Edpresso\rshot" );
// Add a single quote between Edpresso and shot
System.out.println( "Edpresso\'shot" );
// Add a double quote between Edpresso and shot
System.out.println( "Edpresso\"shot" );
// Add a backslash between Edpresso and shot
System.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
1 of 2

But we get:

Edpressoshot

because this sequence depends on the console being used.


Copyright ©2024 Educative, Inc. All rights reserved