When working with strings in Java, it’s important to know how to handle special characters properly. Without doing so, you may encounter errors. For instance:
String message = "We are the "Riders" of the storm.";
This line would cause an error because the double quotes around “Riders” are misinterpreted by Java. The solution is to use the backslash () escape character, which allows special characters to be included in strings.
Escape Characters
The backslash () escape character converts special characters into string characters. Here’s a list of common escape characters in Java:
Escape character | Result | Description |
---|---|---|
\’ | ‘ | Single quote |
\” | “ | Double quote |
\ | \ | Backslash |
Example 1: Using Double Quotes in Strings
To insert a double quote in a string, use the sequence \"
:
String vehicleDescription = "This \"SUV\" is perfect for family trips.";
Example 2: Using Single Quotes in Strings
To insert a single quote in a string, use the sequence \'
:
String feedback = "It's the best bike I've ever ridden.";
Example 3: Using Backslashes in Strings
To insert a single backslash in a string, use the sequence \\
:
String filePath = "C:\\Users\\Public\\Documents\\vehicle_report.txt";
Other Common Escape Sequences
Here are other commonly used escape sequences in Java:
Code | Result | Description |
---|---|---|
\n | New Line | Moves cursor to the next line |
\r | Carriage Return | Returns cursor to the beginning of the line |
\t | Tab | Inserts a tab space |
\b | Backspace | Moves cursor back one position |
\f | Form Feed | Advances to the next page |
Additional Example: Multiple Escape Characters
Let’s combine a few escape characters to create a complex string, In this example, \n
creates new lines, and \t
adds tab spaces to format the list properly.:
String report = "Vehicle List:\n\t1. \"Sedan\"\n\t2. \"Motorcycle\"\n\t3. \"Truck\"";