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?