Java Special Characters in Strings: Handling Quotes and Backslashes

Learn how to handle special characters in Java strings, such as single quotes ('), double quotes ("), and backslashes (\). Discover the techniques for properly escaping these characters in your Java programs.



Java Special Characters in Strings

Because strings must be enclosed within quotes, special characters like single quotes ('), double quotes ("), and backslashes (\) need special handling in Java:

  • \': Inserts a single quote in a string.
  • \": Inserts a double quote in a string.
  • \\: Inserts a backslash in a string.

Examples:

Inserting double quotes:

String txt1 = "We are the so-called \"Vikings\" from the north.";

Inserting single quotes:

String txt2 = "It\'s alright.";

Inserting backslashes:

String txt3 = "The character \\ is called backslash.";

Other common escape sequences in Java strings:

  • \n: New Line
  • \r: Carriage Return
  • \t: Tab
  • \b: Backspace
  • \f: Form Feed