Java Program to Display a String in Reverse Order Without Using Loop or Another Array

In this post, we will see a java program to reverse a string without using any loops or temporary array. Such programming questions are often asked in interviews. It is so simple. We make use of recursion to store the string temporarily. Actually, we do not use any loop. We can easily do it without using any loops. Nor we need to declare an extra array. But when we make use of recursion, stack is used internally for calling each instance of the recursive method. Remember, we should not use the reverse method in StringBuilder class or StringBuffer class. The following java program displays the string in reverse order.


import java.util.Scanner;

public class StrRev{
static int len;
static String str;

static void recurse(int i)
{
    if(i<len-1)
        recurse(i+1);
    System.out.print(str.charAt(i));
}

public static void main(String[] arg)
    {
    System.out.println("Enter string");
    Scanner sc = new Scanner(System.in);
    str=sc.nextLine();
    len=str.length();
    recurse(0);
    }
}

In the above java program we just displayed the string in reverse order. we did not reverse the string in memory. In the following java program, we will see how to rearrange the string in reverse order without using any loops or extra arrays.

import java.util.Scanner;

public class StrRev{
static int len;
static char[] str;

static void recurse(int i)
{
    char a=str[i];
    if(i<len-1)
        recurse(i+1);
    str[len-i-1]=a;
}

public static void main(String[] arg)
    {
    System.out.println("Enter string");
    Scanner sc = new Scanner(System.in);
    str=sc.nextLine().toCharArray();
    len=str.length;
    recurse(0);
    System.out.println(String.copyValueOf(str));
    }
}

In the above java program, we stored the input string initially as a character array. Using a recursive method, we rearranged the character array in reverse order. Then we displayed the character array as a string

No comments:

Post a Comment