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
\t Insert a tab (horizontal space) “Hello\tWorld” Hello World
\0 Null character (no visual output in Apex log) “Hello\0World” HelloWorld

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 info = “Name:\tJohn\nAge:\t28\nLocation:\t\”New York\””;

System.debug(info);

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

She said, “Learning Apex is fun!” 

2. Write an Apex program that prints the file path

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

Line 1: Apex Escape Sequences   

Line 2: Used in Strings 

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

Name:     Adnan   

Course:   Apex Basics   

 

Course Video