-->

Reverse a String in Java using Recursion

Posted by Admin on
public class ReverseOfString {
      
       public static void main(String args[])
       {
              String str = "ABCD";
              int len = str.length()-1;
              String rvrStr = reverse(str,len);
              System.out.println(rvrStr);
       }

       private static String reverse(String str, int len) {
             
              String str1 ="";          
              if(len>=0)
              {
                     str1 = str1+str.charAt(len);
                     str1=str1+reverse(str,len-1);
                     return str1;
              }
              else
              {
              return str1;
              }
             
       }

}


The basic problem ,guys do in above is that instead of str1=str1+reverse(str,len-1) they write str1=reverse(str,len-1) which is wrong because in Java String creates new object everyt time for the string so we need to keep on appending .

No comments:

Post a Comment