Wednesday, 18 May 2016

How to reverse a string in Java

Reversing a string using a recursive method or using iteration is one Java interview coding question asked quite frequently along with some other popular questions like How to find the longest palindrome in the given String, How to find all the permutations of the given String.

Though StringBuilder class has a reverse() method which can do the reversal of the string but generally in the interviews it will be asked to write the iterative or recursive logic or both so in this post both ways are given.

Reversing a string - Non-recursive

Non-recursive solution follows the logic of starting from the end of the string and keep moving back character by character and keep appending those characters to form a new string which is reverse of the given String.

Reversing a string - Recursive

In recursive solution in each recursive call to the method you take the first character (index 0) and call the method with the rest of the string (excluding the first char) and add the first char of the passed string at the end.

Java Code

public class ReverseDemo {

    public static void main(String[] args) {
        
        String reversed = reverseString("Bharat");
        System.out.println("reverse (recursion) - " + reversed);
        
        String reverseItr = reverseItr("India is my country");
        System.out.println("reverse (non recursive) - " + reverseItr);
    }
    
    // Using recursion
    private static String reverseString(String str){
        // validation & base case
        if((str == null) || (str.length() <= 1)){
            return str;
        }
        // recursive call
        return reverseString(str.substring(1)) + str.charAt(0);    
    }
    
    
    // Using iteration - Non Recursive
    private static String reverseItr(String str){
        // validation
        if((str == null) || (str.length() <= 1)){
            return str;
        }
        
        StringBuilder sb = new StringBuilder();
        for(int i = str.length() - 1; i >= 0; i--){
            sb.append(str.charAt(i));
        }
        return sb.toString();
    }
}

Output

reverse (recursion) - tarahB
reverse (non recursive) - yrtnuoc ym si aidnI

Explanation

I guess the explanation for the iteration logic provided above should suffice for that code. Recursive is a little hard to visualize so let's see how recursive calls will actually stack up.

reverseString("Bharat")
(reverseString("harat")) + "B"
((reverseString("arat")) + "h") + "B"
(((reverseString("rat")) + "a") + "h") + "B"
((((reverseString("at")) + "r") + "a") + "h") + "B"
// This will trigger the base condition
(((((reverseString("t")) + "a") + "r") + "a") + "h") + "B"

"tarahB"

That's all for this topic How to reverse a String - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Count total number of times each character appears in a String
  2. How to find the longest palindrome in the given String
  3. How to find all the permutations of the given String
  4. Check if given strings are anagram or not
  5. How to format date in Java using SimpleDateFormat

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment