Java Multi-line String Example


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:

This is a multi-line string line 1.
This is a multi-line string line 2.
This is a multi-line string line 3.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap