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, 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 Anthony. \nI'm an Artist.");
System.out.println();
System.out.println("Age:\t18");
System.out.println("Addresss\b: Washington DC");
}
}
Output:
My name is Anthony.
I'm an Artist.
Age: 18
Address: Washington DC