"Cheaper" in what sense? Performance, I presume. However I think it's pretty rare that a method like this is a significant bottleneck. Particularly since formatting a string is typically a prelude to writing it somewhere, and most IO operations will probably take significantly longer than the formatting anyway. I think the main thing to look for here is something that's easy to read, easy to debug, and easy to modify when requirements change. I would suggest that now that J2SE 5 is out, the preferred way to do this is with a format string, e.g:
The "%5d" is a format string, which indicates a decimal number formatted to a length of five spaces, padded in frot with zeros. There's a bit of a learning curve to understand format strings initially, but I think it's time well spent. With a little practice you can read them fairly easily, and you have access to tremendous flexibility in how you format things. Here's another sample of their use. Run it and see what you get:
An added advantage is that most of the methods in StringUtils are null safe, if that meets your requirements.
The future is here. It's just not evenly distributed yet. - William Gibson
Consultant @ Xebia. Sonny GillTweets
Joined: Jan 29, 2003
Cheaper in CPU cycles / performance, yes. Substringing and concatenating was about 100x faster than two SimpleDateFormats and a Date in a routine that converted MM/DD/YYYY to YYYYMMDD for us. Of course you have to do a million or so in a row to notice the difference, so as usual write for humans to understand first, optimize if you prove it's a problem.
We're still working with J2SE 1.4 here, so I wrote the following function:
There are probably much better ways.
Joined: Jan 29, 2003
The nice thing about that solution is that you can generalize it to pad any string with any character. You might be able to shave some milliseconds off by computing the length of pad you'll need and use Arrays.fill() or something. Again: readable first, milliseconds later.
The REXX language calls this function right() because it right justifies. It also truncates if the string is too long to start with, which is perhaps correct (or not) if you're writing columnar reports to a text file or console. The REXX string and word functions are very sensible; worth looking at as inspiration before you embark on writing a library of your own.