Search code examples
javastringconcatenationstring-concatenation

When to use String#concat() method in Java?


I've been through different topics about String concatenation performance. Almost answer recommend using StringBuilder or StringBuffer to reduce overhead cost (or + operator if concatenation statement outside the loop). It's pretty clear, but I still wonder why Java has String format() and concat() method although it's ineffective. Performance test here: link. Someone mentioned String format() may be useful for Localization purpose (I don't understand much, howsoever I already have a keyword to search later), but what's the purpose of the remaining one? Does it only useful for compatibility backward?


Solution

  • String#concat and + exist to provide a minimalistic set of operations on the type String.

    They are not efficient if used multiple times.

    But they have their own right as type operations "xxx" + "yyy" you do not want to specify using a StringBuilder. (Furthermore there it is a compile time concatenation.)

    StringBuffer is a mistake IMHO. It is slower that the newer StringBuilder as it is synchronized, but one would rarely add something rom two threads (unordered).

    String::concat may be a method reference useful for stream reduction or such.