Wednesday, September 20, 2023

How to Reverse String in Java Using Iteration and Recursion - Example

How to reverse String in Java is a popular core java interview question and asked on all levels from junior to senior java programming jobs. since Java has rich API most java programmer answer this question by using StringBuffer reverse() method which easily reverses a String in Java and its right way if you are programming in Java but the most interview doesn't stop there and they ask the interviewee to reverse String in Java without using StringBuffer or they will ask you to write an iterative reverse function which reverses string in Java.


In this tutorial, we will see how to reverse a string in a both iterative and recursive fashion. This example will help you to prepare better for using recursion in java which is often a weak area of Java programmer and exposed during a programming interview.

Also, basic knowledge of essential data structure is also very important and that's why I suggest all Java programmers join hands-on data structure and algorithms courses to fill the gaps in your understanding.



Reverse String in Java using Iteration and Recursion

How to reverse Java String using Iteration and Recursionif you are from a C background and new to Java then you get surprised that java Strings are not character arrays instead they are objects and Strings in Java are not null-terminated but still, you can use your C skill to write an iterative reverse function for a string by getting character array by calling String.toCharArray() and getting the length of String by calling String.length()

Now if you succeed in writing the String reverse function, an iterative version without using StringBuffer reverse then they finally ask you to write a recursive one. Since recursion is a tricky concept and not many Java developers think recursive as compared to C++ dudes, you may see many Java programmers stuck here by doing doodling around subString, indexOf, etc. 

So it's better to prepare in advance. here I have given an example of reversing string using StringBuffer, iterative version of String reversal, and reversing a string in Java using recursion

As I said the recursive solution is always tricky to come up you need to found a suitable base case and then repetitive call recursive method with each call reducing the length of the argument. anyway, my way is just one way of reversing string using recursion, there are many solutions out there. so don’t forget to try out yourself.




String Reverse Example using Iteration and Recursion in Java

Here is a code example String reverse using an iterative and recursive functions written in Java. The recursive solution is just for demonstrative and education purposes, don’t use the recursive solution in production code as it may result in StackOverFlowError if String to be reversed is very long String or if you have any bug in your reverse function.

Anyway it's good test to make yourself comfortable with recursive functions in java.

import java.io.FileNotFoundException;
import java.io.IOException;

/**
*
*@author Javin
/
public class StringReverseExample {

    public static void main(String args[]) throws FileNotFoundException, IOException {

        //original string
        String str = "Sony is going to introduce Internet TV soon";
        System.out.println("Original String: " + str);

        //reversed string using Stringbuffer
        String reverseStr = new StringBuffer(str).reverse().toString();
        System.out.println("Reverse String in Java using StringBuffer: " + reverseStr);

        //iterative method to reverse String in Java
        reverseStr = reverse(str);
        System.out.println("Reverse String in Java using Iteration: " + reverseStr);

        //recursive method to reverse String in Java
        reverseStr = reverseRecursively(str);
        System.out.println("Reverse String in Java using Recursion: " + reverseStr);

    }

    public static String reverse(String str) {
        StringBuilder strBuilder = new StringBuilder();
        char[] strChars = str.toCharArray();

        for (int i = strChars.length - 1; i >= 0; i--) {
            strBuilder.append(strChars[i]);
        }

        return strBuilder.toString();
    }

    public static String reverseRecursively(String str) {

        //base case to handle one char string and empty string
        if (str.length() < 2) {
            return str;
        }

        return reverseRecursively(str.substring(1)) + str.charAt(0);

    }
}


That’s all on how to reverse String in Java using Recursion, Iteration, and without using StringBuffer. This is one of my favorite interview questions and I mostly ask to write a recursive solution just to know whether the programmer has the ability to comprehend the recursive problems or not.


Here are a few more Java interview questions you may like.

And now is the quiz time, What is the time complexity of reverse a String using iteration and recursion, I mean for above solution? And, can you improve it by using any data structure?

49 comments:

  1. Nice One - One more operation is Reversing the words of Palindrome Sentences.

    String str = "India is Great becuase Great is India";

    public String reverseWords(String str) {
    String arr[]=str.split(" ");
    StringBuilder stb=new StringBuilder();
    for(int i=arr.length-1;i>=0;i--)
    stb.append(arr[i]+" ");
    return stb.toString();
    }

    Chandraprakash Sarathe
    ---------------------------
    http://javaved.blogspot.com/

    ReplyDelete
  2. @Chandraprakash, indeed reversing words on String is also good interview question and can be asked in conjunction with reversing string using recursion. I see you have also good blog keep it up. you may also like core java interview questions and answers asked in Finance domain

    ReplyDelete
  3. reversing string in java using loop is better than reversing string using recursion. code example of reverse string for loop looks much simpler and easy to understand than code example of recursive reversal of string. Another disadvantage of using recursion for reversing string is chance of StackOverFlowError. Also using loop is optimized way of reversing string in Java.

    ReplyDelete
  4. Hi, I am looking answer for question on String, "How to reverse word in a String in Java", Can you guys please help with code example and explanation ? I have one more question regarding implementing wrapping of String. I have fixed size of String which may vary from one android device to another and I want to write my own String wrap function which takes Screen width and wrap String accordingly.

    ReplyDelete
  5. I was looking for simple Java program to reverse String in Java when I find this great tutorial. This tutorial not only explains how to reverse String in Java with simple example of recursion and for loop but also explains logic behind it. Thanks for your Java program, you are helping programmers and developers in big way.

    ReplyDelete
  6. Can you please format this Java program for string reversal so that we can see the keyword in different color. I really like this Program to reverse String in Java and want to use in my site with attribution link, is it ok?

    ReplyDelete
  7. I was looking for a Java program to reverse String in Java without using StringBuffer reverse function when I come across this article. Its wonderful, Thanks for showing us two ways to reverse String in Java including tough one e.g. recursion. no matter how much I practice, it's always hard to reverse String using Recursion. I love to that using StringBuffer reverse() method if I am allowed to do so.

    ReplyDelete
  8. in the recursive function i think it will be nice to have a null check before we do str.length()

    ReplyDelete
  9. Be careful of the recursion function never returning. In this case when the recursion function is called, it will continuously go in a loop and won't terminate. You probably want some checks in there or else I'd say you failed that interview question ;)

    ReplyDelete
  10. Writing Java program to reverse a String without using reverse function or using recursion is just too popular and every body knows how to do that. There is no point asking this question in Interviews as you will get standard answers explained here.

    ReplyDelete
  11. For fun, here's an optimization to your recursive method.. even though Java doesn't currently support tail-call optimization.

    public static String reverseRecursively(String str) {
         //base case to handle one char string and empty string
         if (str.length() < 2) {
              return str;
         }

         //tail-call optimization
         return reverseRecursively(str, "");
    }

    public static String reverseRecursively(String str, String reverseStr) {
         if (str.length() < 1) {
              return reverseStr;
         }
         StringBuilder strBuilder = new StringBuilder();
         strBuilder.append(str.charAt(0));
         strBuilder.append(reverseStr);
         return reverseRecursively(str.substring(1), strBuilder.toString());
    }

    ReplyDelete
  12. For fun, another example:

    // iterative method to reverse String in Java
    public static String reverse(String str) {
    char[] c = str.toCharArray();

    for (int i=0; i < str.length(); i++)
    for (int j=c.length-1; j > i; j--) {
    char temp = c[j];
    c[j] = c[j-1];
    c[j-1] = temp;
    }

    return new String(c);
    }

    Additionally, a cool Java trick is if there is only one expression or statement after a control structure... Curly brackets aren't necessary!

    ReplyDelete
  13. Below will help to avoid inner loops
    public class StringRecursion {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    String str="abcdefghi";
    int strMaxIndex=str.length()-1;
    char[] c=str.toCharArray();
    char temp;
    System.out.print("String Before:"+c.toString());

    for(int i=0;i<=strMaxIndex;i++)
    {

    if(i>=strMaxIndex-i)
    {
    break;
    }
    temp=c[i];
    c[i]=c[strMaxIndex-i];
    c[strMaxIndex-i]=temp;
    }
    System.out.print("\nString After:"+c.toString());


    }

    }

    ReplyDelete
  14. Another way, run only half the size of chars o(n/2)

    public static String getReversedString(String str)
    {
    char[] chars = str.toCharArray();

    for(int i = 0 ; i < chars.length/2; i ++)
    {
    char temp1 = chars[i];

    chars[i]= chars[chars.length-i-1];
    chars[chars.length-i-1]= temp1;

    }

    return new String(chars);
    }

    ReplyDelete
  15. Can i get the code of java to print the string "please test" to "test please" and also for the input string also. Please reply this answer on niksy@ymail.com

    ReplyDelete
  16. String str = "India is Great becuase Great is India";

    public String reverseWords(String str) {
    String arr[]=str.split(" ");
    StringBuilder stb=new StringBuilder();
    for(int i=arr.length-1;i>=0;i--)
    stb.append(arr[i]+" ");
    return stb.toString();
    }

    ReplyDelete
  17. @vinaykumar +1 , that solution was first that came up to my mind

    ReplyDelete
  18. public static String reverseUsingCharArray(String str) {
    char[] chArray = str.toCharArray();
    for(int i=0; i< chArray.length/2;i++) {
    char a = chArray[i];
    chArray[i] = chArray[chArray.length-1 - i];
    chArray[chArray.length -1- i] = a;
    }
    return new String(chArray);
    }

    complexity would be O(n/2).

    ReplyDelete
  19. public static String reverseRec(String str){
    return str = (str.length()<=1 || str==null)? str: reverseRec(str.substring(1))+ str.charAt(0);
    }

    ReplyDelete
  20. I think this one is easy to understand:

    private static String reversString(String str) {

    char chArr[] = new char[str.length()];
    for( int i = 0, j = str.length() -1; i < j; i++, j--) {
    chArr[i] = str.charAt(j);
    chArr[j] = str.charAt(i);
    }
    String rStr = new String(chArr);
    return rStr;
    }

    ReplyDelete
  21. Here are my solutions with stack and with elements exchange:

    private static String ReverseA(String input)
    {
    if (null == input)
    {
    return null;
    }

    Stack chars = new Stack(input.ToCharArray());

    StringBuilder sb = new StringBuilder(input.Length);

    while (chars.Count > 0)
    {
    sb.Append(chars.Pop());
    }

    return sb.ToString();
    }

    private static String ReverseB(String input)
    {
    if (null == input)
    {
    return null;
    }

    Char[] chars = input.ToCharArray();

    for (Int32 q = 0, qMax = chars.Length / 2; q < qMax; q++)
    {
    Char cache = chars[q];

    Int32 mirrorIndex = chars.Length - 1 - q;

    chars[q] = chars[mirrorIndex];

    chars[mirrorIndex] = cache;
    }

    return new string(chars);
    }

    ReplyDelete
  22. @Chandraprakash

    I think that code breaks...
    example String str = "1234 56789";
    the output wl come .= " 56789 1234" which is wrong

    ReplyDelete
  23. I don't think doing StringBuilder.append is most efficient way here, because it will check capacity when appending every character, also it copy character by loop, we could do reverse on char array then convert the char array to string, which is using System.arrayCopy, should be much efficient.

    int n = strChars.length - 1;
    for (int i = (n - 1) >> 1; i >=0; i--) {
    char c = strChars[i];
    strChars[i] = strChars[n - i];
    strChars[n - i] = c;
    }
    return new String(strChars);

    ReplyDelete
  24. 1 temp - O(n) solution

    public static void main(String args[]) {

    String str = "Reverse this string";

    int slength = str.length();
    int end = slength-1;

    char[] buf = new char[str.length()];
    for(int i=end; i!=-1; i--) {

    buf[(end)-i] = str.charAt(i);
    }

    String sOut = new String(buf);
    System.out.println(String.format("In:%s", str));
    System.out.println(String.format("Out:%s", sOut));


    }

    ReplyDelete
  25. import java.io.*;
    class split
    {
    public static void main(String args[])throws IOException
    {
    String str[];
    String finalstr="";
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    str=br.readLine().split(" ");
    for(int i=str.length-1;i>=0;i--)
    finalstr+=str[i]+" ";
    System.out.println(finalstr);
    }
    }

    ReplyDelete
  26. Mine way :

    public static char[] revStr(char[] arr, int start, int end)
    {
    if(start == (arr.length/2))
    {
    return arr;
    }

    char temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;

    return revStr(arr, ++start, --end);
    }

    ReplyDelete
  27. please sir can u breifly explain this function plz

    public static String reverseRecursively(String str) {

    if (str.length() < 2) {
    return str;
    }

    return reverseRecursively(str.substring(1)) + str.charAt(0);

    }
    }

    ReplyDelete
  28. @praashant, that's the base case if String has less than two character e.g. empty or just one character than reverse of the String is the String itself e.g. reverse of "a" is "a" itself, or reverse of empty String is "" itself, that's why we are return the same str there. Remember, every recursive algorithm needs a base case to solve the problem without it, recursion will never end and your program will die after running out of Stack depth throwing java.lang.StackOverFlowError in Java.

    ReplyDelete
  29. Another one to check String Palindrome...

    package com.practice.java;

    import java.util.Scanner;

    public class PalindromeStringCheckSimple {

    public static void main(String[] args) {
    System.out.println("Enter any String: ");
    Scanner sc = new Scanner(System.in);
    String text = sc.nextLine();
    char[] text1 = text.toCharArray();
    int length = text1.length;
    int temp = length;
    boolean isPalindrome = true;
    for(int n=0; n<length; n++){
    temp = temp-1;
    if(text1[n] != text1[temp]){
    isPalindrome = false;
    }
    }
    System.out.println("String is Pallindrome: "+isPalindrome );
    sc.close();
    }

    }

    ReplyDelete
  30. package Reverse;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;

    public class Reverse {
    public static void main(String args[]){

    ActionReverse ar = new ActionReverse();
    System.out.println("Enter a String");
    @SuppressWarnings("resource")
    Scanner scanner = new Scanner(System.in);
    String input1 = scanner.nextLine();
    System.out.println(ar.reverseString(input1));
    System.out.println(ar.reverseArray(input1));


    }
    }

    class ActionReverse{
    public String reverseString(String input){
    String reverseString ="";

    for(int i = input.length()-1; i>=0; i--)
    {
    char char1 = input.charAt(i);
    reverseString = reverseString +Character.toString(char1);

    }
    return reverseString;

    }

    public List reverseArray(String input){
    List list = new ArrayList();
    for(int i = input.length()-1; i>=0; i--)
    {
    char char1 = input.charAt(i);
    list.add(char1);
    }
    return list;
    }
    }

    ReplyDelete
  31. // tail recursive approach
    recursiveReverse("tail recursive approach","");
    public static String recursiveReverse(String text, String newStr) {
    if (text.length() < 1) {
    return newStr;
    }
    return recursiveReverse(text.substring(1), text.charAt(0) + newStr);
    }

    ReplyDelete
  32. Why cannot we do use charAt and append from (string.length -1) to 0 and create a new string?

    ReplyDelete
  33. can someone explain where the + str.charAt(0); in reverseRecursively(str.substring(1))+ str.charAt(0);
    returns to?
    I also don't understand where it stores or how it stores the string till it returns it fully reversed to reverseStr up top.

    ReplyDelete
  34. I don't understand how recursion works. Can you please give more logic details?

    ReplyDelete
  35. void reverseString(string str){
    if(str.size() >0)
    reverseString(str.substr(1,str.size()));
    cout<<str[0];
    }

    ReplyDelete
  36. public class Reverse {

    public static void main (String[] args) {
    System.out.println(reverse("Madam is adam"));
    }
    public static char[] reverse (String str) {
    char[] character = str.toCharArray();
    char temp;
    for(int i=0; i<character.length/2; i++) {
    temp = character[i];
    character[i] = character[character.length -i -1];
    character[character.length -i -1] = temp;
    }
    return character;
    }
    }

    ReplyDelete
  37. Assume you have a string “this is test string”.
    You need to write a code to reverse the string. The output should be “string test is this”.
    There is a reverse method by default available in Java, do not use that.can any slove this

    ReplyDelete
  38. public static String reverse(String input) {
    if (input.length() == 1) {
    return input;
    } else {
    String first = String.valueOf(input.charAt(0));
    return reverse(input.substring(1)) + first;
    }
    }

    ReplyDelete
  39. public static string ReverseString(string str )
    {
    if (str.Length == 0)
    return "";
    string reversed = str[str.Length - 1] + ReverseString(str.Substring(0, str.Length - 1));
    return reversed;
    }

    ReplyDelete
  40. public static string ReverseString(string str)
    {
    if (string.IsNullOrEmpty(str))
    return null;
    return str[str.Length - 1] + ReverseString(str.Substring(0, str.Length - 1));
    }

    ReplyDelete
  41. I have made some changes to recursive method by using StringBuilder. In this way we can reduce the number of string objects being created to some extend.

    private static StringBuilder reverseRecursive(String str) {
    if(str.length() < 2) return new StringBuilder(str);

    return reverseRecursive(str.substring(1)).append(str.charAt(0));
    }

    ReplyDelete
  42. private static String reverseRecursively2(String str) {
    if(str.length()==1){
    return str;
    }
    str=str.charAt(str.length()-1)+reverseRecursively2(str.substring(0,str.length()-1));
    return str;
    }

    ReplyDelete
  43. package com.pageTest;

    import java.util.*;
    import java.util.stream.Collectors;

    public class DuplicateCharacters {

    private String stringReverse(String string) {
    String reverseString = "";
    char chars[] = string.toUpperCase().toCharArray();
    for (int i = chars.length-1; i >=0; i--) {

    reverseString = reverseString+chars[i];

    }
    return reverseString;
    }

    public static void main(String[] args) {
    DuplicateCharacters duplicateCharacters = new DuplicateCharacters();
    System.out.println(duplicateCharacters.stringReverse("srinu"));

    }

    }

    ReplyDelete
  44. String reversedString = "";
    public void reverseString(String word){
    int stringLength = word.length();

    String lastChar = word.substring(stringLength-1,stringLength);
    reversedString += lastChar;
    if(word.length() != 1) {
    String updatedString = word.substring(0, stringLength - 1);
    reverseString(updatedString);
    }
    Log.d("ReverseStringRecursion",reversedString);

    }

    ReplyDelete
  45. package helloworld;
    import java.util.*;
    import java.lang.*;

    public class countingnoofchar {

    public static void main(String[] args)
    {
    String str1="mamonfire";
    String str2="";
    int i,p=str1.length();
    for(i=p-1;i>=0;i--)
    {
    str2+=str1.charAt(i);
    }
    System.out.println(str2);



    }

    }

    ReplyDelete
  46. Not sure if there's been such suggestions in comments, but I don't see why iterating over whole table and not its half and why using StringBuilder while we know it's going to be a table of same size:

    public String iteratively(String given){
    var letters = given.toCharArray();
    for (int i = 0; i < letters.length/2; i++) {
    var temp = letters[i];
    letters[i] = letters[letters.length -1 -i];
    letters[letters.length -1 -i] = temp;
    }
    return String.valueOf(letters);
    }

    ReplyDelete
  47. Hello @Unknow, the original solution is a brute force one for simplicity one. Your solution is optimized and yes, no need to iterate whole table, as you can swap characters. Also, using array is better than StringBuffer here for the reason you mentioned that Stringbuffer will have same length.

    ReplyDelete
  48. Hi,
    In return statemnt 'reverseRecursively(str.substring(1))+ str.charAt(0)' why charAt(0) is appended. But when I try to print the string passed as parameter I don't see any appended character at end.But if I try removing str.charAt(0) the code doesn't work.Please explain why we are using str.charAt(0) and how this recursion works.

    ReplyDelete
  49. //Reverse String withiout Recursive, no StringBuffer needed
    public static String reverseNoRecursive(String str) {

    String reverse = "";

    for(int i = str.length(); i > 0; i--) {
    reverse = reverse + str.substring(i- 1, i);
    }

    return reverse;

    }// end method reverseNoRecursive()

    ReplyDelete