Feb 16
A lot has been said, written and blogged on this subject, I know. I’ll try to cover it from the disassembly angle, though, after going over the main points of this comparison.
Why use StringBuilder?
A good question deserves a good answer. See, the String class is an immutable class - It will never really change internally. When you use the operator + it actually generates code that does it for you, and if you use the concat(String) it is clearly stated that a new string is created.
Worthy to note is that all of String methods do not change the string itself, but rather return a new String. More than once I’ve seen people calling replace and wondering why it does not work - They had forgot to take the returned value as the new value!
StringBuilder? I thought it was called StringBuffer!
The sharp eyed might notice that in J2SE 5.0, a new class was introduced called StringBuilder, while up until then there was a class called StringBuffer. Well, StringBuffer is still there, and I’ve discussed their differences earlier as an aside of a different post.
Continue reading »
Feb 09
I wonder how many people actually know about java.text.MessageFormat. I didn’t until a few days ago, and it’s a shame, in my opinion.
In Java 5.0, we were introduced with a new feature which was the new String.format method, with the complimentary PrintStream.printf method (classically used via the System.out member). This feature allowed us to go back to the old C days, and write things like String.format("The index is %d", idx) instead of the old, familiar System.out.print("The index is " + idx). Obviously, better uses for this method have been found.
However, the MessageFormat class provided this functionality, even if in a bit more complicated manner, years ago. Getting to know MessageFormat I found out that:
- It’s faster For a simple format, such as “The index is X and the letter is Y” where X was some loop index and Y was the character achieved by
'a' + (X % 26), MessageFormat.format worked about three times faster than String.format.
- It’s bi-directional With a complimentary
MessageFormat.parse method, you could extract the same parameters you use for formatting from an already formatted text.
- Optional choice formatting Inside the format pattern you can define conditions that would show different values relevant to the value passed. For example, you could show “no entries” if the value passed was 0, and “X entries” if the value passed was higher, by just writing
{0, choice, "0#no entries|0< {0} entries"} as a format pattern. Obviously, there’s a class externalising this behaviour called ChoiceFormat.
Give it a try. In my opinion, it’s very useful when one needs to generate the same patterned text for different values in some iteration or at a triggered event - patterned text such as SQL code or log messages.
Edited: removed the SQL code generation. As noted in the comments, it’s better to use PreparedStatement instead.