Contenido del Curso
Java Extended
Java Extended
Recursion
How to easily break your code?
This can be done with recursion.
Recursion in Java is a process when a method calls itself. Why can this break the code? Because it can lead to infinite recursion, which will endlessly consume memory and decrease the device's performance.
So why do we need recursion at all?
In some cases, recursion can be useful, but it should be used with caution. Recursion, for example, can replace a while loop.
Let's look at an example of using recursion to calculate the sum of all numbers up to a number passed as a parameter:
Main
package com.example; public class Main { public static void main(String[] args) { // do not change code from below System.out.println(calculateSum(5)); } // do not change the code above static int calculateSum(int num) { if (num > 0) { num = num + calculateSum(num - 1); } else { return 0; } return num; } }
The method calculateSum()
calls itself with reduced values. We also have an exit point from this recursion when the variable num
becomes zero. This method calculates the sum of all numbers from 1 to the parameter, in our case 5
. Let's look at the flowchart that shows how recursion works using this method as an example:
The example above demonstrates how the method calls itself with reduced values, and when it reaches zero, it goes back up by summing the values. We can also observe how the body of the if
block is executed, where we add num
to the result of the method call with a reduced value. The intermediate values after each method call are indicated near the arrows.
Can we avoid using recursion?
Recursion can also be replaced with a regular loop. Let's look at an example where we first use a recursive method and then use a for
loop to perform the same operation:
Main
package com.example; public class Main { public static void main(String[] args) { // do not change code from below int num = 5; System.out.println("result after using recursion: " + calculateSum(num)); int result = 0; for (int i = 1; i <= num; i++) { result = result + i; } System.out.println("result after using for-loop: " + result); } // do not change the code above static int calculateSum(int num) { if (num > 0) { num = num + calculateSum(num - 1); } else { return 0; } return num; } }
Here we can see how we replace our recursive method with a regular for
loop, using the variable i
to increment our result
by i
each time until it reaches the specified number num
, which is the parameter in the method.
Conclusion
In conclusion, I can say that recursive methods are quite interesting but also dangerous. With recursion, you can both improve and completely break your code. Almost any recursion can be replaced with a loop using method calls. So, whether to use recursion or replace it with a method is your choice. But if you still choose to use recursion, even if you have mastered it well, be extremely cautious.
¡Gracias por tus comentarios!