Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

String.format(...) help...?

I've been using the format(..) method from the Formatter class as a Static method as shown. I can't figure out why I can do that. In other words, I don't see the connection between the String class and the Formatter class that allows me to do that.

Update:

Interesting. I found out that I had been consulting an early version of Java in which the String class does NOT have a format(..) method:

http://download.oracle.com/javase/1.4.2/docs/api/j...

After your answer I went to the Oracle Java Tutorials site and searched for string and found that newer versions of Java String does have the method.

http://download.oracle.com/javase/7/docs/api/java/...

Thanks. I thought that there was something that I didn't understand about the basic heirarchy of classes, etc.

Update 2:

As soon as I can I'll rate your answer.

1 Answer

Relevance
  • 10 years ago
    Favorite Answer

    format() is a static method of the String class, and produces a String result. It uses a Formatter object, which has a different format() method. The Formatter method is not static and writes its output into the Formatter objects destination, either a StringBuilder/StringBuffer object or some kind of stream or writer.

    The static String.format() method makes sense as a kind of "factory method" for producing string objects. Internally, it likely uses a Formatter object to create a StringBuilder object. The result you see would then from a toString() call on the StringBuilder object to get the result as a String. That dance is required because Strings are immutable.

Still have questions? Get your answers by asking now.