Java Text Blocks
A text block is a string literal written across several lines. The lines inside the block become the lines of the string.
Three lines in one literal
The block below holds three lines of text. Printing the string prints all three lines.
public class Main {
public static void main(String[] args) {
String verse = """
Roses are red
Violets are blue
Sugar is sweet
""";
System.out.print(verse);
}
}The closing delimiter sets the margin
Two blocks hold the same words at different depths. The comparison and the printout show both values come out the same.
public class Main {
public static void main(String[] args) {
String first = """
one
two
""";
String second = """
one
two
""";
System.out.println(first.equals(second));
System.out.print(first);
}
}A block is a plain String
The block below feeds a String method like any other string. The method counts the lines inside it.
public class Main {
public static void main(String[] args) {
String menu = """
Soup
Salad
Pasta
Bread
""";
System.out.println(menu.lines().count());
}
}Example
public class Main {
public static void main(String[] args) {
String address = """
Ada Lovelace
12 Engine Way
London
""";
System.out.println("Delivery address:");
System.out.print(address);
System.out.println("Lines: " + address.lines().count());
}
}Key points
- A text block opens with three double quotes and a line break.
- The content starts on the line after the opening delimiter.
- The closing delimiter sets the indentation stripped from every line.
- A text block value is a plain String, so String methods work on it.
- One literal holds many lines without joining separate strings with plus signs.
In this example, one text block holds a three-line address, the program prints it under a label, and the lines method counts its three lines.
Note
Spaces inside a line stay untouched, since only the shared left margin is stripped.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What decides how much indentation a text block strips from each line?