The classes StringBuilder and StringBuffer have exactly the same list of methods. The difference is that the methods of the class StringBuilder perform faster than the same methods of the class StringBuffer. That is because the class StringBuffer has an overhead of not allowing concurrent access to its values from different application threads. So, if you are not coding for multithreaded processing, use StringBuilder.
There are many methods in the classes StringBuilder and StringBuffer. But, we are going to show how to use only the method append(), which is by far the most popular, used for cases when multiple String value modifications are required. Its main function is to append a value to the end of the value already stored inside the StringBuilder (or StringBuffer) object.
The method append() is overloaded for all primitive types and for the classes String, Object, CharSequence, and StringBuffer, which means that a String representation of the passed-in object of any of these classes can be appended to the existing value. For our demonstration, we are going use only the append(String s) version because that is what you are probably going to use most of the time. Here is an example:
List<String> list =
List.of("That", "is", "the", "way", "to", "build", "a", "sentence");
StringBuilder sb = new StringBuilder();
for(String s: list){
sb.append(s).append(" ");
}
String s = sb.toString();
System.out.println(s); //prints: That is the way to build a sentence
There are also methods replace(), substring(), and insert() in the class StringBuilder (and StringBuffer) that allow modifying the value further. They are used much less often than the method append() though, and we are not going to discuss them as they are outside the scope of this book.