Java program to reverse a sentence using recursion
httpww//:sw.theitroad.com
Here's an example Java program that reverses a sentence using recursion:
public class ReverseSentence { public static void main(String[] args) { String sentence = "The quick brown fox jumps over the lazy dog."; System.out.println("Original sentence: " + sentence); System.out.println("Reversed sentence: " + reverseSentence(sentence)); } public static String reverseSentence(String sentence) { if (sentence.isEmpty()) { return sentence; } return reverseSentence(sentence.substring(1)) + sentence.charAt(0); } }
This program defines a reverseSentence()
method that takes a string as input and recursively reverses it by reversing the substring that excludes the first character and appending the first character to the end of the resulting substring. This process is repeated until the input string becomes empty.
The main()
method initializes a variable sentence
with the original sentence to be reversed and prints both the original and reversed sentences to the console by calling the reverseSentence()
method.
The output of this program would be:
Original sentence: The quick brown fox jumps over the lazy dog. Reversed sentence: .god yzal eht revo spmuj xof nworb kciuq ehT