Cg2916
Cg2916

Reputation: 1117

Invalid Escape Sequence in Java

When I create this String:

private String chars = " `~1!2@3#4$5%6^7&8*9(0)-_=+qQwWeErRtTyYuUiIoOpP[{]}\|aAsSdDfFgGhHjJkKlL;:'"zZxXcCvVbBnNmM,<.>/?";

Eclipse tells me:

Invalid escape sequence (valid ones are  \b  \t  \n  \f  \r  \"  \'  \\ )

How do I fix this?

Upvotes: 0

Views: 12893

Answers (1)

BalusC
BalusC

Reputation: 1108712

The \ is an escape character. You're basically escaping | which doesn't need to be escaped at all. If you want to represent an \ in String, then you need to let it escape itself.

private String chars = " `~1!2@3#4$5%6^7&8*9(0)-_=+qQwWeErRtTyYuUiIoOpP[{]}\\|aAsSdDfFgGhHjJkKlL;:'\"zZxXcCvVbBnNmM,<.>/?";

Please note that the " does need to be escaped, otherwise the string value ends too early and the code still won't compile due to all the odd characters thereafter.

Upvotes: 5

Related Questions