Concatenating Strings using Varargs in Java


Write a Java program to demonstrate a method with varargs that concatenates a specific string with a variable number of strings

  • The StringAppender class has a static method appendString that takes two parameters: a base string (base) and a variable number of strings (strings).
  • Inside the method, a StringBuilder named result is created with the initial value set to the base string.
  • Using a for-each loop, each string in the strings array is appended to the result StringBuilder.
  • Finally, the result StringBuilder is converted to a string using the toString method and returned.
  • In the main method, the appendString method is called with a base string "Hello, " and additional strings "Java", "Programmers", and "World!". The concatenated string is then printed to the console.

Source Code

public class StringAppender
{
	static String appendString(String base, String... strings)
	{
		StringBuilder result = new StringBuilder(base);
		for (String str : strings)
		{
			result.append(str);
		}
		return result.toString();
	}
 
	public static void main(String[] args)
	{
		String finalString = appendString("Hello, ", "Java ", "Programmers ", "World!");
		System.out.println("Concatenated String : " + finalString);
	}
}

Output

Concatenated String : Hello, Java Programmers World!

Example Programs