Concatenate Characters with Varargs in Java
Create a Java program using a method with varargs to concatenate a series of characters
- The CharacterConcatenator class contains a static method named concatenateChars that takes a variable number of characters (char... chars) as arguments.
- Inside the method, it initializes a StringBuilder named result to store the concatenated characters.
- It then iterates through each character in the chars array using an enhanced for loop.
- For each character, it appends it to the result StringBuilder using the append method.
- After iterating through all characters, it converts the StringBuilder to a string using the toString method and returns the result.
- In the main method, the concatenateChars method is called with the characters 'T', 'u', 't', 'o', 'r', ' ', 'J', 'o', 'e', 's'.
- The concatenated characters are printed to the console. In this case, it prints "Concatenated Characters : Tutor Joes".
Source Code
public class CharacterConcatenator
{
static String concatenateChars(char... chars)
{
StringBuilder result = new StringBuilder();
for (char c : chars)
{
result.append(c);
}
return result.toString();
}
public static void main(String[] args)
{
String concatenatedChars = concatenateChars('T', 'u', 't', 'o', 'r', ' ', 'J', 'o', 'e', 's');
System.out.println("Concatenated Characters : " + concatenatedChars);
}
}
Output
Concatenated Characters : Tutor Joes