English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input Output (I/O)

Java Reader/Writer

Java other topics

Java program uses recursion to reverse a sentence

Java Examples Comprehensive

In this program, you will learn to use recursion in Java to reverse the given sentence.

Example: Using recursion to reverse a sentence

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);
    }
}

When running the program, the output is:

The reversed sentence is: krow oG

In the above program, we have a recursive function reverse().

In each iteration, we use charAt(0) to add (concatenate) the result of the next reverse() function to the first character of the sentence.

Recursive calls must be made before charAt(), because in this way the last character will start to be added to the left. If you reverse the order, you will get the original sentence.

Finally, we end with an empty sentence, and reverse() returns the reversed sentence.

Execution Steps
Iterationreverse()substring()reversedString
1reverse("Go work")"o Work"result + "G"
2reverse("o Work")" Work"result + "o" + "G"
3reverse(" Work")"Work"result + " " + "o" + "G"
4reverse("Work")"ork"result + "W" + " " + "o" + "G"
5reverse("ork")"rk"result + "o" + "W" + " " + "o" + "G"
6reverse("rk")"k"result + "r" + "o" + "W" + " " + "o" + "G"
7reverse("k")""result + "k" + "r" + "o" + "W" + " " + "o" + "G"
Finalreverse("")-"" + "k" + "r" + "o" + "W" + " " + "o" + "G" = "kroW oG"

Java Examples Comprehensive