Java, prior to version 13, did not have native support for multiline strings in the form that many other programming languages (like Python or JavaScript) do. However, starting with Java 13, the language introduced text blocks to support multiline strings in a more readable and convenient way.
Multiline Strings in Java 13 and Later (Text Blocks)
Text blocks were introduced in Java 13 as a preview feature and became a permanent feature in Java 15. They allow for the creation of multiline strings in a more natural way without needing escape sequences for newlines.
Here’s how you can use text blocks:
public class Main {
public static void main(String[] args) {
// Multiline string using a text block (Java 13+)
String textBlock = """
This is a multiline string
that spans multiple lines.
It preserves line breaks
and makes the code easier to read.
""";
System.out.println(textBlock);
}
}
Key Features of Text Blocks:
- Multiline Strings: You can easily define strings that span multiple lines, preserving both line breaks and indentation.
- No Escape Sequences for Newlines: You don’t need to manually add
\n
for newlines, as the string format preserves them. - Triple Quotation Marks (
"""
): The string is enclosed within triple double-quotes ("""
). The string is automatically formatted across multiple lines as it appears in the code. - Whitespace Handling: Leading spaces or indentation can be trimmed using the
stripMargin()
method if needed. For example:String textBlock = """ |This is a multiline string |with margin that can be stripped. """.stripMargin();
Example without Text Blocks (Pre-Java 13)
Before Java 13, if you wanted to have a multiline string, you had to use concatenation or escape sequences. For example:
public class Main {
public static void main(String[] args) {
// Multiline string with escape sequences (pre-Java 13)
String multilineString = "This is a multiline string\n" +
"that spans multiple lines.\n" +
"It uses escape sequences for line breaks.";
System.out.println(multilineString);
}
}
Conclusion:
- Java 13+ introduced text blocks to provide a more convenient and readable way to handle multiline strings.
- For Java 8-12, multiline strings required using concatenation or escape characters, which were less convenient and harder to read.
So, if you’re using Java 13 or later, text blocks offer a much more intuitive way to work with multiline strings.