Already since Java 5.0 (released in Sept. 2004) the String class has been extended by the “format“ class method. This method offers the possibility to use placeholders in a string that will be replaced by argument values. Similar methods are known as “sprinf“ or simply “printf” in various programming languages.

With String.format the following expression

String s = "Hello " + name;

can be re-written as

String s = String.format("Hello %s", name);

It‘s getting more interesting if you want to output formatted values. Here is another example which outputs a number and a formatted date:

String s = "Found "  count  " requests since " + DateFormat.getDateInstance().format(date);

Now the same expression with the String.format method.

String s = String.format("Found %d requests since %tD", count, date);

Check out the javadocs for more information:



Marco Rico Gomez is a passionate software developer located in Germany who likes to share his thoughts and experiences about software development and technologies with others.

blog comments powered by Disqus