Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java endless recursion and StackOverflowError

Sorry, for probably a dumb question, I'm new to Java.

Is there a way to make an endless recursion in Java, somithing like:

public void sillyMethod()
{
    System.out.println(i);
    i++;
    sillyMethod();

}

it throws StackOverflowError, but I really want to run it endless. Is there any way to make it?

Thanks!

like image 236
rosx Avatar asked Apr 10 '26 08:04

rosx


1 Answers

Yes and no, (but mostly no! :)

No, it's not possible (the most sensible answer):
For every call, there will be an activation record pushed onto the JVM call stack. This takes a non-zero amount of memory, thus you will at some point run out of memory, at which point a StackOverflowException will be thrown.

Yes, it is possible (the super-theoretical answer):
There is nothing in the Java Language Specification that explicitly says that you should eventually run into a StackOverflowException. This means that if you find a cleaver enough compiler, it may be intelligent enough to compile this into a loop.


A related question would be, "Does the JVM support tail-call optimization." The answer to this question is, "no, not at moment, but it's not ruled out for future versions".

like image 143
aioobe Avatar answered Apr 11 '26 21:04

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!