Pop quiz: Hashtable is to HashMap as StringBuffer is to …

Answer: StringBuilder. I recently worked on a Java project where the target environment was Java 1.5. Although Java 1.5 has been out for almost three years, the client was just upgrading to it to take advantage of its [language features](http://mcqueeney.com/roller/page/tom?entry=new_features_in_jdk_5) and APIs. While working on the project, I noticed most developers continued to use the StringBuffer class when [StringBuilder](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html) would have been the better choice. In asking around, most developers said they were unaware of StringBuilder. In case you’re using Java 1.5 or 1.6 but not yet using StringBuilder, StringBuilder is an unsynchronized version of the tried-and-true [StringBuffer](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html) class. Most of StringBuffer’s public methods are synchronized to allow multiple threads to read and modify the string simultaneously. But since StringBuffer is almost always used to build up a string within a method, or to build a string over several method calls within a single-threaded environment, the synchronized nature of StringBuffer is overkill. An [article](http://www.ddj.com/dept/java/188700760?pgno=2) in Dr. Dobb’s Journal in June 2006 estimated switching from StringBuffer to StringBuilder could speed string building by 38%. That’s why Sun added StringBuilder to the language in JDK 5. None of StringBuilder’s methods is synchronized, so the class is not meant to be used when multiple threads need to access the string. In multi-threaded contexts, you will want to use StringBuffer. But consider your own code. How many times have you needed to share a StringBuffer between multiple threads? You’ll probably find that StringBuilder is often the better choice.