Writing a Java program to reverse 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 a given String, How to find all the permutations of a 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 in Java - 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 in Java - 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.
Reverse a String Java Program
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 in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-