Concatenating Strings with Prefix with Varargs in Java


Write a Java program demonstrating a varargs method that concatenates strings and adds a prefix

It includes a method called concatenateWithPrefix, which takes a string prefix and a variable number of strings as input. This method concatenates each string in the input array with the specified prefix. It iterates through each string in the array and appends the prefix followed by the string to a StringBuilder.

The main method serves as the entry point of the program. Inside main, it calls the concatenateWithPrefix method with the prefix "*" and several strings as arguments. It stores the concatenated result in the variable concatenated.

Finally, it prints out the result using System.out.println, displaying "Concatenated with Prefix : " followed by the concatenated string.

Source Code

public class PrefixStringConcatenator
{
	static String concatenateWithPrefix(String prefix, String... strings)
	{
		StringBuilder result = new StringBuilder();
		for (String str : strings)
		{
			result.append(prefix).append(str);
		}
		return result.toString();
	}
 
	public static void main(String[] args)
	{
		String concatenated = concatenateWithPrefix("*", "One", "Two", "Three");
		System.out.println("Concatenated with Prefix : " + concatenated);
	}
}

Output

Concatenated with Prefix : *One*Two*Three

Example Programs