Why does this string print only ""\\""? Does the backslash do something to the string? Please explain the function of the backslash. All I know is that it is the escape character, but I don't understand why it does this to strings.
Asked
Active
Viewed 196 times
-2
-
FYI the fact that you are using BlueJ is not actually relevant. – Manos Nikolaidis Sep 20 '15 at 13:31
-
@ManosNikolaidis Sorry. I thought it'd be useful info. I will edit it out. – TheUnicornMaster Sep 20 '15 at 13:31
2 Answers
3
The backslash '\' can be used in a String to add characters that would otherwise be illegal (e.g. " and ') or have another meaning (e.g. t, b, n, r, f and \). for your particular example :
- The first 2 backslashes are escaping the double quotes. So
\"\"
is printed as""
- The next backslashes are escaping the backslashes that immediately follow so
\\\\
is printed as\\
- The last 2 backslashes behave as the first 2 escaping the quotes so
\"\"
is printed as""

Manos Nikolaidis
- 21,608
- 12
- 74
- 82
-
I would add for beginners: You have to use a backlash \ if you wan't to treat an special character as a String and it is the reason why it happens. – Francisco Romero Sep 20 '15 at 13:32
-
-
-
@ManosNikolaidis Thanks for the link. I actually read it before I posted this question. But it does not tell what a backslash does to a string. Maybe I missed something though – TheUnicornMaster Sep 20 '15 at 13:42
-
@ManosNikolaidis Sorry. I meant the top part of the question where it said it was a duplicate. Marcus's answer is fine. – TheUnicornMaster Sep 20 '15 at 13:50
2
The Backslash is the escape character, used to encode special things like "
in your string (which you normally couldn't use, because they'd mark the end of a string). You should read up on "String literals" in the official Java documentation or the book you read to learn Java.

Marcus Müller
- 34,677
- 4
- 53
- 94