Last editor: Dave Cherry, last modified: Oct 25, 2009
Over the years there have been no shortage of ways to format a string in java. What
with the + operator, StringBuffer, StringBuilder,
String.format(..) and various specialised formatters for numbers and dates
we sometimes feel a little spoilt for choice. But how do they all work and what are
their advantanges / disadvantages?
StringBuffer is a synchronized object! Yes, everything you do with it will
cause synchronization. This is for historic reasons, unless you actually want this side
effect use StringBuilder which has the same methods without the overhead.
This object provides a simple way to concatenate various types. See the example below that uses StringBuilder to concatenate a String, char and a String:
public class Formatting
{
public static void main(String[] args)
{
final int DEFAULT_SIZE = 100;
StringBuilder sb = new StringBuilder(DEFAULT_SIZE);
sb.append("Hello");
sb.append(' ');
sb.append("World");
System.out.println(sb.toString());
}
}
Note that when I construct the object I pass in the desired capacity, this is because the default size of a StringBuilder is 16 characters, so to grow to 256 characters would take several re-allocations.
Unless you are in a critical section of code, there probably little wrong with
just adding strings together using the + and += operator. For example, the slight
overhead of doing this would not be noticed during initialisation. In addition, I believe
that if used carefully it does not make the code less readable. For some time java
compilers have optimised this out into a series of calls to StringBuilder.
Just note the above problem, with the default size of StringBuilder as this applies here to.
Next pages, using String.format(..), numbers and NumberFormat. Last page, dates and DateFormat.