String vs StringBuffer and StringBuilder in Java

In Java, a String is a primitive data type and almost all developers use String for a character strings operation. Other than that, Sun provided StringBuffer, StringBuilder.


What are the differences between the String, Stringbuffer, and Stringbuilder?

1. String: A string is immutable, which means that once a String is created, its value cannot be changed.

String s = "Hello";

s = s + " World!";


When executing this code, the string Hello World! will be printed. How?

Java created a new String object and stored "Hello World!" as its value. If this style of coding is used often in a program, the program will have performance problems due to the lack of memory.

2. StringBuffer: A StringBuffer is mutable, which means once a StringBuffer object is created, we just append the content to the value of the object instead of creating a new object. Their methods are synchronized when necessary so that the StringBuffer will be used effectively in threads. The StringBuffer runs slow in a one-thread program.

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World!");
System.out.println(sb.toString()); //Hello World!

3. StringBuilder: The StringBuilder is essentially the same as StringBuffer but it is not thread-safe, that means that their methods are not synchronized. In comparison to the other Strings, the Stringbuilder runs the fastest. 

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World!");
System.out.println(sb.toString()); //Hello World!