RSS Feed Monday, 05 Jan 2009.

 

Formatting numbers, dates and other types into Strings using Java (Page 1 of 4)

Keywords:  java analysis formatting string

The background, string formatting in java

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 - a hang up from times gone by!

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.

StringBuilder - an easy way to concatenate data.

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.

Whats wrong with adding strings together anyway?

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.

 1   2   3   4  Next page >>

Comments [0]

Please leave a comment



captcha image
 

Blog Entries

prev January, 2009 next
SuMoTuWeThFrSa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31