Java string builder vs string buffer

ww‮ual.w‬tturi.com
Java string builder vs string buffer

StringBuilder and StringBuffer are both classes in Java that allow you to create modifiable strings. They have the following differences:

  • StringBuilder is faster than StringBuffer because it is not thread-safe. This means that it is not synchronized, so it can be used in a single-threaded environment without any additional synchronization code.

  • StringBuffer, on the other hand, is thread-safe. This means that it is synchronized, so it can be used in a multi-threaded environment without the need for additional synchronization. However, this added synchronization comes at a cost, and StringBuffer is slower than StringBuilder.

Both StringBuilder and StringBuffer have the same methods for appending, inserting, and deleting characters from the string. Here's an example of how to use them:

StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.insert(5, " world");

StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.insert(5, " world");

In general, you should use StringBuilder unless you specifically need the thread-safety provided by StringBuffer.

Created Time:2017-10-17 20:18:53  Author:lautturi