'Why does this Java code output "3210123"?

public static void downup(int n) {
    System.out.println(n);
    if(n>0) {
        downup(n-1);
        System.out.println(n);
    }   
}

I saw this code and do not understand why the output is 3210123 when n is 3. I can only understand that it has to be "3210". What about the rest of the output ("123")?



Solution 1:[1]

The exeuction can be visualized like this:

downup(3)
    println(3)
    downup(3-1)
        println(2)
        downup(2-1)
            println(1)
            downup(1-1)
                println(0)
                condition false, recursion stopped
                return
            println(1)
            return
        println(2)
        return
    println(3)
    return

Every time downup() is called (recursively), indentation increases. When execution returns from downup(), indentation decreases.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michel K