What is the string literal \\
backslash? What does it do? I have thought about it but I do not understand it. I also read it on wikipedia. When I try to print the following:
System.out.println("Mango \\ Nightangle");
the output is: Mango \ Nightangle
What is the significance of this string literal?
This question is related to
java
string
string-literals
If double backslash looks weird to you, C# also allows verbatim string literals where the escaping is not required.
Console.WriteLine(@"Mango \ Nightangle");
Don't you just wish Java had something like this ;-)
The \
on it's own is used to escape special characters, such as \n
(new line), \t
(tabulation), \"
(quotes) when typing these specific values in a System.out.println()
statement.
Thus, if you want to print a backslash, \
, you can't have it on it's own since the compiler will be expecting a special character (such as the ones above). Thus, to print a backslash you need to escape it, since itself is also one of these special characters, thus, \\
yields \
.
Imagine you are designing a programming language. You decide that Strings are enclosed in quotes ("Apple"). Then you hit your first snag: how to represent quotation marks since you've already used them ? Just out of convention you decide to use \"
to represent quotation marks. Then you have a second problem: how to represent \
? Again, out of convention you decide to use \\
instead. Thankfully, the process ends there and this is sufficient. You can also use what is called an escape sequence to represent other characters such as the carriage return (\n
).
\
is used for escape sequences in programming languages.
\n
prints a newline
\\
prints a backslash
\"
prints "
\t
prints a tabulator
\b
moves the cursor one back
It is used to escape special characters and print them as is. E.g. to print a double quote which is used to enclose strings, you need to escape it using the backslash character.
e.g.
System.out.println("printing \"this\" in quotes");
outputs
printing "this" in quotes
Source: Stackoverflow.com