Объясните различия между String, StringBuilder и StringBuffer в Java.
sobes.tech AI
Answer from AI
In Java (although the question is in the C# module, but these classes relate to Java), there are three main types for working with strings:
-
String — an immutable object. When the string is modified, a new object is created. This is safe for multithreaded use but can be inefficient for frequent string modifications.
-
StringBuilder — a mutable class for working with strings. Allows efficient modification of content without creating new objects. Not thread-safe, but faster in single-threaded scenarios.
-
StringBuffer — similar to StringBuilder but thread-safe (synchronized). Used when safety is required when working with multiple threads, but it is slower than StringBuilder due to synchronization.
Example:
String s = "Hello";
s += " World"; // creates a new String object
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // modifies the existing object
StringBuffer sbuf = new StringBuffer("Hello");
sbuf.append(" World"); // also modifies the object, but synchronized
Conclusion: for frequent string modifications in single-threaded applications, it is better to use StringBuilder; for multithreaded applications, StringBuffer; and for immutable strings, String.