Escape Sequence in Java

Escape sequence is a character which is preceded by the backslash (\). Compiler has special meaning for escape sequences.

Use of Escape Sequences

Sometimes we may need to print some text within double quotes or we may need insert a new line in between texts. So these escape sequences were introduced to perform these special operations.

List of Escape Sequences in Java:

Escape SequenceDescription
\nInsert newline in the text at this point.
\rInsert a carriage return in the text at this point.
\fInsert a formfeed in the text at this point.
\bInsert a backspace in the text at this point.
\tInsert a tab in the text at this point.
\\Insert a backslash character in the text at this point.
\’Insert a single quote character in the text at this point.
\”Insert a double quote character in the text at this point.

Let us look at an Example code :

public class EscapeSequence {

	public static void main(String[] args) {

		// enclosing code within double quotes using escape sequence - \"
		System.out.println("Tech4Humans post \"code\" related info");
		
		//adding new line using escape sequence - \n
		System.out.println("Tech4Humans also post tech memes.\nThese memes are very funny.");
	}

}

Output

Tech4Humans post "code" related info
Tech4Humans also post tech memes.
These memes are very funny.

Leave a Comment