Concatenate Strings with Varargs in Java


Create a Java program using a method with varargs to concatenate strings

  • The class StringConcatenator contains a single static method concatenateStrings that takes a variable number of strings as input (using varargs).
  • Inside the concatenateStrings method, a StringBuilder named result is created to efficiently concatenate strings.
  • The method iterates through each string in the input array strings.
  • For each string str, it appends str to the StringBuilder result.
  • After appending all strings, it converts the StringBuilder to a String using the toString method and returns the concatenated string.
  • In the main method, the concatenateStrings method is called with multiple string arguments. The concatenated string returned by concatenateStrings is printed to the console.

Source Code

public class StringConcatenator
{
	static String concatenateStrings(String... strings)
	{
		StringBuilder result = new StringBuilder();
		for (String str : strings)
		{
			result.append(str);
		}
		return result.toString();
	}
 
	public static void main(String[] args)
	{
		String concatenatedString = concatenateStrings("Welcome, ", "Tutor ", "Joe's!");
		System.out.println("Concatenated String : " + concatenatedString);
	}
}

Output

Concatenated String : Welcome, Tutor Joe's!

Example Programs