Apex Escape Sequences (in Strings)

Simulate inserting middle name into full name.

Apex Escape Sequences (in Strings)

Escape sequences are special characters that allow you to include non-printable characters within strings. They help you represent characters that can’t be typed directly, like tabs (a blank space), newline, or quotes (). In Apex, escape sequences are also denoted by a backslash (\) followed by a specific character that has special meaning for the compiler. 

Escape Sequences in Apex

Escape Sequence Description Example Output
\” Output a double quote “\”Hello\”” “Hello”
\\ Output a backslash “C:\\\\Windows” C:\Windows
\n Insert a new line “Line1\nLine2” Line1 Line2
\r Insert a tab (horizontal space) “Hello\tWorld” Hello World
\0 Null character (no visual output in Apex log) “Hello\0World” HelloWorld
\b Backspace (removes one char before it) “Hello\bWorld” HellWorld

Note: Some escape sequences like \b or \0 might not show visible effects in the Apex Developer Console, but they’re valid in the language. 

Code Examples

1. Print Text with Quotes and Newline

String message = ‘Hello, it\’s a beautiful day!\n\”Programming is fun,\” she said.’;

System.debug(message);

2. Print File Path with Backslashes

String filePath = ‘C:\\Program Files\\MyApp’;

System.debug(filePath);

3. Using Backspace (\b)

String message = ‘Hello\bWorld’;

System.debug(message);

4. Combining Multiple Escape Sequences

String info = “Name:\tJohn\nAge:\t28\nLocation:\t\”New York\””;

System.debug(info);

Tasks:

1. Write an Apex program that prints the following using escape sequences

2. Write an Apex program that prints the file path

3. Write an Apex program that prints this tab-separated list

4. Write an Apex program that demonstrates the use of \r (carriage return)