Press "Enter" to skip to content

Java 13 String API Updates

Java 13 features another attempt at bringing multiline strings to the language – this time in a form of JEP-355 Text Blocks.

This, in turn, creates demand for additional String methods that complement the new syntax.

String#formatted(java.lang.Object[])

This method allows us to conveniently format the provided String template with given arguments – think non-static String#format.

System.out.println("Hello %s!".formatted("World")); // Hello World!

If we look underneath, we can see that this is effectively just a convenience for Java 1.5’s Formatter:

public String formatted(Object... args) {
    return new Formatter().format(this, args).toString();
}

String#stripIndent()

This method allows us to trim redundant indentation from each line while preserving the relationship between them – which is essentially the same that the compiler does when preprocessing Text Blocks.

If that wasn’t supported, we’d end up with a lot of redundant whitespace in our Strings and we surely wouldn’t want that to happen!

The simple example would involve having a String consisting of two four-space-indented lines:

var s1 = "    foo\n.   bar";

If we print it out, we can notice that both lines are indeed indented:

System.out.println(s1);
    foo
    bar

…but if we process the String with the new API method, we can see that the redundant indentation is gone:

System.out.println(s1.stripIndent());
foo
bar

String#translateEscapes()

Addition of Text Blocks triggered a discussion about the philosophy of dealing with escape sequences.

The new approach is encapsulated by the new String#translateEscapes methods which translate escape sequences as if in a String literal:

System.out.println("\n".equals("\\n".translateEscapes())); // true

Why are new methods already deprecated?

The curious ones out there will quickly spot that all the new methods are deprecated for removal:

@Deprecated(forRemoval=true, since="13")

The reality is that all the new methods are associated with the new Text Block features and in order to preserve backward compatibility, they are marked as not safe to use, yet.

Summary

Addition of Text Blocks to Java created a demand for new String methods.

However, since Text Blocks and above methods are a Preview feature, it’s advised to not use them in production code yet.




If you enjoyed the content, consider supporting the site: