String and StringBuffer are both used to store and manipulate character data in Java. The key difference is that String objects are immutable, meaning their value cannot be changed after creation, whereas StringBuffer objects are mutable, allowing their content to be modified without creating new objects.
Key Points: • String is immutable; any modification creates a new object. • StringBuffer is mutable and allows changes to the same object. • StringBuffer is thread-safe because its methods are synchronized. • String is preferred for fixed text that does not change frequently. • StringBuffer is suitable for applications that perform frequent string modifications in a multithreaded environment. • String generally offers better readability, while StringBuffer provides better performance for repeated modifications.
Example: When building a large text message by repeatedly appending values, using String creates multiple objects, whereas StringBuffer updates the same object, making it more efficient.
Code Example:
public class Demo {
public static void main(String[] args) {
String str = "Java";
str = str + " Programming";
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
System.out.println(str);
System.out.println(sb);
}
}Difference Between String and StringBuffer:
String: • Immutable • Creates a new object on modification • Not synchronized • Suitable for read-only data • Better for constant values
StringBuffer: • Mutable • Modifies the same object • Synchronized and thread-safe • Suitable for frequent modifications • Better in multithreaded environments
Interview Tip: A concise interview answer is:
"String is immutable, so any modification creates a new object. StringBuffer is mutable and allows changes to the same object. Additionally, StringBuffer is thread-safe because its methods are synchronized, making it a better choice for frequent string modifications in multithreaded applications."