Junior — Middle
Explain what the StringBuffer class is and how it is used in Java for working with strings.
sobes.tech AI
Answer from AI
The StringBuffer class in Java is used for creating and modifying mutable strings. Unlike the String class, whose objects are immutable, StringBuffer allows changing the contents of the string without creating new objects, which improves performance during frequent string modifications.
Main features of StringBuffer:
- Mutability: you can add, delete, insert characters and substrings.
- Thread safety: methods are synchronized, making
StringBuffersafe for use in multithreaded environments.
Example of usage:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" world"); // Adds a string
System.out.println(sb.toString()); // Will output: Hello world
sb.insert(6, "Java "); // Inserts "Java " at position 6
System.out.println(sb.toString()); // Will output: Hello Java world