In Java, is there a way to write a string literal without having to escape quotes?

No, and I’ve always been annoyed by the lack of different string-literal syntaxes in Java.

Here’s a trick I’ve used from time to time:

String myString = "using `backticks` instead of quotes".replace('`', '"');

I mainly only do something like that for a static field. Since it’s static the string-replace code gets called once, upon initialization of the class. So the runtime performance penalty is practically nonexistent, and it makes the code considerably more legible.

Leave a Comment