D
D
DDwrt1002021-02-15 09:33:30
Java
DDwrt100, 2021-02-15 09:33:30

How does recursion work in Java?

Hello everyone, who can tell what happens to the function with this code?

public void save(){
String myString =n.readstring();
if(n==null){
save();
return;
}
this.classString = myString;
}

The code may have errors, but it conveys the essence, and not the best. We read the variable, if there is nothing in it, then we call the function again. If there is data, then we write and close the variable. I'm interested in the recursive part.
In this version, it turns out that the function remains on the stack, and a new function is generated (like a nesting doll), and this will continue until the JVM stack ends, or the result is obtained. If we get the result, then all open functions collapse? I understand correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Erik Mironov, 2021-02-18
@DDwrt100

When you call a method from within another method, the calling method is suspended in a partially completed state. All values ​​of the variables of the calling function are physically stored in memory. The method called by the method that calls it is placed on top of the calling method, and the same thing happens as long as the recursive case is met (the condition under which the method calls itself). When the base case (the condition under which the recursion must be stopped) occurs, the methods return control to the method that called them in turn, until the original (bottom-most) method completes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question