Does Java have support for multiline strings?
In Java, there is no native support for multiline strings. However, there are a few ways you can achieve a similar effect:
- Use the
+
operator to concatenate multiple strings:
String multilineString = "Line 1\n" +
"Line 2\n" +
"Line 3";
- Use string concatenation with the
\
character at the end of each line to break the string into multiple lines:
String multilineString = "Line 1\n" +
"Line 2\n" +
"Line 3";
- Use string concatenation with the
\
character at the end of each line and enclose the string in parentheses:
String multilineString = ("Line 1\n" +
"Line 2\n" +
"Line 3");
- Use a string literal with the
\
character at the end of each line:
String multilineString = "Line 1\n" +
"Line 2\n" +
"Line 3";
- Use a string literal with the
\
character at the end of each line and enclose the string in triple quotes:
String multilineString = """
Line 1
Line 2
Line 3
""";
Note that the triple-quote syntax for defining a string literal is not part of the Java language specification and may not be supported by all Java compilers.
I hope these examples help! Let me know if you have any other questions.