StringBuilder and StringBuffer are two classes in Java that represent a sequence of characters. While the String class creates an immutable sequence of characters, the StringBuilder and StringBuffer classes create a mutable sequence of characters.
StringBuffer is a peer class of String and provides much of the same functionality as strings. However, while strings represent fixed-length, immutable character sequences, StringBuffer represents growable and writable character sequences.
The main difference between StringBuilder and StringBuffer is their synchronization. The StringBuilder class provides no guarantee of synchronization, while the StringBuffer class does. Therefore, the StringBuilder class is designed for use as a drop-in replacement for StringBuffer in places where the StringBuffer is being used by a single thread. StringBuilder is faster and preferred over StringBuffer for single-threaded programs. If thread safety is needed, then StringBuffer should be used. It is recommended that the StringBuilder class be used in preference to StringBuffer where possible, as it will be faster under most implementations. Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required, then it is recommended that StringBuffer be used.
Here is an example Java code that illustrates the internal working of the String, StringBuilder, and StringBuffer classes:
javaclass GfG {
public static void main(String[] args) {
// String class
String s1 = "geeks";
// s2 points to the same location as s1
String s2 = s1;
// Creates a new location to store s1
s1 = s1 + "forgeeks";
// s1 and s2 refer to different locations
if (s1 == s2) {
System.out.println("Same");
} else {
System.out.println("Not Same");
}
// StringBuilder or StringBuffer class
StringBuilder sb1 = new StringBuilder("geeks");
// sb2 refers to the same location as sb1
StringBuilder sb2 = sb1;
// Append operation modifies the same object
// as it is mutable in nature
sb1 = sb1.append("forgeeks");
// Both sb1 and sb2 refer to the same location
if (sb1 == sb2) {
System.out.println("Same");
} else {
System.out.println("Not Same");
}
}
}
The output of this code is:
Not Same Same
I hope this helps! Let me know if you have any further questions or concerns.