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?
The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.
The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.
format gives you more power in "formatting" the string; and concatenation means you don't have to worry about accidentally putting in an extra %s or missing one out. String. format is also shorter. Which one is more readable depends on how your head works.
locale which is the locale value to be applied on the this method. format which is the format according to which the String is to be formatted. args which is the number of arguments for the formatted string. It can be optional, i.e. no arguments or any number of arguments according to the format.
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 String
s 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 String
s in general.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With