Loading...

Java Recursion

Write a method named down that takes one int named n. If n is 0 or less, stop with a bare return;. Otherwise print n, then call down(n - 1) from inside the same method. From main call down(3);. The screen should show three lines: 3, then 2, then 1. The method keeps calling itself with a smaller number until the stop ends the chain. That self-call with a stop is what this page teaches.

A method that calls itself

On the scope page, mark ran once and finished. Here down runs, then starts another down with a new argument before the first call is fully done. Each call has its own n. The chain only ends when a call hits the stop.
Create a small program file named Ladder.java. The public class on the first line must match the file name: public class Ladder. Do not leave an older Gate or Sign class name in this file; the compiler expects the class name and the file name to agree.
Outside main, still inside the class braces, write static void down(int n). Keep void on this page: each step prints, and nothing needs to come back through a typed return value. The stop uses return; with no value — that only ends this call. Save the file before you compile. The full first program is in the next box.

Ladder.java with down

This is the version you compile first. main holds one call. down holds the stop, the print, and the self-call.

down prints then calls itself

java
public class Ladder {
    public static void main(String[] args) {
        down(3);
    }

    static void down(int n) {
        if (n <= 0) {
            return;
        }
        System.out.println(n);
        down(n - 1);
    }
}

From the folder that holds Ladder.java, run javac Ladder.java. When parentheses, braces, and semicolons match, javac writes no line of its own. Then run java Ladder — not java Ladder.java. Leave the .java ending off the second command. The same two commands work on Windows and on macOS. The program should print three lines and stop: 3, then 2, then 1. It should not ask you to type. If the terminal waits for keyboard input, a nextLine call from an older exercise is still in the file. Delete that call and keep down(3); plus the down method above.
Walk the run once in order. Java starts at main. The call down(3) enters with n equal to 3. That is greater than 0, so the method prints 3, then calls down(2). That second call prints 2, then calls down(1). That third call prints 1, then calls down(0). The call with 0 hits n <= 0 and returns without printing. The chain ends. The screen keeps the three printed lines.
Each of those calls is a separate pass through the same method text. The first pass still has work waiting after it starts down(2) — namely finishing after the inner call returns. You do not write four different method names. You write one method and let the smaller argument carry the progress toward the stop.
If you change the start to down(2);, the screen should show 2 then 1. The method body stays the same; only the first argument changes, so the chain is shorter. Starting at down(4); should show four lines: 4, 3, 2, 1. Again the body is unchanged; only main picks the first value.

Put the stop first

The stop must be checked before the print and before the self-call. If you print first and never test n, or if you always call down(n) with the same value, the program does not finish. Keep the if (n <= 0) block at the top of the method on this beginner shape.

stop checked before print

java
public class Ladder {
    public static void main(String[] args) {
        down(2);
    }

    static void down(int n) {
        if (n <= 0) {
            return;
        }
        System.out.println(n);
        down(n - 1);
    }
}

Compile and run again: javac Ladder.java, then java Ladder. The screen shows 2 then 1. The stop still ends the chain when n reaches 0. Writing down(n) instead of down(n - 1) sends the same number again and again. Then the program may run until the system stops it. The smaller argument is part of the idea: each call must move toward the stop.
Think of the stop as the exit door. The print is the work you do on this step. The self-call is the next step. If the door is missing, every step opens another step with no end. If the next step uses the same n, you never walk toward the door. Both mistakes look different in the source, but both refuse to finish cleanly on this beginner shape.

Call chain beside the screen

Read one starter call beside the lines it produces. Each row is one visit to down that still prints.

📊 down call chain for down(3)

Call Value of n Screen line
first down(3) 3 3
then down(2) 2 2
then down(1) 1 1
then down(0) 0 (no line — stop)

A common mix-up is leaving out the stop. Then every call prints and calls again forever. Another mix-up is printing after the recursive call instead of before it. On this page the print comes first, so the screen counts down. If you move println below down(n - 1), the order of lines changes — keep the print above the self-call for the countdown shown here.
Scope from the previous page still matters in a small way: each call’s n is that call’s own parameter. The outer call’s n does not rewrite itself when the inner call runs. The inner call has a separate n. When the inner call returns, the outer call continues from the line after the self-call — and on this page that is simply the end of the method.
A leftover Gate demo with mark(4) can sit in the same file and confuse the screen if main still calls mark. Clear main down to down(3); or down(2); while you learn this page. Do not nest down inside main’s braces. Methods sit inside the class, next to main.
Writing System.out.println("down"); in main prints the word down. It does not start the chain. Keep down(3); when you want the three countdown lines.

One more shape: stop prints nothing

You already saw that the call with 0 returns quietly. You can also practice a start value of 1. The screen should show a single line: 1. Then the next call is down(0), which stops.

down starting at one

java
public class Ladder {
    public static void main(String[] args) {
        down(1);
    }

    static void down(int n) {
        if (n <= 0) {
            return;
        }
        System.out.println(n);
        down(n - 1);
    }
}

After javac Ladder.java and java Ladder, the screen shows one line: 1. The same method body covers down(3), down(2), and down(1). Only the first argument in main changes. That is enough for this beginner page. Deeper ideas like returning a sum from recursion wait for later courses; here the goal is the self-call, the smaller argument, and the stop.
If the screen shows nothing at all, check whether main still calls something else, or whether the stop test is wrong — for example if (n >= 0) would stop before any print when you start with a positive n. Keep n <= 0 as the quiet exit, and keep a positive starter in main so at least one line can appear.

Before classes

You can write down(int n), stop when n is 0 or less, print n, then call down(n - 1). From main, one call starts the whole chain. The screen shows the countdown lines. A method that never moves toward the stop does not finish. The next page is classes, where you begin building types with fields beyond these static method pages.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
5
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top