Sobes.tech
Junior

Что такое String, StringBuilder и StringBuffer в Java?

sobes.tech AI

Answer from AI

String is an immutable class. Any operation that modifies a String actually creates a new String object. Suitable for strings that will not change often.

StringBuilder and StringBuffer are mutable classes. They allow efficient modification of strings without creating new objects for each change operation.

Key differences:

Feature String StringBuilder StringBuffer
Mutability Immutable Mutable Mutable
Thread safety Thread-safe (due to immutability) Not thread-safe Thread-safe (methods are synchronized)
Performance Slower for frequent modifications Faster for frequent modifications (in single-threaded environment) Slower than StringBuilder due to synchronization

Example:

// String - new objects are created during concatenation
String s1 = "Hello";
s1 = s1 + " World"; // Creates a new object "Hello World"

// StringBuilder - modifies the same object
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies the existing StringBuilder object

// StringBuffer - similar to StringBuilder but with synchronization
StringBuffer sbf = new StringBuffer("Hello");
sbf.append(" World"); // Modifies the existing StringBuffer object

The choice between them depends on the requirements for mutability and thread safety in a specific situation. For single-threaded applications where frequent string modifications are needed, StringBuilder is usually preferred due to better performance. In multi-threaded applications where multiple threads may modify a string simultaneously, StringBuffer is used to ensure thread safety. String is used when the string does not require modifications after creation.