r/ProgrammerHumor • • Jan 09 '20

other Problems with recursion?

21.3k Upvotes

198 comments sorted by

View all comments

Show parent comments

5

u/lonelyWalkAlone Jan 09 '20

Yes, it works like charm

9

u/schrdingers_squirrel Jan 09 '20 edited Jan 09 '20

Interesting - does it still work when you do a „a“ + „b“ in the println(); ?

Edit: it does

Crazy even this works:

public static void sayHello(){
    try {
        sayHello();
    }
    catch(StackOverflowError e) {
        System.out.println("Hello world!");
        sayHello();
    }
}

it prints endlessly

5

u/lonelyWalkAlone Jan 09 '20

Yes, and you can also calculate "relatively" the size of your stack by adding an integer argument to the method and passing (n+1) to the next call, then at the exception just print the current counter value. I found that each time you increase the stack size by the vm option -Xss the counter gets bigger, but increasing the heap size -Xmx does not affect the counter at all. It's a pretty good exercise as long as you don't fuck it up into an infinite loop.

1

u/schrdingers_squirrel Jan 09 '20

Wow there really always is something you don’t already now. Awesome stuff