What's the difference between String.format() and str.formatted() in Java?
Asked Answered
M

2

21

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!

Madura answered 5/2, 2022 at 3:17 Comment(3)
format() is a static method of the String class. formatted() is a method of an instance of the String class.Munt
formatted was added much later, as a usability enhancement for text blocks. There’s no difference in functionality.Choreodrama
"formatted was added much later", that is: JDK 15!Cliffhanger
C
24

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)

Cramped answered 5/2, 2022 at 10:52 Comment(1)
Why isn't formatted implemented as return String.format(this, args);? Seems like a missed opportunity of DRYing the codeAllophane
M
6

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)
Monogenic answered 3/6, 2023 at 12:8 Comment(1)
Thorough, detailed answer. Well done. 1 nitpick: I don't think I'd say String.format() is "much more cleaner" than .formatted(), and not bc the English is incorrect, but because it's just slightly cleaner, so just "cleaner" is sufficient, or if you want to use a qualifier, "slightly" or similar would be more precise.Xanthus

© 2022 - 2024 — McMap. All rights reserved.