Escape sequence & Verbatim String in Java
In Java, escape sequences are used similarly to C#, allowing for the inclusion of non-printable or special characters within strings. These sequences start with a backslash (\), followed by a specific character that represents the desired effect.
Escape Sequence | Description | Example | Output |
---|---|---|---|
\’ | Output a single quote | “It\’s” | It’s |
\” | Output a double quote | “\”Hello\”” | \\ |
\\ | Output a backslash. Usually used for defining a path on the server e.g., C:\Windows | “C:\\Windows” | C:\Windows |
\n | Insert a new line | “Line1\nLine2” |
Line1 Line2 |
\r | Insert a carriage-return, delete previous word | “Hello\rWorld” | World |
\t | Insert one-character blank space | “Hello\tWorld” | Hello World |
\0 | Add null character between hello and world\0 | “Hello\0World” | Hello |
\b | Insert a backspace i.e. delete 1 character before \b | “Hello\bWorld” | HellWorld |
Verbatim Strings in Java
Java does not have a direct equivalent of C#’s verbatim string (with @). However, you can avoid escape sequences by using triple quotes in newer versions (Java 13+) through text blocks. Text blocks allow you to write multiline strings without needing to escape special characters.
For example:
Description | Example | Output |
---|---|---|
Verbatim string with newline | “””Hello\nWorld””” | Hello\nWorld |
In text blocks, escape sequences like \n are treated as literal text rather than special commands, similar to how verbatim strings work in C#.
Tasks:
1. Write a Java program that prints the following text using escape sequences:
kotlin
Hello, it’s a beautiful day!
“Programming is fun,” she said.
2. Write a Java program that prints the file path C:\Program Files\MyApp using escape sequences.
3. Write a Java program that prints the following table using escape sequences:
Name Age
Alice 30
Bob 25
4. Write a Java program that demonstrates the use of the carriage return \r to replace part of a string. The initial string should be Goodbye and after applying \r, it should be Hello.
5. Write a Java program that uses the backspace \b escape sequence to correct the following string from Helllo World to Hello World.
6. Write a Java program that inserts a null character \0 between two words and prints the string. The output should demonstrate that the null character does not affect the visible output. For example, the string should be Hello\0World.
7. Write a Java program that prints the string Hello\nWorld exactly as it is, without interpreting the \n as a newline character.