Concatenate Strings in Reverse with Varargs in Java


Create a Java program using a method with varargs to concatenate a set of strings in reverse order

  • The ReverseStringConcatenator class contains a static method named concatenateReverse that concatenates the given strings in reverse order.
  • Inside the method, it first prints the given strings using Arrays.toString() method.
  • It initializes a StringBuilder named result to store the concatenated reversed string.
  • Then, it iterates through the strings array in reverse order using a for loop starting from strings.length - 1 down to 0.
  • Within the loop, it appends each string to the result StringBuilder.
  • After the loop, it returns the concatenated reversed string by converting the StringBuilder to a string using toString() method.
  • In the main method, the concatenateReverse method is called with the strings "Red", "Blue", and "Green".
  • The concatenated reversed string is then printed to the console.

Source Code

import java.util.Arrays;
public class ReverseStringConcatenator
{
	static String concatenateReverse(String... strings)
	{
		System.out.println("Given String : " + Arrays.toString(strings));
		StringBuilder result = new StringBuilder();
		for (int i = strings.length - 1; i >= 0; i--)
		{
			result.append(strings[i]);
		}
		return result.toString();
	}
 
	public static void main(String[] args)
	{
		String reversedString = concatenateReverse("Red", "Blue", "Green");
		System.out.println("Reversed Concatenated String : " + reversedString);
	}
}

Output

Given String : [Red, Blue, Green]
Reversed Concatenated String : GreenBlueRed

Example Programs