🌐
W3Schools
w3schools.com › java › java_recursion.asp
Java Recursion
Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the following example, recursion is used to add a range of numbers together by breaking it down into the simple task of adding two numbers:
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › examples-Java-recursion-recursive-methods
Five examples of recursion in Java
March 24, 2021 - In this example, the recursive method returns a whole number that represents an ongoing sum. The recursive Java logic is as follows. Start with a number and then add that number to one less than itself. Repeat that logic until you hit zero.
🌐
Programiz
programiz.com › java-programming › recursion
Java Recursion: Recursive Methods (With Examples)
Any object in between them would be reflected recursively. ... In the above example, we have called the recurse() method from inside the main method (normal method call). And, inside the recurse() method, we are again calling the same recurse method.
🌐
Reddit
reddit.com › r/learnprogramming › recursion in java - tutorial recommendation
r/learnprogramming on Reddit: Recursion in Java - tutorial recommendation
January 11, 2023 -

Hi all.. I am having quite a lot of difficulty with recursion. For me it is what is happening internally at each step, what is being returned, what the internal stack looks like.. I understand the basics, the base case, like the Fibonacci sequence. Intellectually I understand depth first searches .. but I simply do not understand what is going on under the hood. I cannot make the connection between what visually is supposed to be happening, vs how the algorithm works.

This towers of Hanoi explanation should be more than sufficient, and yet, it simply leaves me overwhelmed.

I am specifically asking for a tutorial in Java - Thank you.

Top answer
1 of 3
2
I've found that visualizations can be really useful for understanding what's going on. You might try walking through a simple DFS with some sort of interactive debugger, like this one .
2 of 3
2
In my opinion, recursion is best understood bottom-up. Let's look at the tower of hanoi: fun solveTower(num, from, to, using) if num eq 0 return solveTower(num-1, from, using, to) print "Moved disk {n} from {from} to {to}" solveTower(num-1, using, to, from) First, let's take a look at the basic idea. If you want to solve the 8 disk tower, move 7 disks (that's n-1) to the "not the to" peg, move the last disk (that's the print statement) to the to peg, and move the 7 disks to the "to" peg. Some people will start with num=8 and build a big execution tree and I think that way leads to confusion. Let's start at the bottom. Do you agree that this works if num=0? It does... well, it does nothing at all. That's what you need to do with 0 disks, so I guess it works. Great. File in your head "This code works when num=0". What about when num=1? We want to move the disk from a to c using b. First thing we do is call solveTower(0, a, c, b) this function... stop right there. We don't evaluate this function. Why? Because we have already established that it does the right thing with 0 disks. It just does. So trace through the rest of the code. Do you agree that this function works when num=1? Good, I hope so. Now consider when n=2 (again, moving from a to c using b). The first thing we do is call solveTower(1, a, c, b). Do we evaluate that function? Nope. We have already done the work with this. We know that this correctly moves one peg from a to c using b. We'll just take that as given. Trace through the rest of it. At this point you should determine that this function works when num=2. Now GIVEN THAT THIS FUNCTION WORKS WHEN NUM=2, does it work when num=3? Try it! Don't evaluate the recursive calls, just accept that they do the thing you already know that they do. You've already shown that solveTower(2, whatever, whocares, idontknow) does the right thing. That's done. Assume it works and see if the num=3 solution works. Does that help?
🌐
GeeksforGeeks
geeksforgeeks.org › java › recursion-in-java
Recursion in Java - GeeksforGeeks
July 11, 2025 - The classic example of recursion is the computation of the factorial of a number. The factorial of a number N is the product of all the numbers between 1 and N. The below-given code computes the factorial of the numbers: 3, 4, and 5. ... // ...
🌐
Baeldung
baeldung.com › home › java › core java › recursion in java
Recursion in Java | Baeldung
January 2, 2026 - Here our input is n. Thinking in a recursive way, we can calculate (n-1)-th power of 10 first, and multiply the result by 10. Then, to calculate the (n-1)-th power of 10 will be the (n-2)-th power of 10 and multiply that result by 10, and so on.
🌐
Princeton CS
introcs.cs.princeton.edu › java › 23recursion
2.3 Recursion
For example, the gcd(102, 68) = 34. We can efficiently compute the gcd using the following property, which holds for positive integers p and q: If p > q, the gcd of p and q is the same as the gcd of q and p % q. The static method gcd() in Euclid.java is a compact recursive function whose reduction ...
🌐
JavaTutorOnline
javatutoronline.com › home › recursion in java example program | understanding java recursion
Recursion in Java Example Program | Understanding Java Recursion
December 21, 2024 - In this tutorial we will see how to do recursion in java, and also see examples of recursion using java.
Find elsewhere
🌐
w3resource
w3resource.com › java-exercises › recursive › index.php
Java Recursive Methods: Exercises, Practice, Solution
May 14, 2025 - Write a Java recursive method to calculate the sum of all numbers from 1 to n.
🌐
CodingBat
codingbat.com › java › Recursion-1
CodingBat Java Recursion-1
Recursion strategy: first test for one or two base cases that are so simple, the answer can be returned immediately. Otherwise, make a recursive a call for a smaller case (that is, a case which is a step towards the base case). Assume that the recursive call works correctly, and fix up what it returns to make the answer. Java Example Solution Code ·
Top answer
1 of 6
1

A recursive function is a function that calls itself until it reaches a return statement, that stops it from recalling itself. Take your example, the Factorial function. Factorial is a mathematical function that returns the number multiplied by itself - 1 multiplied by itself - 2, ... multiplied by 1, example: factorial of 5 = 5! = 5x4x3x2x1 = 120. it is also equal to itself multiplied by the factorial of itself -1, which is: 5! = 5x4! Take into consideration that 0! = 1. to represent this in a Java code, you need a loop that multiplies the numbers starting from 1, and going till the number you are calculating its factorial. Further more, explaining your code, let us calculate Factorial(5): Factorial() returns an integer.

Initial Call from main(): 5 != 0, then skip the condition (n == 0); t = Factorial(5-1) = Factorial(4);

Second call from Factorial(4): 4 != 0, then skip the condition (n == 0); t = Factorial(4-1) = Factorial(3);

Third call from Factorial(3): 3 != 0, then skip the condition (n == 0); t = Factorial(3-1) = Factorial(2);

Fourth call from Factorial(2): 2 != 0, then skip the condition (n == 0); t = Factorial(2-1) = Factorial(1);

Fifth call from Factorial(1): 1 != 0, then skip the condition (n == 0); t = Factorial(1-1) = Factorial(0);

Sixth call from Factorial(0): 0 == 0, then return value 1;

First return, 1, to Fifth call (Factorial(1)): return n*t = return 1*1 = return value 1;

Second return, 1, to Fourth call (Factorial(2)): return n*t = return 2*1 = return value 2;

Third return, 2, to third call (Factorial(3)): return n*t = return 3*2 = return value 6;

Second return, 6, to second call (Factorial(4)): return n*t = return 4*6 = return value 24;

Second return, 24, to First call (Factorial(5)): return n*t = return 5*24 = return value 120;

Second return, 120, to Initial call (from main()): print(120);

Hope this helps you understand recursion.

2 of 6
1

When a call is made to another method, a stack frame is created to hold the state of the current method and it is pushed onto the stack. This is regardless of a method calling itself or another method.

When the call returns, the stack frame is popped of the stack, the state of the method is restored and execution continues in the calling method.

Recursion is when a method (directly or indirectly) calls itself. The general form of a recursive method is:

  • If a parameter meets a terminating condition, return (usually a result)
  • Else adjust parameters for the next iteration and call self

The code your teacher wrote has some style issues. It would be clearer if written like this:

static int factorial(int n) {
    if (n == 0) {
        return 1;
    } 
    return n * factorial(n - 1);
}

Eradicating the unnecessary variable t and redundant else (there is no "else" when the "if" returns - there is merely continuation of execution)

I would write it like this, eliminating the if altogether:

static int factorial(int n) {
    return n == 0 ? 1 : n * factorial(n - 1);
}
Top answer
1 of 5
10

In recursion the order of the calls is very important! You can understand better your own example when you unroll it. It will look like this:

// step 1
// flowerInVase is greater than 7, so the first thing to do is call the function again! 
// Note that the System.out.println is NOT yet reached because of the execution of the function!
// call emptyVse(7 - 1), the *stack* has *remembered* to the current value of *floweInVase* => 7
emptyVase(7); 
// step 2
emptyVase(6);
// condition is *true* yet again, so the same rules as above apply
// current *remembered* value of `floweInVase` is 6
// step 3
emptyVase(5);
// and so on ... until `flowerInVase` is 0 ... now ...

Now the stack looks like this:

emptyVase(7)
    emptyVase(6)
        emptyVase(5)
            emptyVase(4)
                emptyVase(3)
                    emptyVase(2)
                        emptyVase(1)
                            emptyVase(0) 
                                -> nothing to do, recursion is stopped.
                                -> so go back to previous 
                                -> *stack frame* which is 1
                        System.out.println(1);
                    System.out.println(2);
                System.out.println(3);
            System.out.println(4);
        System.out.println(5);
    System.out.println(6);
System.out.println(7);

In stack frame for emptyVase(1) the function execution is done, so print the current flowerInVase which is 1. Go back to the previous stack frame, every time print the currently stored variable until the last stack frame is reached.

And that is why the order is reverse! That is also why if you change the order of the print and the function execution it will look as expected.

public static void emptyVase( int flowersInVase ) {
    // if there is a flower to take from the vase
    if( flowersInVase > 0 ) {
        // print the count of flowers BEFORE one is taken!
        System.out.println(flowersInVase);
        // take one flower and put it aside
        emptyVase( flowersInVase - 1 ) ;
    } else {
           // the vase is empty, nothing to do
           System.out.println(flowersInVase);
           // print 0!
    }
}

This will produce:

7
6
5
4
3
2
1
0

The vase is actually empty, but because your condition is flowerInVase > 0, this means when the last call is made with emptyVase(0) the else part is taken and you don't print there the value of the counter. Add a print there and you will see an empty vase.

Your approach (and the example) for understanding recursion is good. I think the important thing to notice in your example is the fact, that the recursive call interrupts the current function call and starts a new one (executes the same function again), but the previous call is remembered and once the new call is done, the flow continues from where it was interrupted!

You could imagine every recursive call as a creation of a box in a box:

|-------------------------------|
|--- emptyVase(7)           --- |
|                               |
|   |--- emptyVase(6)       ---||
|   |                          ||
|   |   |--- emptyVase(5)   ---||
|   |   |                      ||
|   |   |   |... and so on     ||
|   |   |   |---emptyVase(0)---||
|   |   |   | S.out.println(0) ||
|   |   |   |------------------||
|   |   |----------------------||
|   |   System.out.println(6)  ||
|   |--------------------------||
|   System.out.println(7);     ||
|-------------------------------|

The deeper the recursion, the more boxes you have.

This is also where the problem is. Recursion is pretty expensive in terms of memory allocation and because the computers have a finite amount of memory, if the recursion creates too many boxes, the execution of the program reaches the maximum allowed count of boxes = stack frames and says stack overflow. Be aware that my explanation is a very basic one. For a thorough explanation of the so called call stack have a look at this Wikipedia article - Call stack.

2 of 5
1

Each call to emptyVase() will print a flowersInVase value , so basicly you will call System.out.println() 7 times. The first print '1' is for the last call to emptyVase(), the second one '2' is for the before last one and so again .The last one '7' is for the first call to emptyVase() witch was realy 7 flower in the vase.

🌐
Tutorialspoint
tutorialspoint.com › java › java-recursion.htm
Java - Recursion
This kind of the problems are perfect candidates to be solved using recursion. Consider the following code snippet. ... Here a fact() is method which is to return the factorial of a given natural number. Now before implementing the fact(), we should think on base conditions are well which should be as following. ... Now let's see the complete example for factorial using recursion.
🌐
Codecademy
codecademy.com › learn › java-algorithms › modules › recursion-apcs › cheatsheet
Java: Algorithms: Recursion Cheatsheet | Codecademy
This value varies depending on the complexity of the algorithm of the recursive function. For example, a recursive function of input N that is called N times will have a runtime of O(N).
🌐
Zero To Mastery
zerotomastery.io › blog › recursion-in-java
Beginner’s Guide to Recursion in Java | Zero To Mastery
April 10, 2025 - That’s why forgetting a base case or accidentally writing a recursive call that never gets closer to it causes a stack overflow. The call stack keeps growing with no end in sight, and eventually Java says, “That’s enough.”
🌐
Medium
medium.com › @AlexanderObregon › everything-you-need-to-know-about-recursion-in-java-29d30b3e3d0a
Everything You Need to Know About Recursion in Java
February 24, 2024 - Basically, the base case answers the question, “What is the simplest version of this problem?” For example, in a recursive function that computes factorials, the simplest case is the factorial of 0 or 1, both of which are defined as 1. The base ...
🌐
EDUCBA
educba.com › home › software development › software development tutorials › java tutorial › recursion in java
Recursion in Java | Examples to Solve Various Conditions of Recursion
May 13, 2024 - Here are some more examples to solve the problems using the recursion method. A set of “n” numbers is said to be in a Fibonacci sequence if number3=number1+number2, i.e. each number is a sum of its preceding two numbers.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Blogger
javarevisited.blogspot.com › 2012 › 12 › recursion-in-java-with-example-programming.html
Recursion in Java with Example – Programming Tutorial for Beginners
Recursion is very intuitive in many cases e.g. trees, graphs and other recursive data structures, for example path finding algorithms rely on recursion. The problem of stackoverflow error can also be solved by tail call optimization and many JVM language like Scala already does that. By the way, Java is shy way from recursion, even in TreeMap implementation in Java uses non-recursive approach to navigat trees.
🌐
Cburch
cburch.com › books › java › ch18-recurex › index.html
Programming via Java: Recursion examples
In this case, doing a recursive call is pointless, since the white square to be drawn is such a situation is smaller than one pixel. The full working program appears in Figure 18.4. Figure 18.4: The Sierpinski program. 1 import java.awt.*; 2 import acm.program.*; 3 import acm.graphics.*; 4 5 public class Sierpinski extends GraphicsProgram { 6 public void run() { 7 // draw black background square 8 GRect box = new GRect(20, 20, 242, 242); 9 box.setFilled(true); 10 add(box); 11 12 // recursively draw all the white squares on top 13 drawGasket(20, 20, 243); 14 } 15 16 public void drawGasket(int x
🌐
TechVidvan
techvidvan.com › tutorials › recursion-in-java
Recursion in Java - TechVidvan
January 4, 2024 - The computation of the factorial of a number is a classic example of recursion. All the numbers between 1 and N form the factorial of the number N.