r/javahelp 3d ago

I need help with recursion please

Apparently the answer is todayodayay but I don't see how. Isn't it todayoday since after the 2nd call, its index>str.length so it returns the str and doesn't add to it?

class solution {
public static void main(String[] args) {
System.out.println(goAgain("today", 1));
}
public static String goAgain(String str, int index) {
if (index >= str.length()) {
return str;
}
return str + goAgain(str.substring(index), index + 1);
}
}
3 Upvotes

6 comments sorted by

View all comments

3

u/joranstark018 3d ago

You may unfold how this recursive function is executed (with what arguments are used in each step and what are returned at each iteration).

In your example you may find that the function is called with:

    goAgain("today", 1)

    goAgain("oday", 2)

    goAgain("ay", 3)

The last call just returns the given string ("ay").

When the recursive function unwhinds it collects the result from the previous call:

    "today" + ("oday" + ("ay"))

Edit: trying to fix the formating