English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

is it a rule of thumb to specify a return type other than void in recursive methods? I am barely learning and found that a method can can call itself when its return type is void but the book I am learning off always specifies a return type other than void.

2007-12-29 14:16:52 · 2 answers · asked by Dre D 2 in Computers & Internet Programming & Design

2 answers

Typically in any language. A recursive method must have an out, else it will go into an infinite loop. Typically, using direct recursion the return type is used to signal the out; however, a parameter passed in by reference can also be used. Since Java, doesn't support pass by reference, using the return value is probably the easiest.

2007-12-29 14:25:01 · answer #1 · answered by Cipher 3 · 0 0

Recursion requires a way to stop. A non-void return is one way. If there is a path that can simply not make the next level call for further recursion, but instead can just return, that also works. What you want to watch out for is a sequence that, come Hell or High Water, will always make the recursion call.

Recursion is tricky but worth it (sometimes). Just remember that the exit path is as important as the recursion path.

2007-12-29 22:33:02 · answer #2 · answered by The_Doc_Man 7 · 0 0

fedest.com, questions and answers