Java Program to Reverse a Given String without using Predefined Functions

Java Program to Reverse a Given String without using Predefined Functions thumbnail
6K
By Dhiraj Ray 01 January, 2018

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

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.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.