Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 262
Randy Sugianto 'Yuku' Avatar asked Apr 27 '09 04:04

Randy Sugianto 'Yuku'


People also ask

What does format () do in java?

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.

What is formatting with the format () method?

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.

Why do we use string format?

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.

What is locale in string format?

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.


1 Answers

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.

like image 135
coobird Avatar answered Sep 20 '22 15:09

coobird