13

I know that method String.format() is nearly the same as method System.out.printf() except it returns a String. But I could hardly find the introduction about method "formatted" which is defined as follows:

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

And I know the functions of two codes below are the same.

String str1 = String.format("%s", "abab");
System.out.println(str1);
String str2;
str2 = "%s".formatted("abab");
System.out.println(str2);

Therefore I'm wandering what's the difference between them. Thank you!

NormalLLer
  • 183
  • 2
  • 11
  • 2
    `format()` is a static method of the String class. [`formatted()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#formatted(java.lang.Object...)) is a method of an instance of the String class. – President James K. Polk Feb 05 '22 at 03:20
  • 2
    `formatted` was added much later, as a usability enhancement for [text blocks](https://openjdk.java.net/jeps/378). There’s no difference in functionality. – Tim Moore Feb 05 '22 at 03:29
  • 1
    "formatted was added much later", that is: JDK 15! – Jacob van Lingen Mar 21 '23 at 10:00

2 Answers2

12

Make sure you use a good IDE so that you have easy access to browse into JDK source code. In Eclipse say, use F3 to open to any declaration. IntelliJ IDEA has similar feature.

If you view the source code for both methods, you can see these calls are identical except that variables this is interchanged with format when comparing the instance vs static method:

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

So as you've observed: String.format(str, args) is same as str.formatted(args)

DuncG
  • 12,137
  • 2
  • 21
  • 33
1

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 much more 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)
Mehdi Rahimi
  • 1,453
  • 5
  • 20
  • 31