What is the best way to append strings in Java?

What is the most efficient way to append a string in Java? I wrote a Java program where I need to continuously append a string, like " u13a2", to an existing one, such as "u1234 u12de u1386 ... u15a3". However, as the string grows longer, I notice that each append operation takes more time. How can I optimize this process?

I initially used:

unicodeArray += " " + unicode;

or

unicodeArray = unicodeArray.concat(" " + unicode);

But both seem to have similar performance issues. Since Java’s String type creates a new object for each modification, would switching to another type, like a byte array, be a better approach?

I’ve worked with Java for years, and I can tell you from experience—using String for repeated modifications is inefficient. Since strings in Java are immutable, every append creates a new object, slowing things down significantly. For frequent appends, use StringBuilder. It modifies the same object instead of creating a new one each time:

StringBuilder unicodeArray = new StringBuilder("u1234 u12de u1386 ... u15a3");  
unicodeArray.append(" ").append("u13a2");  
System.out.println(unicodeArray.toString());  
// Output: u1234 u12de u1386 ... u15a3 u13a2  

:white_check_mark: Why it’s better?

  • StringBuilder is mutable, so it doesn’t create a new object for every append.
  • It’s much faster than String.concat() or += for large strings.
  • Ideal for string append java operations in performance-critical applications.

@yanisleidi-rodriguez makes a great point about StringBuilder being faster, but if you’re working in a multi-threaded environment, you’ll want to be thread-safe. That’s where StringBuffer comes in—it works just like StringBuilder but with synchronized methods, ensuring safety in concurrent scenarios:"*

StringBuffer unicodeArray = new StringBuffer("u1234 u12de u1386 ... u15a3");  
unicodeArray.append(" ").append("u13a2");  
System.out.println(unicodeArray.toString());  

:white_check_mark: When to use?

  • If multiple threads might modify the string simultaneously, StringBuffer ensures thread safety.
  • For single-threaded operations, stick with StringBuilder since it’s faster.
  • Both are excellent for string append java tasks, but choose based on your threading needs.

@joe-elmoufak raises a valid point about thread safety, but there’s another optimization trick for large-scale string operations—preallocating capacity in StringBuilder. This reduces unnecessary memory reallocations and boosts performance:"*

StringBuilder unicodeArray = new StringBuilder(1000);  // Preallocate space  
unicodeArray.append("u1234 u12de u1386 ... u15a3");  
unicodeArray.append(" ").append("u13a2");  
System.out.println(unicodeArray.toString());  

:white_check_mark: Why this helps?

  • Preallocating avoids repetitive resizing, making appends faster.
  • Particularly useful when handling large text data in loops.
  • A must-know technique for efficient string append java operations.