Java Program to Reverse a Sentence Using Recursion

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 SNIPPET
public 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. 

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024