Java Escape Sequences


"Escape sequence is a character which escapes normal sequence of output (evaluation)". Escape sequences are very common in a language. Escape sequence precedes with a \ (backslash). For example, \n stands for new line; even though it looks two characters, Java treats them as one character with ASCII code of 10. Escape sequence, being a single character, should be put within single quotes.
Observe the following simple code on Escape Sequences

.

public class Demo
{
  public static void main(String args[])
  {              
    int x = '\t';                            // enclosed within single quotes
    System.out.println(x);                   // prints 9

    int y = '\n';
    System.out.println(y);                   // prints 10
  }
}

You can try for other escape characters also what their ASCII codes.

Java also comes Escape Sequences and the list if given here under.

Escape Sequence Meaning
\n Gives a new line
\t Gives one tab space (Java gives 6 spaces)
\" Prints just double quotes, "
\' Prints just single qutotes, '
\r Carriage return; The second line comes to the beginning of the line; that is, comes to extreme left where a new line begins.
\b Moves one space backwards. The character preceded to \b is deleted
\\ prints one slash (instead of two)
\f Form feed
Following code gives some Escape Sequences usage.
public class Demo
{
  public static void main(String args[])
  {              
    
    System.out.println("abc\ndef");    // abc and def are given in two lines

    System.out.println("ab\bcd");      // prints acd
    System.out.println("ab \bcd");     // prints abcd, the space before \b is gone
    System.out.println("abcdefghij");  // prints ab   cd, gives 3 spaces between ab and cd
    System.out.println("ab\tcd");      // prints ab   cd, gives 3 spaces between ab and cd

    System.out.println("a\"bc\"d");    // prints a"bc"d 

    System.out.println("a\'bc\'d");    // prints a'bc'd 
  }
}

1 thought on “Java Escape Sequences”

Leave a Comment

Your email address will not be published.