Does Java have support for multiline strings?
Text blocks were introduced in Java 15+ for supporting multiline strings. Here's how to use them:
Earlier versions have to resort to concatenation or using \n
for newlines.
Options for multiline strings before JDK 15
In this section, we'll explore how to handle multiline strings before JDK 15 introduced text blocks.
The classic: string concatenation
Since time immemorial (okay, since JDK 1.0), devs used string concatenation with \n
for newlines:
The builder: StringBuilder
For performance-oriented coders, StringBuilder.append() has been the trusted ally:
The formatter: String.format()
Having troubles with readability? String.format() is here for the rescue:
The joiner: String.join()
String.join() allows joining strings with a delimiter of your choice:
The reader: Externally stored strings
For multiline string content that is too large, consider reading it from a text file:
Remember, dealing with IO operations come with their own set of issues.
The helper: IDE features
Don't forget to use the cool features of your IDE. In Eclipse, "Escape text when pasting into a string literal” saves lot of time.
The previewer: Text blocks in JDK 13/14
You could get a flavor of the future in the past! Good old JDK 13 and 14 let you preview text blocks with a --enable-preview
flag. Thank you JEP 378!
Beyond the basic: Advanced techniques
Properties file
Consider using .properties files for storing strings for different locales.
Custom annotations
Thinking of creating custom annotations and an annotation processor for multiline strings? Well, you can. But tread cautiously as it could affect your code maintainability.
Javadoc and the clever hack
Don't reformulate Javadoc comments in your IDE settings. You can store your multiline strings there. Clever, isn't it?
Learning from others
It's great to learn lessons from other languages. Take a peek at how Visual Basic .NET manages multiline strings with XML literals.
Was this article helpful?