Java Equivalent to .NET's String.Format

Is there an equivalent to .NET's String.Format in Java?


Solution 1:

The 10 cent answer to this is:

C#'s


String.Format("{0} -- {1} -- {2}", ob1, ob2, ob3)

is equivalent to Java's


String.format("%1$s -- %2$s -- %3$s", ob1, ob2, ob3)

Note the 1-based index, and the "s" means to convert to string using .toString(). There are many other conversions available and formatting options:

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

Solution 2:

Have a look at the String.format and PrintStream.format methods.

Both are based on the java.util.Formatter class.

String.format example:

Calendar c = new GregorianCalendar(1995, MAY, 23);
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"

System.out.format example:

// Writes a formatted string to System.out.
System.out.format("Local time: %tT", Calendar.getInstance());
// -> "Local time: 13:34:18"