Java reverse string using recursion

In this post, we will see a Java program to reverse a string using recursion. Also learn to reverse string without recursion as well.

Read More: Reverse words in a string in Java

1. Reverse String using recursion

To reverse a string by characters, we can write a recursive function which will perform following actions –

  1. Take first character and append to last of string
  2. Perform above operation until string ends
public class StringExample 
{
	public static void main(String[] args) 
	{
		String blogName = "How To Do In Java ";
		
		String reverseString = reverseString(blogName);
		
		System.out.println(reverseString);
	}
	
	public static String reverseString(String string)
	{
		if (string.isEmpty()){
		 return string;
		}
		//Calling function recursively
		return reverseString(string.substring(1)) + string.charAt(0);
	}
}

Program output.

avaJ nI oD oT woH

2. Reverse a sentence in Java – without recursion

You can reverse a string by character easily, using a StringBuilder.reverse() method.

public class StringExample 
{
	public static void main(String[] args) 
	{
		String blogName = "How To Do In Java";

		String reverseString = new StringBuilder(string).reverse();

		System.out.println(reverseString);
	}
}

Program output.

avaJ nI oD oT woH

In this example, you learned to reverse a string using recursive function and also without using recursive function as well.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

2 thoughts on “Java reverse string using recursion”

  1. Hey!
    There is a problem with “Reverse a sentence -without recursion”.

    There are casting errors.Why don’t you give it a try?

    Reply
    • yes, there is casting error. I did it this way and it worked

      public class test
      {
      public static void main(String[] args)
      {
      String blogName = “How To Do In Java”;

      StringBuilder reverseString = new StringBuilder(blogName).reverse();

      System.out.println(reverseString);
      }
      }

      Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.