adsterra

How to print Escape Character "\n" in Java?


Most programming languages allow for “escape sequences”, where you signal with some sort of escape character that the next character you see shouldn’t be handled in the normal way.
A character with a backslash (\) just before it is an escape sequence or escape character. We use escape characters to perform some specific task. The total number of escape sequences or escape characters in Java is 8. Each escape character is a valid character literal.
For Example: if we try to print (“”) with this code...

public class Test {
    public static void main(String[] args)
    {
        System.out.println("Hi User, welcome to " Programming Soup ".");
    }
}

This code gives a compile time error as:

prog.java:3: error: ')' expected
    System.out.println("Hi User, welcome to " Programming Soup ".");
                                             ^
prog.java:3: error: not a statement
    System.out.println("Hi User, welcome to " Programming Soup ".");
                                                          ^
prog.java:3: error: ';' expected
    System.out.println("Hi User, welcome to " Programming Soup ".");
                                                             ^
3 errors

This happened because the compiler expects nothing but only strings inside the quotation mark but when the compiler found a quotation mark, it expects another quotation mark in the near future (the closing one) and between them, the string of text should be created.


Control Sequence:
A control sequence is nothing however the backslash(\) glued with a character (the character which has to be escaped) is called a control sequence.

Example to print “\n”:



public class Character
{
   public static void main(String[] args) {
System.out.println("Escape Sequence");
String text="";
text="\\n";
System.out.println(text);
   }
}

Output:


Post a Comment

0 Comments