Text blocks and formatting
Multi-line text and neat number output are common tasks. For the first, Java has text blocks; for the second, template-based formatting.
A text block
A text block starts with three quotes """ and a line break, and ends with three quotes. Line breaks inside are kept, and regular quotes need no escaping:
void main() {
String poem = """
Roses are red,
Violets are blue,
"Java" is great!
""";
IO.print(poem);
}Output:
Roses are red,
Violets are blue,
"Java" is great!Java removes the common indentation on the left by itself: it is measured from the leftmost line and the position of the closing """.
Indentation inside a block
Extra indentation of individual lines is kept. This is handy for JSON, HTML and SQL right in the code:
void main() {
String json = """
{
"name": "Anna",
"age": 30
}""";
IO.println(json);
}Output:
{
"name": "Anna",
"age": 30
}Here the closing quotes come right after }, so there is no line break at the end of the block.
formatted and String.format
The formatted() method fills values into a template. In the template, %s marks a place for a string, %d for a whole number, and %.2f for a fractional number with two decimal places:
void main() {
String name = "Oleg";
int cups = 3;
double total = 10.5;
String text = "%s ordered %d cups for $%.2f".formatted(name, cups, total);
IO.println(text);
}Output:
Oleg ordered 3 cups for $10.50String.format(template, values) does the same. Note that the decimal separator follows the system's regional settings: an English locale uses a dot, while a German or Russian one prints 10,50.
printf
System.out.printf() formats and prints at once. A line break in the template is written as %n:
void main() {
System.out.printf("Item: %s, price: %.1f%n", "tea", 2.456);
System.out.printf("%d%% done%n", 75);
}Output:
Item: tea, price: 2.5
75% done%.1f rounds to one decimal place. To print the percent sign itself, double it: %%.
Field width
A number between % and the letter sets the minimum width. By default the value is right-aligned, and a minus sign left-aligns it. That is how you get even tables:
void main() {
String format = "%-10s|%6d%n";
System.out.printf(format, "Apples", 12);
System.out.printf(format, "Pears", 7);
System.out.printf(format, "Oranges", 150);
}Output:
Apples | 12
Pears | 7
Oranges | 150Common mistake
No text may follow the opening """ on the same line — a line break must come right after it:
void main() {
String text = """Hello,
world""";
IO.println(text);
}Output (the first error; the compiler then prints four more that follow from it):
Main.java:2: error: illegal text block open delimiter sequence, missing line terminator
String text = """Hello,
^Start the block's content on the next line.