CORE JAVA

ProwessApps Learning Portal

Escape Sequences in Java


  • The Java programming language also supports a few special escape sequences for char and String literals:

  • These can be represented by using escape sequences represented by a backslash(\) followed by one or more characters.

ESC. SEQUNICODEDESCRIPTION
\b\u0008Backspace
\t\u0009Horizontal Tab
\n\u000aNewline
\f\u000cFormfeed
\r\u000dCarriage return
\'\u0027Apostrophe-quote
\"\u0022Double Quotation
\\\u005cBackslash

Example :

Test.java Copy Code
class Test
{
 public static void main(String []arg)
  {
   System.out.print("C Prowess");
   System.out.print("\tC++ Prowess");
   System.out.print("\nJava Prowess");
  }
}          
OUTPUT:
C Prowess        C++ Prowess
Java Prowess

More Examples :

1. Newline (\n): Inserts a newline character.

Java Copy Code
String newLine = "Hello\nWorld";
System.out.println(newLine);
// Output:
// Hello
// World

2. Tab (\t): Inserts a tab character.

Java Copy Code
String tab = "Java\tProgramming";
System.out.println(tab);
// Output: Java    Programming

3. Backslash (\): Inserts a backslash character.

Java Copy Code
String backslash = "C:\\Program Files\\Java";
System.out.println(backslash);
// Output: C:\Program Files\Java

4. Single quote ('): Inserts a single quote character.

Java Copy Code
String singleQuote = "It\'s raining";
System.out.println(singleQuote);
// Output: It's raining

5. Double quote ("): Inserts a double quote character.

Java Copy Code
String doubleQuote = "He said, \"Hello\"";
System.out.println(doubleQuote);
// Output: He said, "Hello"

6. Carriage return (\r): Inserts a carriage return character.

Java Copy Code
String carriageReturn = "Hello\rWorld";
System.out.println(carriageReturn);
// Output: World

7. Unicode character (\uXXXX): Inserts the Unicode character represented by the hexadecimal number XXXX.

Java Copy Code
String unicode = "\u00A9 2023";
System.out.println(unicode);
// Output: © 2023




advertisement