I have a problem with the following code:
public class Recursividad1 {
public static void main(String[] args) {
System.out.println("El factorial es: "+NumeroEntero.getFactorial(5));
System.out.println("El factorial es: "+NumeroEntero.getPotencia(5, 2));
}
}
and this is the class where the recursive methods are:
public class NumeroEntero {
private static int devuelveFactorial(int numero) {
if (numero == 0) {
return 1;
} else {
return numero * devuelveFactorial(numero--);
}
}
private static int devuelvePotencia(int valor, int potencia) {
if (potencia == 0) {
return 1;
} else {
return valor * devuelvePotencia(valor,potencia--);
}
}
public static int getPotencia(int valor2, int potencia2){
return devuelvePotencia(valor2, potencia2);
}
public static int getFactorial(int numero2){
return devuelveFactorial(numero2);
}
}
What is the stack?
The stack in java is a stack in which the data referring to the execution of the methods (internal variables, and others) are stored.
What is StackOverflow?
Every time you make a method call, memory is allocated on the stack. Taking into account that memory is finite, there is always the possibility that this memory will end up being full.
When that memory is full and you make one more call to another new method, the JRE is not able to save the necessary data in memory because it is full, and that is when the StackOverflow is launched.
Why does it occur in recursive calls?
From the previous point you may have realized that, in theory, it is quite easy to force a StackOverflow. The good part is that in java, there are a lot of optimizations, both on the garbage collector and on the compiler side to avoid things like that.
One point where it can't be avoided, however, is in recursive calls:
This is usually not a problem because there isn't usually a very long call queue between methods, but on an infinite recursive call, the stack fills up quickly.
That is why it is very important to leave a return that gets closer and closer to the trivial case, which in your exercise is
numero == 0
.What is your mistake?
Your error occurs on this line:
Not easy to catch with the naked eye. The problem is that by doing
numero--
you are applying a post-decrement . That is, java will execute the return first, and after returning the result, decrement the value ofnumero
, but it's too late .Fixing it is as easy as changing the post-decrement to a
numero - 1
: