Junior — Middle
How can an efficient mechanism for sequential string assembly in Java be created?
sobes.tech AI
Answer from AI
In Java, for efficient sequential string concatenation, it is recommended to use the StringBuilder class. Unlike string concatenation using the + operator, which creates new string objects with each operation, StringBuilder accumulates changes in a single object, significantly improving performance when performing many operations.
Example usage:
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(", ");
sb.append("world!");
String result = sb.toString();
System.out.println(result); // Outputs: Hello, world!
If a thread-safe version is required, you can use StringBuffer, but in most cases, StringBuilder is preferred due to better performance.