Java 15 String Methods: formatted, stripIndent and More
Introduction
Java 15Click to read tutorial: Overview of New Features in Java 15 made text blocksClick to read tutorial: Java Text Blocks: Multi-line Strings with Examples a standard feature, and added three methods to the
OUTPUT of the above code
Since the arguments come after the template, a text block with
stripIndent()
A text block removes incidental indentation - the indentation which comes only from where the text block sits in the source code - while keeping the relative indentation of its lines.
OUTPUT of the above code
The dots make the spaces visible. Every line lost the 6 spaces of common indentation, the
OUTPUT of the above code
An invalid escape such as
How these methods relate to text blocks
When the compiler processes a text block, it does three things, in this order: it normalizes line endings to
String class which go together with them. This tutorial explains the Java 15 String methods with examples - formatted(), an instance-method version of String.format(); stripIndent(), which removes incidental indentation from multi-line strings; and translateEscapes(), which turns escape sequences written as text into the characters they represent.
formatted()
Definition of String.formatted()
public String formatted(Object... args)"...".formatted(args) does exactly the same as String.format("...", args), using the string itself as the format. It reads better in a chain of method calls, and especially with a text block, where the format string comes first and the arguments follow -
String.formatted() with a text block
//FormattedDemo.java
public class FormattedDemo {
public static void main(String[] args) {
String name = "Java 15";
int jeps = 14;
System.out.println(String.format("%s has %d JEPs", name, jeps)); // before
System.out.println("%s has %d JEPs".formatted(name, jeps)); // Java 15
String json = """
{
"release": "%s",
"jeps": %d,
"lts": %b
}""".formatted(name, jeps, false);
System.out.println(json);
}
}
Java 15 has 14 JEPs
Java 15 has 14 JEPs
{
"release": "Java 15",
"jeps": 14,
"lts": false
}
%s placeholders becomes a simple, readable template for JSON, SQL or messages. Like String.format(), it uses the default locale; use String.format(Locale, ...) when the output must not depend on it.
stripIndent() applies the same algorithm to any string, which is useful for multi-line text which does not come from a text block, such as a string read from a file or built at runtime. It finds the smallest indentation of the non-blank lines, removes that much from every line, and also removes trailing spaces from each line.
Removing incidental indentation with stripIndent()
//StripIndentDemo.java
public class StripIndentDemo {
public static void main(String[] args) {
String sql = " SELECT name, marks\n"
+ " FROM students \n"
+ " WHERE marks > 75\n"
+ " ORDER BY marks DESC";
System.out.println("Before:\n" + sql.replace(' ', '.'));
System.out.println("After:\n" + sql.stripIndent().replace(' ', '.'));
}
}
Before: ......SELECT.name,.marks ......FROM.students... ........WHERE.marks.>.75 ......ORDER.BY.marks.DESC After: SELECT.name,.marks FROM.students ..WHERE.marks.>.75 ORDER.BY.marks.DESC
WHERE line kept its 2 extra spaces, and the trailing spaces after students were removed.
translateEscapes()
In Java source code, "\n" is a newline character. But a string read from a file or a configuration property may contain the two characters \ and n. translateEscapes() interprets such escape sequences the way the Java compiler does: \n, \t, \", \\, octal escapes, and the text block escapes \s (a space) and backslash-newline (a line continuation). Unicode escapes such as A are not translated, since the compiler handles those at an earlier stage.
Interpreting escape sequences at runtime
//TranslateEscapesDemo.java
public class TranslateEscapesDemo {
public static void main(String[] args) {
// As if read from a properties file: a real backslash followed by n and t
String fromConfig = "Name:\\tTom\\nMarks:\\t78";
System.out.println("Raw : " + fromConfig);
System.out.println("Translated:\n" + fromConfig.translateEscapes());
try {
"bad \\q escape".translateEscapes();
} catch (IllegalArgumentException e) {
System.out.println("Invalid escape -> " + e.getMessage());
}
}
}
Raw : Name:\tTom\nMarks:\t78 Translated: Name: Tom Marks: 78 Invalid escape -> Invalid escape sequence: \q \\u0071
\q throws an IllegalArgumentException, just as it would be a compile error in source code.
\n, removes the incidental indentation, and then interprets escape sequences. The last two steps are exactly stripIndent() and translateEscapes(), which were added so that the same processing is available for strings created at runtime. formatted() completes the set by making a text block easy to use as a template.
Summary
In this tutorial we went through the three String methods added in Java 15. We used formatted() to fill placeholders in a string or a text block, stripIndent() to remove the common indentation and trailing spaces of multi-line text, and translateEscapes() to interpret escape sequences in strings read at runtime. Lastly, we saw that the last two perform the same steps the compiler applies to text blocks. Next, read about the ZGC and Shenandoah garbage collectorsClick to read tutorial: ZGC and Shenandoah: Low-Pause GCs in Java 15.Continue Reading Java 12 to 17 Tutorials
Overview of New Features in Java 15Click to read tutorial: Overview of New Features in Java 15 Java Text Blocks: Multi-line Strings with ExamplesClick to read tutorial: Java Text Blocks: Multi-line Strings with Examples Java 15 Hidden Classes Explained with ExamplesClick to read tutorial: Java 15 Hidden Classes Explained with Examples ZGC and Shenandoah: Low-Pause GCs in Java 15Click to read tutorial: ZGC and Shenandoah: Low-Pause GCs in Java 15 Overview of New Features in Java 12Click to read tutorial: Overview of New Features in Java 12 Overview of New Features in Java 13Click to read tutorial: Overview of New Features in Java 13 Overview of New Features in Java 14Click to read tutorial: Overview of New Features in Java 14 Overview of New Features in Java 16Click to read tutorial: Overview of New Features in Java 16 Overview of New Features in Java 17Click to read tutorial: Overview of New Features in Java 17
Overview of New Features in Java 15Click to read tutorial: Overview of New Features in Java 15 Java Text Blocks: Multi-line Strings with ExamplesClick to read tutorial: Java Text Blocks: Multi-line Strings with Examples Java 15 Hidden Classes Explained with ExamplesClick to read tutorial: Java 15 Hidden Classes Explained with Examples ZGC and Shenandoah: Low-Pause GCs in Java 15Click to read tutorial: ZGC and Shenandoah: Low-Pause GCs in Java 15 Overview of New Features in Java 12Click to read tutorial: Overview of New Features in Java 12 Overview of New Features in Java 13Click to read tutorial: Overview of New Features in Java 13 Overview of New Features in Java 14Click to read tutorial: Overview of New Features in Java 14 Overview of New Features in Java 16Click to read tutorial: Overview of New Features in Java 16 Overview of New Features in Java 17Click to read tutorial: Overview of New Features in Java 17