Java multiline string

skiphoppy Source

Coming from Perl, I sure am missing the "here-document" means of creating a multi-line string in source code:

$string = <<"EOF"  # create a three-line string

In Java, I have to have cumbersome quotes and plus signs on every line as I concatenate my multiline string from scratch.

What are some better alternatives? Define my string in a properties file?

Edit: Two answers say StringBuilder.append() is preferable to the plus notation. Could anyone elaborate as to why they think so? It doesn't look more preferable to me at all. I'm looking for a way around the fact that multiline strings are not a first-class language construct, which means I definitely don't want to replace a first-class language construct (string concatenation with plus) with method calls.

Edit: To clarify my question further, I'm not concerned about performance at all. I'm concerned about maintainability and design issues.



answered 9 years ago Josh Curren #1

The only way I know of is to concatenate multiple lines with plus signs

answered 9 years ago Tom #2

String newline = System.getProperty ("line.separator");
string1 + newline + string2 + newline + string3

But, the best alternative is to use String.format

String multilineString = String.format("%s\n%s\n%s\n",line1,line2,line3);

answered 9 years ago Josh Curren #3

Another option may be to store long strings in an external file and read the file into a string.

answered 9 years ago user54579 #4

You can concatenate your appends in a separate method like:

public static String multilineString(String... lines){
   StringBuilder sb = new StringBuilder();
   for(String s : lines){
     sb.append ('\n');
   return sb.toStirng();

Either way, prefer StringBuilder to the plus notation.

answered 9 years ago Kip #5

Define my string in a properties file?

Multiline strings aren't allowed in properties files. You can use \n in properties files, but I don't think that is much of a solution in your case.

answered 9 years ago Tom Hawtin - tackline #6

If you define your strings in a properties file it'll look much worse. IIRC, it'll look like:


Generally it's a reasonable idea to not embed large strings in to source. You might want to load them as resources, perhaps in XML or a readable text format. The text files can be either read at runtime or compiled into Java source. If you end up placing them in the source, I suggest putting the + at the front and omitting unnecessary new lines:

final String text = ""
    +"text "
    +"text "

If you do have new lines, you might want some of join or formatting method:

final String text = join("\r\n"

answered 9 years ago Andreas_D #7

A quite efficient and platform independent solution would be using the system property for line separators and the StringBuilder class to build strings:

String separator = System.getProperty("line.separator");
String[] lines = {"Line 1", "Line 2" /*, ... */};

StringBuilder builder = new StringBuilder(lines[0]);
for (int i = 1; i < lines.length(); i++) {
String multiLine = builder.toString();

answered 9 years ago Kip #8

It sounds like you want to do a multiline literal, which does not exist in Java.

Your best alternative is going to be strings that are just +'d together. Some other options people have mentioned (StringBuilder, String.format, String.join) would only be preferable if you started with an array of strings.

Consider this:

String s = "It was the best of times, it was the worst of times,\n"
         + "it was the age of wisdom, it was the age of foolishness,\n"
         + "it was the epoch of belief, it was the epoch of incredulity,\n"
         + "it was the season of Light, it was the season of Darkness,\n"
         + "it was the spring of hope, it was the winter of despair,\n"
         + "we had everything before us, we had nothing before us";

Versus StringBuilder:

String s = new StringBuilder()
           .append("It was the best of times, it was the worst of times,\n")
           .append("it was the age of wisdom, it was the age of foolishness,\n")
           .append("it was the epoch of belief, it was the epoch of incredulity,\n")
           .append("it was the season of Light, it was the season of Darkness,\n")
           .append("it was the spring of hope, it was the winter of despair,\n")
           .append("we had everything before us, we had nothing before us")

Versus String.format():

String s = String.format("%s\n%s\n%s\n%s\n%s\n%s"
         , "It was the best of times, it was the worst of times,"
         , "it was the age of wisdom, it was the age of foolishness,"
         , "it was the epoch of belief, it was the epoch of incredulity,"
         , "it was the season of Light, it was the season of Darkness,"
         , "it was the spring of hope, it was the winter of despair,"
         , "we had everything before us, we had nothing before us"

Versus Java8 String.join():

String s = String.join("\n"
         , "It was the best of times, it was the worst of times,"
         , "it was the age of wisdom, it was the age of foolishness,"
         , "it was the epoch of belief, it was the epoch of incredulity,"
         , "it was the season of Light, it was the season of Darkness,"
         , "it was the spring of hope, it was the winter of despair,"
         , "we had everything before us, we had nothing before us"

If you want the newline for your particular system, you either need to use System.getProperty("line.separator"), or you can use %n in String.format.

Another option is to put the resource in a text file, and just read the contents of that file. This would be preferable for very large strings to avoid unnecessarily bloating your class files.

answered 9 years ago Laurence Gonsalves #9

Sadly, Java does not have multi-line string literals. You either have to concatenate string literals (using + or StringBuilder being the two most common approaches to this) or read the string in from a separate file.

For large multi-line string literals I'd be inclined to use a separate file and read it in using getResourceAsStream() (a method of the Class class). This makes it easy to find the file as you don't have to worry about the current directory versus where your code was installed. It also makes packaging easier, because you can actually store the file in your jar file.

Suppose you're in a class called Foo. Just do something like this:

Reader r = new InputStreamReader(Foo.class.getResourceAsStream("filename"), "UTF-8");
String s = Utils.readAll(r);

The one other annoyance is that Java doesn't have a standard "read all of the text from this Reader into a String" method. It's pretty easy to write though:

public static String readAll(Reader input) {
    StringBuilder sb = new StringBuilder();
    char[] buffer = new char[4096];
    int charsRead;
    while ((charsRead = >= 0) {
        sb.append(buffer, 0, charsRead);
    return sb.toString();

answered 9 years ago Paul Morie #10

Stephen Colebourne has created a proposal for adding multi-line strings in Java 7.

Also, Groovy already has support for multi-line strings.

answered 9 years ago Jay #11

Pluses are converted to StringBuilder.append, except when both strings are constants so the compiler can combine them at compile time. At least, that's how it is in Sun's compiler, and I would suspect most if not all other compilers would do the same.


String a="Hello";
String b="Goodbye";
String c=a+b;

normally generates exactly the same code as:

String a="Hello";
String b="Goodbye":
StringBuilder temp=new StringBuilder();
String c=temp.toString();

On the other hand:

String c="Hello"+"Goodbye";

is the same as:

String c="HelloGoodbye";

That is, there's no penalty in breaking your string literals across multiple lines with plus signs for readability.

answered 9 years ago Peter Lawrey #12

When a long series of + are used, only one StringBuilder is created, unless the String is determined at compile time in which case no StringBuilder is used!

The only time StringBuilder is more efficient is when multiple statements are used to construct the String.

String a = "a\n";
String b = "b\n";
String c = "c\n";
String d = "d\n";

String abcd = a + b + c + d;

String abcd2 = "a\n" +
        "b\n" +
        "c\n" +

Note: Only one StringBuilder is created.

   0:   ldc     #2; //String a\n
   2:   astore_1
   3:   ldc     #3; //String b\n
   5:   astore_2
   6:   ldc     #4; //String c\n
   8:   astore_3
   9:   ldc     #5; //String d\n
   11:  astore  4
   13:  new     #6; //class java/lang/StringBuilder
   16:  dup
   17:  invokespecial   #7; //Method java/lang/StringBuilder."<init>":()V
   20:  aload_1
   21:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   24:  aload_2
   25:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   28:  aload_3
   29:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   32:  aload   4
   34:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   37:  invokevirtual   #9; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   40:  astore  5
   42:  getstatic       #10; //Field java/lang/System.out:Ljava/io/PrintStream;
   45:  aload   5
   47:  invokevirtual   #11; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   50:  ldc     #12; //String a\nb\nc\nd\n
   52:  astore  6
   54:  getstatic       #10; //Field java/lang/System.out:Ljava/io/PrintStream;
   57:  aload   6
   59:  invokevirtual   #11; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   62:  return

To clarify my question further, I'm not concerned about performance at all. I'm concerned about maintainability and design issues.

Make it as clear and simple as you can.

answered 9 years ago Panu Viljamaa #13

A simple option is to edit your java-code with an editor like SciTE (, which allows you to WRAP the text so that long strings are easily viewed and edited. If you need escape characters you just put them in. By flipping the wrap-option off you can check that your string indeed is still just a long single-line string. But of course, the compiler will tell you too if it isn't.

Whether Eclipse or NetBeans support text-wrapping in an editor I don't know, because they have so many options. But if not, that would be a good thing to add.

answered 9 years ago Bob Albright #14

This is something that you should never use without thinking about what it's doing. But for one-off scripts I've used this with great success:


This is a CRAZY " ' ' " multiline string with all sorts of strange 


// From:
// Takes a comment (/**/) and turns everything inside the comment to a string that is returned from S()
public static String S() {
    StackTraceElement element = new RuntimeException().getStackTrace()[1];
    String name = element.getClassName().replace('.', '/') + ".java";
    StringBuilder sb = new StringBuilder();
    String line = null;
    InputStream in = classLoader.getResourceAsStream(name);
    String s = convertStreamToString(in, element.getLineNumber());
    return s.substring(s.indexOf("/*")+2, s.indexOf("*/"));

// From
private static String convertStreamToString(InputStream is, int lineNum) {
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null; int i = 1;
    try {
        while ((line = reader.readLine()) != null) {
            if (i++ >= lineNum) {
                sb.append(line + "\n");
    } catch (IOException e) {
    } finally {
        try {
        } catch (IOException e) {

    return sb.toString();

answered 9 years ago BalusC #15

An alternative I haven't seen as answer yet is the

StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
writer.println("It was the best of times, it was the worst of times");
writer.println("it was the age of wisdom, it was the age of foolishness,");
writer.println("it was the epoch of belief, it was the epoch of incredulity,");
writer.println("it was the season of Light, it was the season of Darkness,");
writer.println("it was the spring of hope, it was the winter of despair,");
writer.println("we had everything before us, we had nothing before us");
String string = stringWriter.toString();

Also the fact that has a newLine() method is unmentioned.

answered 9 years ago ThomasP #16

I got a bit annoyed with reading that multiline syntax is indeed been planned for jdk7 (after about how many decades of java existence?). Funnily, there is not even yet a readAll() function for reading the complete contents of a file (from jdk7 only, huhh), so the code below reads single lines.

  MakeMultiline v1.0 (2010) - Free to use and copy.

  Small gadget to turn text blobs into one java string literal
  (doing the split in lines, adding \n at each end and enclosing
  in double quotes). Does escape quotes encountered in the text blob.

  Useful for working around missing multiline string syntax in java
  prior jdk7. Use with:

     java MakeMultiline "    "
     java MakeMultiline "    " mytextfile.txt


class MakeMultiline {
  public static void main(String[] args) {
    try {
      // args[0]: indent
      // args[1]: filename to read (optional; stdin if not given)
      // Beware the nmb of newlines at the end when using stdin!

      String indent = (args.length > 0 ? args[0] : "");
      FileReader fr = null; BufferedReader br;
      if (args.length > 1)
        { fr =  new FileReader(args[1]); br = new BufferedReader(fr); }
        { br = new BufferedReader(new InputStreamReader(; }
      String s; String res = "";
      while((s = br.readLine()) != null) {
        if (res.length() > 0) res += " +\n";
        res += indent + "\"" + s.replace("\"", "\\\"") + "\\n\"";
      br.close(); if (fr != null) fr.close();
      System.out.println(res + ";");
    catch(Exception e) {
      System.out.println("Exception: " + e);

This was the quickest solution for me. (2010-01-27)

answered 8 years ago horace #17

I suggest using a utility as suggested by ThomasP, and then link that into your build process. An external file is still present to contain the text, but the file is not read at runtime. The workflow is then:

  1. Build a 'textfile to java code' utility & check into version control
  2. On each build, run the utility against the resource file to create a revised java source
  3. The Java source contains a header like class TextBlock {... followed by a static string which is auto-generated from the resource file
  4. Build the generated java file with the rest of your code

answered 8 years ago user unknown #18

You may use scala-code, which is compatible to java, and allows multiline-Strings enclosed with """:

package foobar
object SWrap {
  def bar = """John said: "This is
  a test
  a bloody test,
  my dear." and closed the door.""" 

(note the quotes inside the string) and from java:

String s2 = ();

Whether this is more comfortable ...?

Another approach, if you often handle long text, which should be placed in your sourcecode, might be a script, which takes the text from an external file, and wrappes it as a multiline-java-String like this:

sed '1s/^/String s = \"/;2,$s/^/\t+ "/;2,$s/$/"/' file >

so that you may cut-and-paste it easily into your source.

answered 8 years ago Deltaplan #19

I see at least one case where it should be avoided to use external files for long strings : if these long string are expected values in an unit-test file, because I think the tests should always be written in a way that they don't rely on any external resource.

answered 8 years ago Hector Caicedo #20

One small trick. Using this I inject javascritp in a dynamically created HTML page

StringBuilder builder = new StringBuilder();

public String getString()
    return builder.toString();
private DropdownContent _(String a)
    return this;

public String funct_showhide()
    _("function slidedown_showHide(boxId)").
    _("if(!slidedown_direction[boxId])slidedown_direction[boxId] = 1;").
    _("if(!slideDownInitHeight[boxId])slideDownInitHeight[boxId] = 0;").
    _("if(slideDownInitHeight[boxId]==0)slidedown_direction[boxId]=slidedownSpeed; ").
    _("else slidedown_direction[boxId] = slidedownSpeed*-1;").
    _("slidedownContentBox = document.getElementById(boxId);").
    _("var subDivs = slidedownContentBox.getElementsByTagName('DIV');").
    _("for(var no=0;no<subDivs.length;no++){").
    _(" if(subDivs[no].className=='dhtmlgoodies_content')slidedownContent = subDivs[no];").
    _("contentHeight = slidedownContent.offsetHeight;").
    _("slidedownActive = true;").


answered 8 years ago scorpiodawg #21

Since Java does not (yet) native support multi-line strings, the only way for now is to hack around it using one of the aforementioned techniques. I built the following Python script using some of the tricks mentioned above:

import sys
import string
import os

print 'new String('
for line in sys.stdin:
    one = string.replace(line, '"', '\\"').rstrip(os.linesep)
    print '  + "' + one + ' "'
print ')'

Put that in a file named and your string in a file mystring.txt and run it as follows:

cat mystring.txt | python

You can then copy the output and paste it into your editor.

Modify this as needed to handle any special cases but this works for my needs. Hope this helps!

answered 7 years ago Monir #22

In Eclipse if you turn on the option "Escape text when pasting into a string literal" (in Preferences > Java > Editor > Typing) and paste a multi-lined string whithin quotes, it will automatically add " and \n" + for all your lines.

String str = "paste your text here";

answered 7 years ago Leo #23

See Java Stringfier. Turns your text into a StringBuilder java block escaping if needed.

answered 7 years ago Danubian Sailor #24

It may seem a little crazy, but since heredocs are syntactic sugar over one-line declarations with linebreaks escaped, one could write pre-processor for Java files that would change heredocs into single-liners during preprocessing.

It would require writing proper plugins for preprocessing files before compilation phase (for ant/maven build) and a plugin to IDE.

From an ideological point of view, it differs nothing from f.g. "generics", that is also a kind of pre-processed syntactic sugar over casting.

It's, however, a lot of work, so I would at your place just use .properties files.

answered 6 years ago Dan Lo Bianco #25

If you like google's guava as much as I do, it can give a fairly clean representation and a nice, easy way to not hardcode your newline characters too:

String out = Joiner.on(newline).join(ImmutableList.of(

answered 6 years ago SRG #26

This is an old thread, but a new quite elegant solution (with only one drawback) is to use a custom annotation.

Check :

Edit: The above URL seems to be broken. A project inspired from that work is hosted on GitHub:

public final class MultilineStringUsage {

  private static String html;

  public static void main(final String[] args) {

The drawback is that you have to activate the corresponding (provided) annotation processor.

And you probably have to configure Eclipse to not reformat automatically your Javadoc comments.

One may find this weird (Javadoc comments are not designed to embed anything other than comments), but as this lack of multiline string in Java is really annoying in the end, I find this to be the worst solution.

answered 5 years ago David Pickett #27

Late model JAVA has optimizations for + with constant strings, employs a StringBuffer behind the scenes, so you do not want to clutter your code with it.

It points to a JAVA oversight, that it does not resemble ANSI C in the automatic concatenation of double quoted strings with only white space between them, e.g.:

const char usage = "\n"
"Usage: xxxx <options>\n"
"Removes your options as designated by the required parameter <options>,\n"
"which must be one of the following strings:\n"
"  love\n"
"  sex\n"
"  drugs\n"
"  rockandroll\n"
"\n" ;

I would love to have a multi-line character array constant where embedded linefeeds are honored, so I can present the block without any clutter, e.g.:

String Query = "
    another column
      one_table a
      another_table b
    ON =
      AND a.role_code = b.role_code
  WHERE a.dept = 'sales'
    AND b.sales_quote > 1000
  Order BY 1, 2
" ;

To get this, one needs to beat on the JAVA gods.

answered 5 years ago jpfreire #28

Use Properties.loadFromXML(InputStream). There's no need for external libs.

Better than a messy code (since maintainability and design are your concern), it is preferable not to use long strings.

Start by reading xml properties:

 InputStream fileIS = YourClass.class.getResourceAsStream("MultiLine.xml");
 Properties prop = new Properies();

then you can use your multiline string in a more maintainable way...

static final String UNIQUE_MEANINGFUL_KEY = "Super Duper UNIQUE Key";
prop.getProperty(UNIQUE_MEANINGFUL_KEY) // "\n    MEGA\n   LONG\n..."

MultiLine.xml` gets located in the same folder YourClass:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "">

    <entry key="Super Duper UNIQUE Key">

PS.: You can use <![CDATA[" ... "]]> for xml-like string.

answered 5 years ago Fakeer #29

I sometimes use a parallel groovy class just to act as a bag of strings

The java class here

public class Test {
    public static void main(String[] args) {
        // consume .. parse json

And the coveted multiline strings here in TestStrings.groovy

class TestStrings {
    public static String json1 = """
        "name": "Fakeer's Json",
        "messages":["msg 1","msg 2","msg 3"]

Of course this is for static strings only. If I have to insert variables in the text I will just change the entire file to groovy. Just maintain strong-typing practices and it can be pulled off.

answered 4 years ago Mykhaylo Adamovych #30

    import org.apache.commons.lang3.StringUtils;

    String multiline = StringUtils.join(new String[] {
        "It was the best of times, it was the worst of times ", 
        "it was the age of wisdom, it was the age of foolishness",
        "it was the epoch of belief, it was the epoch of incredulity",
        "it was the season of Light, it was the season of Darkness",
        "it was the spring of hope, it was the winter of despair",
        "we had everything before us, we had nothing before us"
    }, "\n");

answered 4 years ago Rodney P. Barbati #31

Actually, the following is the cleanest implementation I have seen so far. It uses an annotation to convert a comment into a string variable...

  private static String html;

So, the end result is that the variable html contains the multiline string. No quotes, no pluses, no commas, just pure string.

This solution is available at the following URL...

Hope that helps!

answered 4 years ago icza #32


Java 8 added a new static method to java.lang.String which offers a slightly better alternative:

String.join( CharSequence delimiter , CharSequence... elements )

Using it:

String s = String.join(
    "First line.",
    "Second line.",
    "The rest.",
    "And the last!"

answered 4 years ago Ruslan Ulanov #33

It's not entirely clear from the question if author is interested in working with some sort of formatted large strings that need to have some dynamic values, but if that's the case a templating engine like StringTemplate ( might be very useful.

A simple sample of the code that uses StringTemplate is below. The actual template ("Hello, < name >") could be loaded from an external plain text file. All indentation in the template will be preserved, and no escaping is necessary.

import org.stringtemplate.v4.*;
public class Hello {
    public static void main(String[] args) {
        ST hello = new ST("Hello, <name>");
        hello.add("name", "World");

P.S. It's always a good idea to remove large chunks of text from source code for readability and localization purposes.

answered 2 years ago Bruno Marinho #34

One good option.

import static some.Util.*;

    public class Java {

        public static void main(String[] args) {

            String sql = $(
              "Select * from java",
              "join some on ",
              "group by"        



    public class Util {

        public static String $(String ...sql){
            return String.join(System.getProperty("line.separator"),sql);


answered 2 years ago nurettin #35

In the IntelliJ IDE you just need to type:


Then position your cursor inside the quotation marks and paste your string. The IDE will expand it into multiple concatenated lines.

answered 5 months ago alostale #36

JEP 326: Raw String Literals will implement multi-line Strings, so you will be able to write something like:

String s = `

At this moment (May 2018), this is not included in future JDK 11, so hopefully it will be available in JDK 12.

answered 3 months ago Morteza Adi #37

I know this is an old question, however for intersted developers Multi line literals gonna be in #Java12

answered 1 day ago nullpointer #38

With JDK/12 early access build # 12, one can now use multiline strings in Java as follows :

String multiLine = `First line
    Second line with indentation
Third line
and so on...`; // the formatting as desired

and this results in the following output:

First line
    Second line with indentation
Third line
and so on...

comments powered by Disqus