Junior — Middle
What is the StringBuffer class used for in programming?
sobes.tech AI
Answer from AI
In Java, the StringBuffer class is used for creating and modifying strings when a mutable sequence of characters is needed. Unlike the String class, whose objects are immutable, StringBuffer allows changing the content without creating new objects.
Main features of StringBuffer:
- Thread-safe (synchronized), making it suitable for multi-threaded environments.
- Allows efficient appending, inserting, deleting, and modifying characters in the string.
Example of usage:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" world");
System.out.println(sb.toString()); // Outputs: Hello world
If thread safety is not required, for better performance, StringBuilder can be used.