Topic Overview and Actualization

Welcome! Today's adventure involves Special Character Sequences in Java. We're going to demystify commonly used escape sequences — newline (\n), tab (\t), backslash (\\), and quotes (\" and \'). Ready? Let's go!

Introduction to Special Character Sequences

Escape sequences are characters prefixed with a backslash (\), which triggers unique behavior in subsequent characters. They're incredibly handy for commanding line breaks, adding tab spaces, or including a backslash or quotes in a string.

Here's an example of the newline character (\n) in action:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Programming is fun!\nLet's learn Java together.");
    }
    // Output:
    // Programming is fun!
    // Let's learn Java together.
}

The output appears on two separate lines!

Understanding Newline Character

Think of \n as your in-code line breaker. It efficiently splits the output, enhancing readability. Here's how it works:

class Main {
  public static void main(String[] args) {
    System.out.println("Java\nProgramming");
    // Output:
    // Java
    // Programming
  }
}

The output breaks "Java" and "Programming" into separate lines, all thanks to \n.

Exploring Tab and Backslash Characters

To insert a tab space, we use \t. It's useful for aligning the output or creating separations in your text.

Check out this example:

class Main {
  public static void main(String[] args) {
    System.out.println("Java\tProgramming");
    // Output: Java     Programming (with a tab space between)
  }
}

If you need to include a backslash in your string, you'll have to use \\.

class Main {
  public static void main(String[] args) {
    System.out.println("Java\\Programming");
  }
  // Output: Java\Programming
}

Note that there's a backslash in the output because we used \\. Also, note that just using a single backslash inside the string will not work and will cause a compilation error - because the backslash is a special character.

Working with Quotes in Strings
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal