Sitemap
Aldyputu

Aldyputu

Java: Recursive Method

2 min readDec 13, 2023

Recursive means we called the method to execute the method again and again until the program crash or output needed :)

We can talk about factorial, 10! -> 1 x 2 x 3 x 4 x 5 x 6 x … x 10. Its the same method that used again and again to times the first number to the next and the next until the n limit reaches and we get the exact result, in this case the result is 3628800.

public class Factorial {

static int factorial(int value) {

var result = 1; //the number always start from one
for (int i = 1; i <= value; i++){

result *= i; //the loop will get us throught the number until the value reached
//it will keep multiply by the last result to the next number until we get final result
}

return result;
}

public static void main(String[] args) {
factorial(10);
}

}
/*
Output
3628800
*/

Above code is an example to write factorial method without recursive. Lets try to write the code using recursive:

public class FactorialRecursive {

static int factorial(int value) {

if (value == 0) {
return 1;
}
//recursive calling the method inside the method
//develop factorial calculation in it
return value * factorial(value - 1);
}

public static void main(String[] args) {
factorial(10);
factorial(5);
factorial(2);
}

}
/*
OUTPUT
3628800
120
2
*/

It is easier to write the code when we need to input the result value to the current method and make next operation on the method until finally hit the parameter method.

Get Aldyputu’s stories in your inbox

Join Medium for free to get updates from this writer.

But, becareful with the fanciness of recursive. There is stack overflow that can be happen to your program when the method deeply call the method again and again that cause the process got it stacked. Just like we place some box above box, if too high it will fall. The limit of method stack is different based on your device specification.

Lets write the code:

public class FactorialRecursive {

static static void loop(int value) {
if (value == 0){
System.out.println("Done!");
} else {
System.out.println("Called of " + value);
loop(value - 1);
}
}

public static void main(String[] args) {
loop(10);
loop(100);
loop(10000);
}

}
/*
Output
-> the first one should be fine
-> second also fine
-> the third messed with error: Stack Overflow, THE METHOD CALLED DEEPLY and
cannot completely finish the task
*/

--

--