Home > DeveloperSection > Blogs > Reverse the string using recursion in java

Reverse the string using recursion in java


Java Java 
Ratings:
0 Comment(s)
 1464  View(s)
Rate this:

Reverse the string using recursion in java

In this blog I am provide you the code for Reverse the string using recursion in java.

import java.io.*;

import java.util.Scanner;

public class RecursionReverse

{

    public static void main(String[] args)

    {

                String val=null;

                Scanner in = new Scanner(System.in);

                System.out.print("Enter String : ");

                val=in.nextLine();    

                Reverser r = new Reverser(val);

        System.out.println(r.reverse());

    }

}

class Reverser

{

    char _arr[];

    int _pos;

    StringBuilder _buf;

    public Reverser(String str)

    {

        setString(str);

        init();

    }

    public String reverse()

    {

        init();

        return (doReverse().toString());

    }

    private StringBuilder doReverse()

    {

        int pos = _pos;

        if (pos == _arr.length - 1)

        {

            return (_buf.append(_arr[pos]));

        }

        else

        {

            ++_pos;

            return (doReverse().append(_arr[pos]));

        }

    }

    public void setString(String str)

    {

        _arr = str.toCharArray();

    }

    public String getString()

    {

        return (new String(_arr));

    }

    private void init()

    {

        _pos = 0;

        _buf = new StringBuilder(_arr.length);

    }

}

Output:-


Don't want to miss updates? Please click the below button!

Follow MindStick