Concatenate Strings Varargs Delimiter in Java


Write a Java program using a method with varargs that concatenates a set of strings with a specified delimiter

  • The StringConcatenator class contains a static method named concatenateStrings that takes a delimiter and a variable number of strings (String... strings) as arguments.
  • Inside the method, it prints the given strings using Arrays.toString() to display the array contents.
  • It initializes a StringBuilder named result to build the concatenated string.
  • It then iterates through each string in the strings array.
  • For each string, it appends it to the result.
  • If it's not the last string, it appends the specified delimiter after the string.
  • After iterating through all strings, it returns the concatenated string.
  • In the main method, the concatenateStrings method is called with a hyphen ("-") as the delimiter and several strings as arguments.
  • The concatenated string is then printed to the console.

Source Code

import java.util.Arrays;
public class StringConcatenator
{
	static String concatenateStrings(String delimiter, String... strings)
	{
		System.out.println("Given String : " + Arrays.toString(strings));
		StringBuilder result = new StringBuilder();
		for (int i = 0; i < strings.length; i++)
		{
			result.append(strings[i]);
			if (i < strings.length - 1)
			{
				result.append(delimiter);
			}
		}
		return result.toString();
	}
 
	public static void main(String[] args)
	{
		String concatenatedString = concatenateStrings("-", "Pink", "Blue", "White", "Red", "Black", "Green", "Yellow");
		System.out.println("Concatenated String : " + concatenatedString);
	}
}

Output

Given String : [Pink, Blue, White, Red, Black, Green, Yellow]
Concatenated String : Pink-Blue-White-Red-Black-Green-Yellow

Example Programs