In this Java program, you’ll learn how to Reverse a Sentence Using Recursion using the Java programming language.
How to Reverse a Sentence Using Recursion?
Example 1: Using Recursion
RUN CODE SNIPPETpublic class Main { public static void main(String[] args) { String sentence = "HELLO EVERYONE"; 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); } }
OUTPUT
The reversed sentence is: ENOYREVE OLLEH
In the above program we have used recursion function. We add the result of next reverse function to the first character of the sentence using charAt(), at each iteration.
In the end the reverse() returns the reversed sentence.