At times you may have a String in Java that has to be initialized as a multi-line string to make it clear to read, in such case you can declare a String object in multiple lines as below.
Example 1:
package org.code2care.java.examples;
public class JavaMultiLineString {
public static void main(String[] args) {
String multiLineStringExample = "This is a multi-line string line 1.\n" +
"This is a multi-line string line 2.\n" +
"This is a multi-line string line 3.";
System.out.println(multiLineStringExample);
}
}
As you can see we have split the lines as sub-strings and made use of the string concatenation operator + as well as the new line character (\n) to display the output in new lines as well.
Example 2: Using Java 15 triple double quotes
package org.code2care.java.examples;
public class JavaMultiLineString {
public static void main(String[] args) {
String multiLineStringExample = """
This is a multi-line string line 1.
This is a multi-line string line 2.
This is a multi-line string line 3.
""";
System.out.println(multiLineStringExample);
}
}
Output:
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!