Escape sequences – special characters

Escape sequences are a set of characters that are used to represent special characters or characters that cannot be typed in the source code of a Java program. They begin with a backslash character () followed by one or more characters that represent the special meaning.

Some common escape sequences in Java include:

These escape sequences are often used in String literals to represent special characters that cannot be typed directly in the code. For example, to create a String that contains a double quote character, you can use the escape sequence “:

String str = “The quick brown “fox” jumps over the lazy dog.”;

Similarly, to create a String that contains a newline character, you can use the escape sequence \n:

String str = “The quick brown\nfox\njumps over the lazy dog.”;

By using escape sequences, you can make your code more readable and maintainable by avoiding the need for complex character encoding schemes.

Example

class EscapeSequences {
	public static void main(String[] args) {
		System.out.println("Heading:\n\'single quote\'\n\"double quote\"\foffset1\foffset2\foffset3\foffset4\nnew line");
	}
}
Output
'single quote'
"double quote"
              offset1
                     offset2
                            offset3
                                   offset4
new line
Code Explanation

This code is defines a class called EscapeSequences that contains a main method. The main method uses escape sequences to format the text that it outputs to the console.

Here’s a step-by-step explanation of what the code does:

  1. The code defines a class called EscapeSequences using the class keyword.
  2. The main method is declared as public static void, which means it’s a public method that doesn’t return a value and can be invoked without creating an instance of the EscapeSequences class. The method takes an array of strings, args, as its argument, which contains the command-line arguments passed to the Java program when it’s run.
  3. Within the main method, the System.out.println method is called with a string argument that contains various escape sequences.

Here’s what each escape sequence does:

  • \n represents a newline character, which causes the text that follows to be printed on a new line.
  • \' is a single quote escape sequence, which allows a single quote character to be included within a string literal.
  • \" is a double quote escape sequence, which allows a double quote character to be included within a string literal.
  • \f represents a form feed character, which causes the text that follows to be offset to the right.
  • offset1, offset2, offset3, and offset4 are just text that will be offset to the right due to the form feed characters.