Java String Reverse Program using Recursion

Write a Java string reverse program using recursion or recursive functions. In this example, the user-defined method checks whether the string is empty, and if it’s true, it prints the exact same or empty space. Otherwise, it performs the string reverse recursively.

On each iteration (recursive call), we perform string concatenation. Here, charAt(0) adds the last character in a string to the first position. 

TIP: Please refer to the Java Reverse a String article.

package RemainingSimplePrograms;

import java.util.Scanner;

public class StringReverseRecur1 {
	
	private static Scanner sc;
	
	public static void main(String[] args) {

		sc= new Scanner(System.in);
		
		System.out.print("Please Enter String to Reverse =  ");
		String str = sc.nextLine();
		
		String revString = stringReverse(str);	
		System.out.println("The reversed String =  " + revString);
	}
	
	public static String stringReverse(String str)
	{
		if(str.isEmpty())
			return str;
		
		return stringReverse(str.substring(1)) + str.charAt(0);
	}
}
String Reverse Program using Recursion

It is another way of writing string reverse programs in using recursion. For more, please refer to the Java programs page.

package RemainingSimplePrograms;

import java.util.Scanner;

public class Example2 {
	
	private static Scanner sc;
	
	public static void main(String[] args) {

		sc= new Scanner(System.in);
		
		System.out.print("Please Enter =  ");
		String str = sc.nextLine();
		
		System.out.print("The Result =  " );
		strRev(str);	
	}
	
	public static void strRev(String str)
	{
		if(str.isEmpty()) {
			System.out.print(str);
		}
		else {
			System.out.print(str.charAt(str.length() - 1));
			strRev(str.substring(0, str.length() - 1));
		}	
	}
}
Please Enter =  Welcome to Java World!
The Result =  !dlroW avaJ ot emocleW

This program moves the last character to the front and recursively calls itself on the remaining characters and perform string reverse.

public class example {
public static String stringRev(String s, int len)
{
if (len < 1)
return "";
if (len == 1)
return String.valueOf(s.charAt(0));
return s.charAt(len - 1) + stringRev(s, len - 1);
}

public static void main(String[] args) {
String s = "Rare Information";
System.out.println(stringRev(s, s.length()));
}
}
noitamrofnI eraR

Also Visit