Text Blocks were finalized and permanently added in JDK 15 and some additional methods added to support text blocks. One of this methods is:
String::formatted(Object... args)
And I know the functions of two codes below are the same.
As you mentioned in your question both methods do the same job and return same results. The goal of introducing such a method is:
simplify value substitution in the Text Block.
Based on JEP (JDK Enhancement Proposals) 378:
Text blocks do not directly support string interpolation. Interpolation may be considered in a future JEP. In the meantime, the
new instance method String::formatted
aids in situations where
interpolation might be desired.
As an example you consider this code segment:
String code = String.format("""
public void print(%s o) {
System.out.println(Objects.toString(o));
}
""", type);
We can change it using formatted method as:
String source = """
public void print(%s object) {
System.out.println(Objects.toString(object));
}
""".formatted(type);
Which is cleaner.
Also consider these minor differences between them when using the methods:
public static String format(String format, Object... args)
- Returns a formatted string using the format string and arguments.
- It's a static method of
String
class.
- It's introduced in Java SE 5 [since 2004].
public String formatted(Object... args)
- Formats using this string as the format string, and the supplied arguments.
- It's an instance method of
String
class.
- It's introduced in Java SE 15 (JDK 15) [since 2020].
- This method is equivalent to
String.format(this, args)
format()
is a static method of the String class.formatted()
is a method of an instance of the String class. – Muntformatted
was added much later, as a usability enhancement for text blocks. There’s no difference in functionality. – Choreodrama