19. Declaring multiline strings (text blocks)

At the time of writing this book, JDK 12 had a proposal for adding multiline strings known as JEP 326: Raw String Literals. But this was dropped at the last minute. 

Starting with JDK 13, the idea was reconsidered and, unlike the declined raw string literals, text blocks are surrounded by three double quotes, """, as follows:

String text = """My high school,
the Illinois Mathematics and Science Academy,
showed me that anything is possible
and that you're never too young to think big.""";
Text blocks can be very useful for writing multiline SQL statements, using polyglot languages, and so on. More details can be found at https://openjdk.java.net/jeps/355.

Nevertheless, there are several surrogate solutions that can be used before JDK 13. These solutions have a common point—the use of the line separator:

private static final String LS = System.lineSeparator();

Starting with JDK 8, a solution may rely on String.join(), as follows:

String text = String.join(LS,
"My high school, ",
"the Illinois Mathematics and Science Academy,",
"showed me that anything is possible ",
"and that you're never too young to think big.");

Before JDK 8, an elegant solution may have relied on StringBuilder. This solution is available in the code bundled with this book.

While the preceding solutions are good fits for a relatively large number of strings, the following two are okay if we just have a few strings. The first one uses the + operator:

String text = "My high school, " + LS +
"the Illinois Mathematics and Science Academy," + LS +
"showed me that anything is possible " + LS +
"and that you're never too young to think big.";

The second one uses String.format():

String text = String.format("%s" + LS + "%s" + LS + "%s" + LS + "%s",
"My high school, ",
"the Illinois Mathematics and Science Academy,",
"showed me that anything is possible ",
"and that you're never too young to think big.");
How can we process each line of a multiline string? Well, a quick approach requires JDK 11, which comes with the String.lines() method. This method splits the given string via a line separator (which supports  , , and ) and transforms it into Stream<String>. Alternatively, the String.split() method can be used as well (this is available starting with JDK 1.4). If the number of strings becomes significant, it is advised to put them in a file and read/process them one by one (for example, via the getResourceAsStream() method). Other approaches rely on StringWriter or BufferedWriter.newLine().

For third-party library support, please consider Apache Commons Lang, StringUtils.join()Guava, Joiner, and the custom annotation, @Multiline.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.47.169