Common Escape Sequences
Inside of a string literal, there are some characters that cannot be written normally.
An easy example is double quotes. You can't write double quotes in the middle of
a string literal because Java will think the extra quote is the end of the String
.
void main() {
String title = "The "Honorable" Judge Judy";
}
In order to make it work, the "
s need to be "escaped" with a backslash.
void main() {
String title = "The \"Honorable\" Judge Judy";
}
Since the backslash is used to escape characters, it too needs to escaped
in order to have it be in a String
. So to encode ¯\_(ツ)_/¯
into a String
you need to escape the first backslash.
void main() {
// The first backslash needs to be escaped. ¯\_(ツ)_/¯
String shruggie = "¯\\_(ツ)_/¯";
}
And much the same as with char
, you need to use \n
to write in a newline.
void main() {
String letter = "To Whom It May Concern,\n\nI am writing this letter to complain.";
}