Explain Codes LogoExplain Codes Logo

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

java
text-blocks
string-handling
java-15
Alex KataevbyAlex Kataev·Jan 27, 2025
TLDR

Java's text blocks, introduced in Java 15, allow unescaped quote marks in strings:

String json = """ {"key": "value with "embedded" quotes"} """;

Employ three quotes at the start and end to include the inner quotes, no backslashes required. This significantly simplifies handling JSON or multi-line content.

Deeper Dive - Text Blocks and More

Java's text blocks provide an elegant solution to incorporate quotes without the need of escape characters. But there's more to understand for efficient string handling.

Text Blocks: A Leap for Better Readability

Text blocks became an official feature in Java 15 after previews in earlier versions. They not only eliminate the pain of quote escaping, but also bring massive readability improvements with multi-line strings.

Groovy: Syntactic Sugar in Java Projects

For those who are yet not on Java 15 or those looking for extra syntactic sweetness, Groovy integration offers GString literals allowing unescaped quotes, potentially elevating readability a step higher.

def canWeSpeak = "We certainly can! No \"escape-the-room\" shenanigans here!"

Friendly Reminder: Static Fields and Performance

Frequently used string literals? Consider constant static fields. These little beauties can speed up your execution by not making JVM process the same string again and again.

The Future is Raw (Strings, That is...)

Keep an eye out for the introduction of raw string literals as per JEP 8196004 in future Java versions. Wouldn't multi-line strings without any escaping sequence be even more joyful?

In-Depth Considerations and Scenarios

Special Pathogens: Characters

Java string literals aren't only about escaping quotes! What about those pesky line breaks or tabs? Text blocks shoos them away elegantly.

String javaPoem = """ Roses are red, Tabs are escaped too; With text blocks, my friend, The joke's not on you! """

Concatenation and Text Blocks: A Budding Romance?

When combining text blocks and traditional strings, be careful, lest you provoke unexpected syntax monsters.

Beware the Edge Cases

Though text blocks simplify strings, their philosophy is different. A text block begins with its content following the first line unlike traditional strings. No extra spinal stretches for trailing spaces anymore!

Hey, Traditional Strings are Still Cool!

With short and sweet strings, the traditional ones with escape sequences can still be a good choice. No need to toss them in the recycle bin yet!