Escape Characters

 

Escape Characters

Try running the code given below in your java compiler.

public class string {
    public static void main(String[] args) {
        System.out.println("He said, "I believe that the Earth is Flat".");
    }
}


As we can see that the code gives an error. This is because the compiler assumes that the string ends after the 2nd quotation mark.


This can be solved by using ‘\’ (backslash). Backslash acts as an escape character allowing us to use quotation marks in strings.


Example:


public class string {
    public static void main(String[] args) {
        System.out.println("He said, \"I believe that the Earth is Flat\".");
        System.out.println("she said, \'But the Earth is spherical\'.");
    }
}


Output:

He said, "I believe that the Earth is Flat".
she said, 'But the Earth is spherical'.

 

Similarly to use a backslash in the string we must escape it with another backslash.

Example:


public class string {
    public static void main(String[] args) {
        System.out.println("The path is D:\\Docs\\Java\\Strings");
    }
}


Output:

The path is D:\Docs\Java\Strings

 

We also have an escape character for printing on a new line(\n), inserting a tab(\t), backspacing(\b), etc.


Example: 


public class string {
    public static void main(String[] args) {
        System.out.println("My name is Maxon. \nI'm a Coder.");
        System.out.println();
        System.out.println("Age:\t26");
        System.out.println("Addresss\b: Kasganj UP");
    }
}


Output:

My name is Maxon. 
I'm a Coder.

Age:    26
Address: Kasganj UP