Do you know Java: Text Blocks


Text blocks is a new proposed feature, hopefully coming with Java 15.

Until then, let us see how it looks like in Java 14 as a feature preview.

Here is how we declare a multiline string value. Once we have to concatenate, and also have to place new line characters (\n).

String text = "one line\n" +
              "and\n" +
              "another";

When text is printed out:

one line
and
another

The new feature looks like the following. Much comfortabl compared to the one which we can use nowadays.

String text = """
            one line
            and
            another
             """;

And the output is the same.

Things that we have to mention here. Since, this feature is preview, we have to use --enable-preview and --release 14 options with javac. Bear in mind that indentation matters.

$ java --enable-preview --source 14 Main.java                 
Note: Main.java uses preview language features.
Note: Recompile with -Xlint:preview for details.
one line
and
another

I am looking forward to seeing text block in Java! Hope, it will be shipped with Java 15.

Further reading about JEP 378: Text Blocks

Code can be found: https://github.com/torokmark/do-you-know-java