Tuesday, January 13, 2009

Java String formatting with "printf" like commands

There is a cool new way to create String templates in java and use the String.format() static method to substitute values dynamically.

For example the code snippet

  1. String message="Hello %1$s";
  2. message = message.format(message,"Jane Doe");
  3. System.out.println(message);

The output is:

> Hello Jane Doe

This gives you an idea of how to create string templates and replace them by using printf like syntax. Here is the sun link that will give you more on this style of formatting. http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html in our project we are using this on the message properties and substituting values for more meaningfull validation messages.

Here is one more example with multiple indexes.

  1. String x = "test who let the stars out '%2$s' ";
  2. String y = "me";
  3. String z = "you";
  4. String message = String.format(x,new String[]{y,z});
  5. System.out.println(message);

The index "2" in the line number 1 refers to the second array element in the string array that is passed to the format utility in line number 4.

Much more complicated example are available in the sun link. I tried the above examples in Java 1.5.

No comments:

Post a Comment