Saturday, January 21, 2012

Quick way to join array of String in Java without third party libraries

As you probably know Java SE doesn't include such useful method as String join. Even old good JavaScript has this nice method:
JavaScript join() Method
Definition and Usage
The join() method joins all elements of an array into a string, and returns the string. The elements will be separated by a specified separator. The default separator is comma (,).
How to implement the similar stuff in Java SE? The easiest what came to my head is:
  * Join String arguments into one String separated by comma (",")
  * @param args input Strings
  * @return joined String
 public static String join(String... args) {
  if(args.length <1) throw new IllegalArgumentException();
  String joined = Arrays.toString(args);
  String result = joined.substring(1, joined.length()-1);
  return result;
Usage is pretty trivial:
import static com.blogspot.HalypHUtils.join;


String joinedString = join("Banana", "Orange", "Apple", "Mango");
And as you've already noticed this join uses comma (",") separator only.


  1. Looks good,
    if this behavior of Array.toString is the same in different JVM implementations.

  2. Yes, you are right, but I've mentioned on top of the post "How to implement the similar stuff in Java SE?" ;-) So, this was tested on Sun/Oracle Java SE.

  3. A very good post on joining array of String in Java, This is useful for beginners. Here is an another blog which contain quality content about join() method in java thread at, hope this information will help java beginners to learn more about join() method in detail. While learning from this blog developers can also post & view java questions and answers to enhance their knowledge & skills.