In this post I am sharing different ways of achieving string concatenation with sample (JAVA) code:
1) Using Plus (+) operator (suitable for constants but should be avoided in loops)
2) Using StringBuilder (not thread safe)
3) Using StringBuffer (thread safe)
4) Using concat method (returns a string object and so allows to chain the calls to append further Strings)
5) Using format method (allows to inject a variety of Java Objects into a String template)
6) Using Join (Available in Java8+ and suitable for strings with a common delimiter)
7) using StringJoiner (Available in Java 8+ and it can be used for joining Strings making use of a delimiter, prefix, and suffix)
8) Collectors.joining (Available in Java 8+ and allows us to funnel the output of a Stream into a single String)
9) Arrays.toString (Not customisable and outputs a String with square brackets)
1) Using Plus (+) operator (suitable for constants but should be avoided in loops)
2) Using StringBuilder (not thread safe)
3) Using StringBuffer (thread safe)
4) Using concat method (returns a string object and so allows to chain the calls to append further Strings)
5) Using format method (allows to inject a variety of Java Objects into a String template)
6) Using Join (Available in Java8+ and suitable for strings with a common delimiter)
7) using StringJoiner (Available in Java 8+ and it can be used for joining Strings making use of a delimiter, prefix, and suffix)
8) Collectors.joining (Available in Java 8+ and allows us to funnel the output of a Stream into a single String)
9) Arrays.toString (Not customisable and outputs a String with square brackets)