Does Java have support for multiline strings?
In Java, there is no native support for multiline strings.
In Java, multiline strings are natively supported starting from Java 15 (previewed in Java 13) via Text Blocks. For earlier versions or dynamic content, you can use the following approaches:
- Use the
+operator to concatenate multiple strings:
String multilineString = "Line 1\n" +
"Line 2\n" +
"Line 3";- Use
String.joinfor dynamic content:
String[] lines = {"Line 1", "Line 2", "Line 3"};
String multilineString = String.join("\n", lines);Note that String.join returns an empty string for an empty array and throws a NullPointerException if any element is null.
- Use
StringBuilderfor building strings in loops or conditionals:
StringBuilder sb = new StringBuilder();
sb.append("Line 1\n");
sb.append("Line 2\n");
sb.append("Line 3");
String multilineString = sb.toString();- Use Text Blocks (Java 15+) for static multiline strings:
String multilineString = """\
Line 1
Line 2
Line 3
""";Note that Text Blocks are part of the official Java language specification and are supported in all modern Java versions.