Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does charAt reverse the input in this method?

Tags:

java

methods

//method
public static String foo(String s)

{
if (s.length() == 1)

return s;

else

return foo(s.substring(1)) + s.charAt(0);
}

What does foo(“abcd”) evaluate to? It is is my understanding that this would reverse the input, but why is that?

like image 459
JavaStudent12344 Avatar asked Jun 04 '26 01:06

JavaStudent12344


2 Answers

It is a recursive reverse. s.substring(1) is the line without its first character; s.charAt(0) is the first character.

What the function is saying is "if the line is one character long, the answer is the line itself; otherwise, chop off the first character, compute the same function, and add the chopped off character to the end of the result".

You can work out on a piece of paper how performing the steps above amounts to reversing a string.

EDIT : It is worth noting that this implementation is going to crash with an exception if you try passing it an empty string. Changing if (s.length() == 1) to if (s.length() == 0) would address this problem (thanks to Tom Hawtin - tackline for mentioning this in a comment).

like image 81
Sergey Kalinichenko Avatar answered Jun 05 '26 23:06

Sergey Kalinichenko


Hope this makes it clear how the recursion works in this case:

foo("bcd") + "a"
  (foo("cd") + "b") + "a"
    ((foo("d") + "c") + "b") + "a"
      (("d" + "c") + "b") + "a" -> "dcba"
like image 21
Alexander Pavlov Avatar answered Jun 06 '26 01:06

Alexander Pavlov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!