Start learning free

LESSON 54 OF 410 · STRINGS I

Escaping characters in Java

Lesson Read the full explanation

There are times when we want to use quotes inside a string. For example, suppose we want to print the message I am John "the coder" Doe:

System.out.println("I am John "the coder" Doe");

You can already see by the text color that we have a problem. Java recognizes the string to be only I am John .

Java finds the first quotation mark and interprets that the string starts there. But then, it finds the second quotation mark (after John ) and interprets the string ends there.

Character escaping comes to our rescue!


Escaping characters:

In Java, some characters serve different functions and so cannot be displayed or printed like other characters. These characters are referred to as special characters.

For example, double quotes (") is considered a special character by Java. Its job is to let Java know when a string declaration starts / ends.

There is a way to print special characters like these in Java, and that is by using the backslash character (\).

When we put \ before a special character, we tell Java:

"Hey, I know this is a special character, but I don't want to use it like that here. I just want to print it like I print any other character."

For example, when putting a \ before a double quote, Java no longer interprets that as being the end of the string:

System.out.println("I am John \"the coder\" Doe");

System.out.println("After \"Coding 101\" we'll solve some problems");

The output of this code is:

I am John "the coder" Doe
After "Coding 101" we'll solve some problems

Escaping backslash:

Sometimes we might want to print strings that contain character \, such as a file path in your PC:

System.out.println("C:\Users\Andy\Games");

This code looks perfectly fine at first sight, but if you run it, it would produce an error: illegal escape character.

When Java sees \U, it supposes that you are trying to escape character U, which is not a special character thus cannot be escaped.

Now that you've learned about its function, what type of character do you think \ is in Java? It's a special character!

And like any special character, it can also be escaped by putting another \ in front of it (\\):

System.out.println("C:\\Users\\Andy\\Games");

The output of this code is:

C:\Users\Andy\Games

New line character:

Similarly, the escape sequence can be used to make an otherwise printable character serve a special function.

For example, the letter n can be printed normally, but adding a backslash before it (\n) will indicate the start of a new line:

System.out.println("Hello world!\nWhat a good day for coding!\n");
System.out.println("Let's have a blast!");

The output of this code is:

Hello world!
What a good day for coding!

Let's have a blast!

Notice the empty line after What a good day for coding! ?

That's one new line from the \n plus the new line that System.out.println() prints no matter what the message is.


Assignment
Follow the Coding Tutorial and let's escape some characters!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    JAVA · STRINGS I

    Escaping Characters in Java, explained

    Introduction

    In this lesson, we will explore the concept of escaping characters in Java. This is a fundamental topic in programming that allows us to include special characters in strings without causing errors. Understanding how to escape characters is crucial for writing robust and error-free code, especially when dealing with strings that contain quotes, backslashes, or other special characters.

    Understanding the Basics

    Before diving into the details, let's understand what escaping characters means. In Java, certain characters have special meanings and cannot be used directly within strings. These characters include double quotes, backslashes, and newline characters. To include these characters in a string, we use the backslash (\) as an escape character.

    For example, to include a double quote inside a string, we use \" instead of just ". Similarly, to include a backslash, we use \\. This tells Java to treat the following character as a literal character rather than a special one.

    Main Concepts

    Let's break down the key concepts and techniques involved in escaping characters in Java:

    • Double Quotes: To include double quotes inside a string, use \". For example:
    • System.out.println("I am John \"the coder\" Doe");
    • Backslashes: To include a backslash, use \\. For example:
    • System.out.println("C:\\Users\\Andy\\Games");
    • Newline Character: To include a newline character, use \n. For example:
    • System.out.println("Hello world!\nWhat a good day for coding!\n");

    Examples and Use Cases

    Let's look at some examples to see how escaping characters can be used in various contexts:

    // Example 1: Including double quotes in a string
    System.out.println("She said, \"Hello, World!\"");
    
    // Example 2: Including a file path with backslashes
    System.out.println("File path: C:\\Program Files\\Java");
    
    // Example 3: Using newline characters
    System.out.println("First line\nSecond line\nThird line");

    These examples demonstrate how escaping characters allows us to include special characters in strings without causing syntax errors.

    Common Pitfalls and Best Practices

    When working with escaping characters, it's important to avoid common mistakes and follow best practices:

    • Avoid forgetting the backslash: Always remember to use the backslash before special characters.
    • Use raw strings for complex paths: For complex file paths, consider using raw strings to avoid excessive escaping.
    • Keep code readable: Use escaping characters judiciously to maintain code readability.

    Advanced Techniques

    In addition to basic escaping, there are advanced techniques that can be useful in certain scenarios:

    • Unicode Escapes: Use Unicode escapes to include characters that are not easily typable. For example, \u00A9 represents the copyright symbol (©).
    • Combining Escapes: Combine multiple escape sequences to achieve complex formatting. For example, \\n can be used to include a backslash followed by a newline.

    Code Implementation

    Here are some well-commented code snippets demonstrating the correct use of escaping characters:

    // Including double quotes in a string
    System.out.println("I am John \"the coder\" Doe");
    
    // Including a file path with backslashes
    System.out.println("C:\\Users\\Andy\\Games");
    
    // Using newline characters
    System.out.println("Hello world!\nWhat a good day for coding!\nLet's have a blast!");

    Debugging and Testing

    When debugging code that involves escaping characters, consider the following tips:

    • Check for missing backslashes: Ensure that all special characters are properly escaped.
    • Use print statements: Print intermediate results to verify that strings are formatted correctly.
    • Write test cases: Create test cases to validate that strings with special characters are handled correctly.

    Example test case:

    public class EscapeCharacterTest {
        public static void main(String[] args) {
            // Test double quotes
            String expected = "I am John \"the coder\" Doe";
            String actual = "I am John \"the coder\" Doe";
            assert expected.equals(actual) : "Test failed for double quotes";
    
            // Test backslashes
            expected = "C:\\Users\\Andy\\Games";
            actual = "C:\\Users\\Andy\\Games";
            assert expected.equals(actual) : "Test failed for backslashes";
    
            // Test newline characters
            expected = "Hello world!\nWhat a good day for coding!\nLet's have a blast!";
            actual = "Hello world!\nWhat a good day for coding!\nLet's have a blast!";
            assert expected.equals(actual) : "Test failed for newline characters";
    
            System.out.println("All tests passed!");
        }
    }

    Thinking and Problem-Solving Tips

    When approaching problems related to escaping characters, consider the following strategies:

    • Break down the problem: Identify the special characters that need to be escaped and handle them one by one.
    • Practice with examples: Work on coding exercises that involve escaping characters to build familiarity.
    • Use online resources: Refer to documentation and tutorials for additional guidance and examples.

    Conclusion

    In this lesson, we covered the importance of escaping characters in Java and how to use escape sequences to include special characters in strings. Mastering this concept is essential for writing robust and error-free code. Practice regularly and explore further applications to deepen your understanding.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free