String is a sequence of characters in Java. String is a class in the java.lang package. String objects are immutable in nature.
Example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
StringBuffer is a mutable sequence of characters in Java. StringBuffer is like a String but can be modified. String buffers are safe for use by multiple threads.
Example:
StringBuffer obj = new StringBuffer("Neptune");
obj.append("World");
System.out.println(obj);
Output :
NeptuneWorld
StringBuilder is a mutable sequence of characters. It is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type.
The append method always adds characters at the end of the builder; the insert method adds the characters at a specified point.
Instances of StringBuilder are not safe for use by multiple threads.
Example:
StringBuilder obj = new StringBuilder("Neptune");
obj.append("World");
System.out.println(obj);
Output :
NeptuneWorld
If a string is going to remain constant throughout the program, then its recommended to use String because a String object is immutable in nature.
Example :
public static void ExampleString() {
String str = new String("Neptune");
String new_str = str + "World";
System.out.println(new_str);
}
If a string can change and will be accessed by multiple threads, then use a StringBuffer because StringBuffer is synchronous, so you have thread-safety.
Example :
public static void ExampleStringBuffer() {
StringBuffer str_buff = new StringBuffer("Neptune");
str_buff.append("World");
System.out.println(str_buff);
}
If a string can change or lots of logic and operations in the construction of the string then use StringBuilder. Also if it is only be accessed from a single thread then StringBuilder is good enough.
Example :
public static void ExampleStringBuilder() {
StringBuilder str_build = new StringBuilder("Neptune");
str_build.append("World");
System.out.println(str_build);
1. String is immutable whereas StringBuffer and StringBuilder are mutable classes.
2. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That’s why StringBuilder is faster than StringBuffer.
3. String concatenation operator (+) internally uses StringBuffer or StringBuilder class.
4. For String manipulations in a non-multi threaded environment, we should use StringBuilder else use StringBuffer class.
That’s all for a quick roundup of differences between String, StringBuffer, and StringBuilder.