yuku yuku - 1 month ago 6
Java Question

Why is String's format(Object... args) defined as a static method?

I wonder why Java 5 and above provide a printf-style formatter using a static method in class String like this:

public static String format(String format, Object... args)


instead of

public String format(Object... args)


so that we can write
"%02d".format(5)
to get
05
instead of
String.format("%02d", 5)
.

I imagined if I could modify the String class, I could add this:

public String format(Object... args) {
return format(this, args)
}


to get the same result.

I found that in C#, a static method is also used instead of an instance method.

I wonder why they decided to do this, but I didn't come to an explanation. The instance methods
trim
and
substring
returns a new instance of string, so they should have done the same thing with
format
.

Moreover, the
DateFormat
class also uses this:

public final String format(Date date)


for formatting dates. So if we consider the instance of DateFormat as the formatter, an instance of String could also be used as a formatter.

Any ideas?

Answer

Perhaps "%02d".format(5) seems to imply that the object on which the format method is being called is a format string.

In this case, the format string happens to also be a String, so furthering that point, one could argue that all Strings are format strings.

Probably this can be avoided by saying that a static method in the String class can be used to format a string, rather than making some implicit statement about all Strings in general.