Search code examples
javatail-recursionstack-overflowtail-call-optimization

I get a StackOverFlowException on this code because my JVM doesn't support tail call optimizaion, right?


I get a StackOverflowException on this Java method:

private static final Integer[] populate(final Integer[] array, final int length, final int current) {

    if (current == length) {
        return array;
    } else {
        array[current] = TR.random.nextInt();
        System.out.println(array[current]);
        return populate(array, length, current + 1);
    }
}

I'm playing with tail call recursion so I guess this is what happens when the JVM doesn't short circuit the stack right?


Solution

  • No JVM that I'm aware of supports tail call optimization. This is not an oversight. Apparently this optimization has significant consequences for Java reflection and Java security managers.

    References: