Hans Müller
Hans Müller

Reputation: 33

Recursive function throws java.lang.StackOverflowError

I get the error java.lang.StackOverflowError when I try to run my code:

public class calc {
    public static void main(String[] args){
double zahl = 847362;
System.out.println( wannawoerk(zahl) );

}


public static double wannawoerk(double zahl){
    if (zahl == 1)
        return 1;
    else
        return wannawoerk(zahl - 1) + zahl;
} }

Is there any workaround for this problem? I have to use a recursive function without for, while, etc.

Upvotes: 0

Views: 1015

Answers (4)

Bathsheba
Bathsheba

Reputation: 234715

Repeated subtraction of 1 from zahl will eventually give you 1. (Floating point subtraction by an integer on integers in this range is exact: you'd only get oddities above the 53rd power of 2).

Your problem is that your JVM is probably not going to allow you that many recursive calls.

A stack depth approaching one million is really not going to end well!

Upvotes: 9

Jiri Tousek
Jiri Tousek

Reputation: 12440

If you're required to use recursion, you could increase memory available for stack: java -Xss256m YourClass - sets stack to 256MB max.

In real world, you'd most probably use a while loop for this. Or, in this case, compute it right away (you don't need recursion for the thing you are computing), but I guess that's not the point.

Upvotes: 1

Simon Jensen
Simon Jensen

Reputation: 486

This example of yours is very also illustrated in this comment! along with a few other very detailed explanations of this issue, why it happens and how to handle it.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533520

The stack is not unlimited and Java doesn't have tail call optimisation. The simplest solution is to have the method

return zahl * (zahl + 1) / 2;

Ideally you wouldn't use double instead you would write

public static long sumUpTo(int n) {
    return n * (n + 1L) / 2;
}

To make any sane optimisation you need a more realistic method.

Upvotes: 1

Related Questions