The function takes the first character of a String - str.charAt(0) - puts it at the end and then calls itself - reverse() - on the remainder - str.substring(1), adding these two things together to get its result - reverse(str.substring(1)) + str.charAt(0)

When the passed in String is one character or less and so there will be no remainder left - when str.length() <= 1) - it stops calling itself recursively and just returns the String passed in.

So it runs as follows:

reverse("Hello")
(reverse("ello")) + "H"
((reverse("llo")) + "e") + "H"
(((reverse("lo")) + "l") + "e") + "H"
((((reverse("o")) + "l") + "l") + "e") + "H"
(((("o") + "l") + "l") + "e") + "H"
"olleH"
Answer from David Webb on Stack Overflow
Top answer
1 of 16
104

The function takes the first character of a String - str.charAt(0) - puts it at the end and then calls itself - reverse() - on the remainder - str.substring(1), adding these two things together to get its result - reverse(str.substring(1)) + str.charAt(0)

When the passed in String is one character or less and so there will be no remainder left - when str.length() <= 1) - it stops calling itself recursively and just returns the String passed in.

So it runs as follows:

reverse("Hello")
(reverse("ello")) + "H"
((reverse("llo")) + "e") + "H"
(((reverse("lo")) + "l") + "e") + "H"
((((reverse("o")) + "l") + "l") + "e") + "H"
(((("o") + "l") + "l") + "e") + "H"
"olleH"
2 of 16
20

You need to remember that you won't have just one call - you'll have nested calls. So when the "most highly nested" call returns immediately (when it finds just "o"), the next level up will take str.charAt(0) - where str is "lo" at that point. So that will return "ol".

Then the next level will receive "ol", execute str.charAt(0) for its value of str (which is "llo"), returning "oll" to the next level out.

Then the next level will receive the "oll" from its recursive call, execute str.charAt(0) for its value of str (which is "ello"), returning "olle" to the next level out.

Then the final level will receive the "oll" from its recursive call, execute str.charAt(0) for its value of str (which is "hello"), returning "olleh" to the original caller.

It may make sense to think of the stack as you go:

// Most deeply nested call first...
reverse("o") -> returns "o"
reverse("lo") -> adds 'l', returns "ol" 
reverse("llo") -> adds 'l', returns "oll" 
reverse("ello") -> adds 'e', returns "olle" 
reverse("hello") -> adds 'h', returns "olleh" 
🌐
BeginnersBook
beginnersbook.com › 2017 › 09 › java-program-to-reverse-a-string-using-recursion
Java Program to Reverse a String using Recursion
September 8, 2017 - import java.util.Scanner; public class JavaExample { public static void main(String[] args) { String str; System.out.println("Enter your username: "); Scanner scanner = new Scanner(System.in); str = scanner.nextLine(); scanner.close(); String reversed = reverseString(str); System.out.println("The reversed string is: " + reversed); } public static String reverseString(String str) { if (str.isEmpty()) return str; //Calling Function Recursively return reverseString(str.substring(1)) + str.charAt(0); } }
Discussions

recursion - Whats the best way to recursively reverse a string in Java? - Stack Overflow
Basically use recursion in situations where you definitely need it. 2014-12-31T19:46:46.107Z+00:00 ... If you're going to do this, you want to operate on a character array, because a String is immutable and you're going to be copying Strings all over the place if you do it that way. This is untested and totally stream of consciousness. It probably has an OB1 somewhere. And very not-Java. public String reverseString... More on stackoverflow.com
🌐 stackoverflow.com
Explanation for how this recursive method to reverse a string works (JAVA)
Try walking through it on paper. Here's an algorithm to follow: Reverse: input is "str". If str is blank, return blank. separate str into the first character, car, and the remaining characters, cdr. Invoke this algorithm with an input of cdr, label result "reversedCdr". Return reversedCdr + car. If you do this by hand, you'll see what's happening. Make sure to carefully track the stack. Here's an example. Reverse(str is "nab") str isn't blank, keep going car is "n", cdr is "ab". Call reverse(str is "ab") str isn't blank, keep going car is "a", cdr is "b" Call reverse(str is "a") str isn't blank, keep going car is "b", cdr is "" Call reverse(str is "") str is blank, return blank. Return "" + "b", "b" Return "b" + "a", "ba" Return "ba" + "n", "ban" More on reddit.com
🌐 r/learnprogramming
3
5
February 21, 2021
Trying to reverse a string using recursion, why is my program not working?
If you are trying to do recursion then you want to have a return. Each step in the recursive process should do one unit of work. After the one unit of work is done, it should examine the data to see if it's done. If it is done, return. If it isn't done recurse. Here's an example in PHP: public function reverseString($input) { // Get the last character in the list/array/string $last_char = $input[strlen($input) - 1]; // Compute the remaining list/array/string $new_input = substr($input, 0, -1); // If the new list/array/string is empty, we are done so we return our result // Else return our result concatenated with the next result if (strlen($new_input) == 0) { return $last_char; } else { return $last_char . $this->reverseString($new_input); } } More on reddit.com
🌐 r/AskComputerScience
17
16
February 28, 2020
Reverse a sentence using recursion
It works to reverse the sentence, because of the order of two inner lines of reverseSentence().eg, if printf was called before recursing, then the sentence would print out in-order. Because the order is to recurse first, then printf, the first character captured is the last to be printed to the screen. More on reddit.com
🌐 r/C_Programming
6
2
September 26, 2022
🌐
Reddit
reddit.com › r/learnprogramming › explanation for how this recursive method to reverse a string works (java)
r/learnprogramming on Reddit: Explanation for how this recursive method to reverse a string works (JAVA)
February 21, 2021 -
public String reverse(String str) {
    if(str.length()==0){
        return str;
    }
    else{
        return reverse(str.substring(1))+str.charAt(0);
    }
}

I was wondering how recursive methods work. What causes this method continue to plug itself back into the function? When does str.length==0 and why does it end up returning a reversed string rather than a blank in my main method.

🌐
TutorialsPoint
tutorialspoint.com › article › java-program-to-reverse-a-string-using-recursion
Java program to reverse a string using recursion
After each recursive call, concatenate the first character of str.charAt() to the result returned by the recursive function. In the main method, initialize an object of StringReverse and call reverseString with a sample string. Print the result to display the reversed string on the console. Below is the Java program to reverse a string using recursion -
🌐
Blogger
javarevisited.blogspot.com › 2012 › 01 › how-to-reverse-string-in-java-using.html
How to Reverse String in Java Using Iteration and Recursion - Example
How to reverse String in Java is a popular core java interview question and asked on all levels from junior to senior java programming jobs. since Java has rich API most java programmer answer this question by using StringBuffer reverse() method which easily reverses a String in Java and its right way if you are programming in Java but the most interview doesn't stop there and they ask the interviewee to reverse String in Java without using StringBuffer or they will ask you to write an iterative reverse function which reverses string in Java. In this tutorial, we will see how to reverse a string in a both iterative and recursive fashion.
🌐
How to do in Java
howtodoinjava.com › home › string › reverse all characters of a string in java
Reverse All Characters of a String in Java
January 10, 2023 - Perform the above operation, recursively, until the string ends · public class ReverseString { public static void main(String[] args) { String blogName = "How To Do In Java"; String reverseString = reverseString(blogName); Assertions.assertEquals("avaJ nI oD oT woH", reverseString); } public static String reverseString(String string) { if (string.isEmpty()) { return string; } return reverseString(string.substring(1)) + string.charAt(0); } }
🌐
Guru99
guru99.com › home › java tutorials › how to reverse a string in java using recursion
How to Reverse a String in Java using Recursion
December 30, 2023 - package com.guru99; public class ReverseString { public static void main(String[] args) { String myStr = "Guru99"; //create Method and pass and input parameter string String reversed = reverseString(myStr); System.out.println("The reversed string is: " + reversed); } //Method take string parameter and check string is empty or not public static String reverseString(String myStr) { if (myStr.isEmpty()){ System.out.println("String in now Empty"); return myStr; } //Calling Function Recursively System.out.println("String to be passed in Recursive Function: "+myStr.substring(1)); return reverseString(myStr.substring(1)) + myStr.charAt(0); } }
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › reverse-a-string-using-recursion
Print reverse of a string using recursion - GeeksforGeeks
March 6, 2025 - The idea is to begin with both corners, swap the corner characters and then make recursive call for the remaining string. ... #include <bits/stdc++.h> using namespace std; void reverse(string &str, int start, int end) { if (start >= end) return; ...
🌐
Java Training School
javatrainingschool.com › home › 2022 › august › reverse a string using recursion
Reverse a String using Recursion - Java Training School
August 25, 2022 - When there is only one letter remaining, simply append the it to the StringBuffer object and break the recursive call. Interesting Fact -> We all know the legendary Bollywood singer Kishor Kumar.
🌐
Medium
medium.com › @jasonwei_613 › java-reverse-string-recursion-f3dcaa3d90e2
Java Reverse String (Recursion). How do you use Recursion to reverse an… | by Jason Wei | Medium
May 21, 2019 - For example, in the problem if there’s a null array passed in you can’t do anything with the null array, because no matter how many times you call the helper function you’ll still get a null array. Therefore we write an if statement to set the base of recursion.
🌐
w3resource
w3resource.com › java-exercises › string › java-string-exercise-44.php
Java - Reverse a string using recursion
March 2, 2026 - // Importing necessary Java utilities. import java.util.*; // Define a class named Main. class Main { // Method to reverse a string recursively. void reverseString(String str1) { // Base case: if the string is null or has a length less than ...
🌐
Javatpoint
javatpoint.com › reverse-a-string-using-recursion-in-java
Reverse a String Using Recursion in Java - Javatpoint
Java Program to prove that strings are immutable in java · Java program to reverse a given string with preserving the position of spaces
🌐
coderolls
coderolls.com › java-reverse-string-using-recursion
How To Reverse A String In Java Using Recursion - Coderolls
December 8, 2021 - * * @author gaurav * */ public class ReverseStringUsingRecursion { public static void main(String[] args) { String str = "hello"; System.out.println(reverse(str)); } public static String reverse(String str) { if ((null == str) || (str.length() <= 1)) { return str; } return reverse(str.substring(1)) + str.charAt(0); } } ... The example java program given in the above tutorial can be found at this GitHub Gist. Please write you thoughts in the comment section below. PREVIOUSFor-each loop in Java or Enhanced For loop in Java
🌐
Programiz
programiz.com › java-programming › examples › reverse-sentence
Java Program to Reverse a Sentence Using Recursion
public class Reverse { public static void main(String[] args) { String sentence = "Go work"; String reversed = reverse(sentence); System.out.println("The reversed sentence is: " + reversed); } public static String reverse(String sentence) { if (sentence.isEmpty()) return sentence; return reverse(sentence.substring(1)) + sentence.charAt(0); } } ... In the above program, we've a recursive function reverse()....
🌐
w3resource
w3resource.com › java-exercises › recursive › java-recursive-exercise-6.php
Java Recursive Method: Reverse a given string
Write a Java program to recursively reverse a string by swapping its first and last characters until the string is fully reversed.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Reverse A String Using Recursion - Java Code Geeks
June 30, 2020 - 1. Introduction In this article, You're going to learn how to reverse a string using recursion approach. The first program is to reverse a string and the
🌐
Vultr Docs
docs.vultr.com › java › examples › reverse-a-sentence-using-recursion
Java Program to Reverse a Sentence Using Recursion | Vultr Docs
December 2, 2024 - For a sentence, the base case is when the length of the sentence is 0 or 1. Recursive Case: This involves calling the recursive function with a smaller part of the sentence, gradually reducing its size towards the base case.
🌐
Quora
quora.com › How-can-I-write-a-program-in-Java-to-reverse-a-string-using-recursion
How to write a program in Java to reverse a string using recursion - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
🌐
YouTube
youtube.com › watch
Java Program to Reverse a String using Recursion - YouTube
Write a java program to reverse a string using recursion. In this tutorial, We are going to write a java code to reverse an input string using recursion.http...
Published   August 19, 2018