In Java, String, StringBuffer, and StringBuilder are used to work with text data. They differ mainly in mutability, thread safety, and performance.
String object is created, it cannot be changed.StringBuffer allows modification and is synchronized.StringBuilder allows modification but is not synchronized.Type a word and click the buttons to see how memory is handled differently.
*Notice how a new object is created every time.
*Notice the Address Ref stays the same.
// Demonstrating immutability of String
String s = "Hello";
s.concat(" World");
System.out.println(s);
// StringBuffer allows modification and is thread-safe
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb);
// StringBuilder allows modification and is faster
StringBuilder sbuilder = new StringBuilder("Hello");
sbuilder.append(" World");
System.out.println(sbuilder);
Hello
Hello World
Hello World
The String value does not change because it is immutable. Both StringBuffer and StringBuilder modify the original object.