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
🌐
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()....
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" 
Discussions

java - Program to reverse the words in a string - Stack Overflow
I have written a program to reverse the words in a string. if i/p is "The dog is chasing" then o/p should be "chasing is dog The" public class String_reverse { public static void main(String[... More on stackoverflow.com
🌐 stackoverflow.com
java - Using recursion to reverse a phrase - Stack Overflow
I have an assignment that asks me to create a Java program that reverses an input phrase using recursion and outputs it. For example, given an input "DATA STRUCTURES AND ALGORITHMS" the program would More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
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
string - Reverse the words in Java with recursively - Stack Overflow
In that case, we can replace the for loop with a recursive call with an exit condition which checks the length of the original string and returns it when length == 0 I guess there are other correct answers already here. thank you 2020-04-09T05:25:13.783Z+00:00 ... public static String reverseString... More on stackoverflow.com
🌐 stackoverflow.com
🌐
BeginnersBook
beginnersbook.com › 2017 › 09 › java-program-to-reverse-a-string-using-recursion
Java Program to Reverse a String using Recursion
September 8, 2017 - public class JavaExample { public static void main(String[] args) { String str = "Welcome to Beginnersbook"; String reversed = reverseString(str); System.out.println("The reversed string is: " + reversed); } public static String reverseString(String str) { if (str.isEmpty()) return str; //Calling ...
🌐
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 ...
Top answer
1 of 4
2

Recursive method, using same logic as linked "duplicate", without use of split():

private static String reverseWords(String text) {
    int idx = text.indexOf(' ');
    return (idx == -1 ? text : reverseWords(text.substring(idx + 1)) + ' ' + text.substring(0, idx));
}

The logic is:

  1. Take first char/word
  2. If that is last char/word, return with it
  3. Perform recursive call with remaining text (excluding word-separating space).
  4. Append space (if doing word)
  5. Append first char/word from step 1
  6. Return result

As you can see, when applied to reversing text (characters) instead of words, it's very similar:

private static String reverseText(String text) {
    return (text.length() <= 1 ? text : reverseText(text.substring(1)) + text.charAt(0));
}

For people who like things spelled out, and dislike the ternary operator, here are the long versions, with extra braces and support for null values:

private static String reverseWords(String text) {
    if (text == null) {
        return null;
    }
    int idx = text.indexOf(' ');
    if (idx == -1) {
        return text;
    }
    return reverseWords(text.substring(idx + 1)) + ' ' + text.substring(0, idx);
}
private static String reverseText(String text) {
    if (text == null || text.length() <= 1) {
        return text;
    }
    return reverseText(text.substring(1)) + text.charAt(0);
}

Notice how the long version of reverseText() is exactly like the version in the linked duplicate.

2 of 4
1

Recursive methods could seem a bit hard when beginning but try to do the following :

  • Simplify the problem as much as possible to find yourself with the less complicated case to solve. (Here for example, you could use a sentence with two words).

  • Begin with doing it on a paper, use Pseudocode to help you dealing with the problem with the simplest language possible.

  • Begin to code and do not forget an escape to your recursion.


Solution

public static void main(String[] args) {
    String s = reverseSentence("This sentence will be reversed - I swear".split(" "));
    System.out.println(s);
}

public static String reverseSentence(String[] sentence){
    if (sentence.length <= 1){
        return sentence[0];
    }
    String[] newArray = new String[sentence.length-1];
    for (int i = 0 ; i < newArray.length ; i++){
        newArray[i] = sentence[i];
    }
    return sentence[sentence.length-1] + " " + reverseSentence(newArray);
}
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-reverse-a-sentence-using-recursion
Java Program to Reverse a Sentence Using Recursion - GeeksforGeeks
July 23, 2025 - // Java Program to Reverse a Sentence Using Recursion import java.io.*; public class GFG { public static String reverse_sentence(String str) { // check if str is empty if (str.isEmpty()) // return the string return str; else { // extract the character at 0th index, that is // the character at beginning char ch = str.charAt(0); // append character extracted at the end // and pass the remaining string to the function return reverse_sentence(str.substring(1)) + ch; } } public static void main(String[] args) { // specify the string to reverse String str = "Geeksforgeeks"; // call the method to rev
🌐
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 - Define the method reverseSentence that takes the sentence to be reversed. Use .indexOf(' ') to find the first space (word boundary). Recursively handle the rest of the sentence, moving the first word found to the end until no spaces are left.
Find elsewhere
🌐
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
String str = "India is Great becuase Great is India"; public String reverseWords(String str) { String arr[]=str.split(" "); StringBuilder stb=new StringBuilder(); for(int i=arr.length-1;i>=0;i--) stb.append(arr[i]+" "); return stb.toString(); } Chandraprakash Sarathe --------------------------- http://javaved.blogspot.com/ ... Javin @ spring interview questions answers said... @Chandraprakash, indeed reversing words on String is also good interview question and can be asked in conjunction with reversing string using recursion.
🌐
Javatpoint
javatpoint.com › reverse-a-string-using-recursion-in-java
Reverse a String Using Recursion in Java - Javatpoint
Reverse a String Using Recursion in Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
W3Schools
w3schools.in › java › examples › reverse-a-sentence-using-recursion
Java Program to Reverse a Sentence Using Recursion
This Java example code demonstrates a simple Java program to reverse a sentence using recursion and print the output to the screen.
🌐
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 - In this case is to reverse the items in the given character array using recursion. No return is necessary, just modify the array. For me the first step of solving something with recursion is to define the possible cases that we’ll encounter.
🌐
w3resource
w3resource.com › java-exercises › recursive › java-recursive-exercise-6.php
Java Recursive Method: Reverse a given string
Learn how to write a recursive method in Java to reverse a given string. Understand the concept of string reverse and implement a recursive algorithm to perform the operation.
🌐
javathinking
javathinking.com › blog › reversing-a-string-with-recursion-in-java
Reversing a String with Recursion in Java: How It Works (Step-by-Step Explanation) — javathinking.com
Recursive call: return 'e' + reverseString("h"). ... Length = 1 (base case). Return "h". Now, we “unwind” the calls by combining results: ... Final Result: "olleh" (the reversed string).
🌐
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); } }
🌐
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.

🌐
Java Code Geeks
javacodegeeks.com › home › core java
Reverse A String Using Recursion - Java Code Geeks
June 30, 2020 - 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 second program will read the input from the user. In the previous articles, I have shown already how to reverse a string without using any built-in function and also how to reverse the words in a string.
🌐
TutorialsPoint
tutorialspoint.com › Java-program-to-reverse-a-string-using-recursion
Java program to reverse a string using recursion
June 5, 2025 - 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.
🌐
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 ... 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); } }...