Skip to content
Advertisement

What’s the difference between String.format() and str.formatted() in Java?

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!

Advertisement

Answer

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)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement