StringBuilder was introduced in JDK 1.5. What's the difference between StringBuilder and StringBuffer? According to javadoc, StringBuilder is designed as a replacement for StringBuffer in single-threaded usage. Their key differences in simple term:
- StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized. StringBuilder does not handle thread-safety issue and none of its methods is synchronized.
- StringBuilder has better performance than StringBuffer under most circumstances.
- Use the new StringBuilder wherever possible.
/**Note the above javadoc still refers to StringBuffer where it should be StringBuilder.
* readObject is called to restore the state of the
* StringBuffer from a stream.
private void readObject(java.io.ObjectInputStream s)
2 interesting methods in StringBuilder or StringBuffer are
- reverse() method modifies the current this StringBuilder/StringBuffer, and also returns itself. More details in Reverse a String with StringBuilder or StringBuffer
- equals(Object) method is not implemented (overridden) in StringBuilder/StringBuffer. So comparing 2 instances of the same content will return false. Also there is no equalsIgnoreCase() method on StringBuilder/StringBuffer. However, toString() is implemented to return a string representing the data in this StringBuilder/StringBuffer.