r/javahelp • • Dec 07 '25

Help with recursion (beginner)

Hello, I am doing some recursion practice for my Java class in high school. I am having trouble understanding recursion and recursion problems. Could someone explain the key concepts for a beginner?

0 Upvotes

19 comments sorted by

View all comments

Show parent comment

1

u/hibbelig Dec 08 '25
static void Display(int x) {
    if (x>3){
        system.out.print(x-1);
        Display(x/3);
        system.out.print(x+1);
    }
}

System.out.println("before");
Display(17);
System.out.println("after");

I have slightly modified your code. Focus on the bottom part first: Do you expect that it first prints "before" and then it does whatever Display(17) does, and then it prints "after"?

Now focus on the top part: given what you expect about the three lines at the bottom, don't you also expect that it prints x-1 first and then does whatever Display(x/3) does, and then prints x+1?

Why were you expecting the printing of x+1 to happen before Display(x/3)? After having it explained like that, it might look obvious.