Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Methods that call themselves?

+10 votes
I think someone mentioned that there are methods that can call themselves. Wouldn't that just result in a never ending process of method calls? Or could it actually be useful? If so, how?
asked Dec 1, 2015 in (Winter 15-16) by Erik Anderberg (100 points)

2 Answers

+6 votes

The process where the method calls it self is called recursion. It can actually be useful to solve smaller problems like factor problems more efficiently .  Without an end condition, the recursive method keeps calling itself forever. 

answered Dec 1, 2015 by Raisha Shrestha (100 points)
+4 votes
Based on what we've learned so far, *yes*, methods that call themselves would get into an endless loop (except that after a while Java will have an error because it runs out of room to keep track of all the methods that have been called!).

Later, we'll learn some more magic that will let us only call the method again *sometimes*, so that the looping can stop once a certain condition is met... that's the "end condition" that Raisha is talking about.
answered Dec 2, 2015 by Forrest Stonedahl (100 points)