Jump to Real's How-to Main page

Format a String (JDK1.5)

JDK1.5 simplifies the operation of formatting a String based on parameters.

The String class now provides a new method called format(). The parameter substitution mechanism is heavily inspired by C's printf.

String s = String.format
   ("Welcome %s at %s", "Real's HowTo", "http://www.rgagnon.com");
// output : Welcome Real's HowTo at http://www.rgagnon.com
A printf method has been added to System.out !
System.out.printf
  ("Welcome %s at %s", "Real's HowTo", "http://www.rgagnon.com");
As you can see, it is now possible to call a method with a variable number of parameters. But it is also possible to use an array (with the new String.format()).
String a[] = { "Real's HowTo", "http://www.rgagnon.com" };

String s = String.format("Welcome %s at %s", a);
System.out.println(s);

Object a[] = { "Real's HowTo", "http://www.rgagnon.com" ,
        java.util.Calendar.getInstance()};

String s = String.format("Welcome %1$s at %2$s ( %3$tY %3$tm %3$te )", a);
//  output : Welcome Real's HowTo at http://www.rgagnon.com (2004 03 7)
You can use this new feature to quickly format strings into table :
public class Divers {
  public static void main(String args[]){
      String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
      System.out.format(format, "FirstName", "Init.", "LastName");
      System.out.format(format, "Real", "", "Gagnon");
      System.out.format(format, "John", "D", "Doe");

      String ex[] = { "John", "F.", "Kennedy" };

      System.out.format(String.format(format, (Object[])ex));
  }
}
Output:
|FirstName |Init.     |LastName            |
|Real      |          |Gagnon              |
|John      |D         |Doe                 |
|John      |F.        |Kennedy             |

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2007
[ home ]