A recursive approach to reversing a string in Java

Assume, you enter a string “There goes Tom Dickson” and you want an output as “Dickson Tom goes There”. To achieve this there are a variety of ways, but the most elegant approach is writing a recursive method to do this.
Here is a program in Java that does just the same.
It uses the ArrayList from Collections class and StringBuilder from String class.

package String;
import java.util.Scanner;
import java.util.ArrayList;
public class Reverser
{
 public static void main(String args[])
 {
 Scanner input=new Scanner(System.in);
 System.out.println("Enter a line of text: ");
 String myString=input.nextLine();
 ArrayList alist = new ArrayList();
 alist = recursiveMethod(myString,alist);
 alist.trimToSize();
 StringBuilder sb = new StringBuilder();
 for(int i = alist.size()-1; i>=0;i--)
 {
 sb.append(alist.get(i)+" ");
 }
 System.out.println(sb);
}
 public static ArrayList recursiveMethod(String myName,ArrayList al)
 {
 int index = myName.indexOf(" ");
 al.add(myName.substring(0, index));
 myName = myName.substring(index+1);
 if(myName.indexOf(" ")==-1)
 {
 al.add(myName.substring(0));
 return al;
 }
 return recursiveMethod(myName,al);

 }
}
Advertisements