Follow @devglan
Java Program to Reverse a Given String without using Predefined Functions
Description
Write a java program to reverse a given string using recursion without using any predefined function.This program checks the understanding of recursion in programming language and also checks the programming sense.Here, the method reverseString() is called recursively to revrse a given string.Following is the complete program.
package com.devglan; public class StringReversal { String reversedString = ""; public String reverseString(String str){ if(str.length() == 1){ return str; } else { reversedString += str.charAt(str.length()-1) +reverseString(str.substring(0,str.length()-1)); return reversedString; } } public static void main(String a[]){ StringReversal reversal = new StringReversal(); System.out.println("Reversed string - " + reversal.reverseString("planet")); } }
Explanation
Click to Suggest Your Own Explanation
If the string length is 1, then return the same string.Else, extract the last character and append in an existing new string and again call the same method recursively by removing the last character which has already been appended to the new string.
Other Similar Java Programs:
If You Appreciate This, You Can Consider:
- Share this article on social media or with your teammates.