-2

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.

TheUnicornMaster
  • 159
  • 2
  • 13

2 Answers2

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 :

  1. The first 2 backslashes are escaping the double quotes. So \"\" is printed as ""
  2. The next backslashes are escaping the backslashes that immediately follow so \\\\ is printed as \\
  3. The last 2 backslashes behave as the first 2 escaping the quotes so \"\" is printed as ""
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
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