How to reverse string in java without using reverse method

How to reverse string in java without using reverse method



How to reverse string without using reverse method of StringBuffer is one of the frequently asked interview questions in java. It is also important for ICSE and ISC students for understanding of String and characters and iterators etc.

In interview most of the java programmers answer this String reverse question by using StringBuffer reverse() method which is used to reverse the String. But interviewer is not interested in this answer so tweaks his question and ask How to reverse the String without using reverse method of StringBuffer. This tutorial explains how to reverse the String using two methods one is iterative and other is recursive.

Reverse string in java using iterative method



In case of iterative method we are using character array of String in java. Once we get the character array we iterate over it in reverse order and use StringBuilder to append each character as shown in example below


public static String reverseUsingChar(String str) {

StringBuilder stringBuilder = new StringBuilder();

char[] charsInStr = str.toCharArray();

for (int i = charsInStr.length - 1; i >= 0; i--) {

stringBuilder.append(charsInStr[i]);

}

return stringBuilder.toString();

}


Reverse string in java using recursive method



Next method we use to reverse the String is recursive method as shown in example below. We are passing the argument of strRev.substring(1) to the method recursively and in the method we are appending the first character of current String to it which do the reverse of the String. But use the recursive code in development code very carefully as it may give stackoverflow error because of long string or some program error itself.

public static String reverseStringRecursively(String strRev) {

if (strRev.length() < 2) {

return strRev;

}

return reverseStringRecursively(strRev.substring(1)) + strRev.charAt(0);

}

Thus we have seen two methods to reverse the String without using StringBuffer reverse method.

Hope you find this article helpful.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

1 comments: