0

Could anyone please explain why "return str" line never executes?

public static String reverseString(String str){
    String reverse="";
    if(str.length() == 1){
        return str; //at one point this condition will be true, but value never returns
    } else {
        reverse += str.charAt(str.length()-1) + reverseString(str.substring(0,str.length()-1));
        return reverse;
    }
}

public static void main(String a[]) {
    System.out.println(reverseString("Test"));
}
4
  • 2
    return str; will only executed if the string has a length of 1, Test has a length of 4 Commented Jun 11, 2015 at 6:48
  • Have you tried running your small example in a debugger? Commented Jun 11, 2015 at 6:50
  • the code is absolutely right... return reverse executes... Commented Jun 11, 2015 at 6:50
  • 1
    If you are using an IDE like eclipse, debug and see it enters if (str.length() == 1) when it gets str = "T" value during recursion calls. Commented Jun 11, 2015 at 6:54

5 Answers 5

2

The line does executes, how can you say it does not executes. I have added the syso statement, it does print, actually you are calling substring in a recursion, once the length becomes 1, it will execute.

public static String reverseString(String str) {
        String reverse = "";
        if (str.length() == 1) {
            System.out.println("hi");
            return str; // at one point this condition will be true, but value never returns
        } else {
            reverse += str.charAt(str.length() - 1) + reverseString(str.substring(0, str.length() - 1));
            return reverse;
        }
    }

    public static void main(String a[]) {
        System.out.println(reverseString("Test"));
    }

output

hi
tseT
Sign up to request clarification or add additional context in comments.

3 Comments

when the length becomes 1, shouldn't it print the value of "str" as well?
@VijayNandwana it is recursive method, method call for reverseString is from else part, carefully observe it, so return str, will return to else part not from whole method ..
Yes, that makes sense. I missed that part. I was wondering that when the if condition becomes true then else block will not execute, but in this case method has been called from else block hence it will get execute. Understood. Thank you Ankur.
1

You can easily use StringBuilder#reverse method

public String reverser(String str){
   return new StringBuilder(str).reverse().toString();
}

3 Comments

Please explain the code in an answer. Even if this works (I think it is), an explanation can help OP to correct his solution better than copying and pasting. (Also this doesn't answer the actual question on "why doesn't this function end properly?")
@Vesper that is a built-in class in Java. check the API-Doc from the above link. If you are interested you can check the source code as well from rt.jar file
The line added is a decent explanation as is. :)
0
public static String reverseString(String str) {
    String reverse = "";
    if (str.length() == 1) {
        return str; // at one point this condition will be true, but value
                    // never returns
    } else {
        String part = reverseString(str.substring(0, str.length() - 1));
        System.out.println("Current: " + part); // Print out
        reverse = str.charAt(str.length() - 1)
                + part;
        return reverse;
    }
}

public static void main(String a[]) {
    System.out.println(reverseString("Test"));
}

Just add a print within your recursive function, to trace what is happening.

Output:

Current: T      // return str
Current: eT     // return reverse
Current: seT    // return reverse
tseT            // final return reverse

From the output, you can convince yourself whether str is being returned.

Comments

0

My Implemention:

    public static String reverse(String str) {
        if(str.length() > 1) {
            return str.substring(str.length()-1)+reverse(str.substring(0, str.length()-1));
        } else {
            return str;
        }
    }

    public static void main(String[] args) {
        System.out.println(reverse("Test"));
    }

output:

tseT

Comments

0

Actually it hits and executes, check this out;

public static String reverseString(String str){
    String reverse="";
    if(str.length() == 1 ){
        System.out.println("HIT: " + str);  // CHECKING HIT
        return str; //at one point this condition will be true, but value never returns
    } else {
        reverse += str.charAt(str.length()-1) + reverseString(str.substring(0,str.length()-1));
        return reverse;
    }
}

public static void main(String a[]) {
    System.out.println(reverseString("Abcd"));
}

If you run this code, you will see the output as below;

HIT: A
dcbA

To Understand how this code is working, you have to understand how reverse method call itself and completes its process;

Check the image down below;

enter image description here

As you can see, on the 3rd step, because that the recursive function's input string length equals to 1, that part of the code is executed.

Hope that all these helps.

1 Comment

Thank you Levent for explaining the method flow with diagram.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.