0

I'm making a class that implements the java Math class and I'm overwriting the add method with a recursive one. I thought my method was pure tail recursive and wouldn't throw a stackoverflow, but I can't add 10000 and 10000 without throwing that.

public int add(int a, int b) {
    if (b == 0)
        return a;
    return add(increase(a), decrease(b));
}

And the increase and decrease methods simply take in the number, add/subtract 1, and return the result. I don't think this should be creating any stack, as the method does not have to wait on any calculations from successive calls to finish. But I'm apparently wrong. Any ideas?

fiveandten
  • 61
  • 1
  • 10
  • possible duplicate of [Does the JVM prevent tail call optimizations?](http://stackoverflow.com/questions/105834/does-the-jvm-prevent-tail-call-optimizations) – Jason C Apr 14 '14 at 05:06
  • While that post is old, it is still accurate (and [it never made it into Java 8, either](http://mail.openjdk.java.net/pipermail/mlvm-dev/2010-October/002016.html)). See also http://stackoverflow.com/questions/3616483/why-does-the-jvm-still-not-support-tail-call-optimization – Jason C Apr 14 '14 at 05:13

1 Answers1

0

The Java compiler does not support tail call optimization. See this question and this question for details.

Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • Thanks. I saw several things online saying that Java does not support tail call optimization, but my professor insists that we should not be getting any stack overflows with any valid positive integer calculations. He's even mentioned in class that Java does not support optimization, so I don't know if we're supposed to somehow change the entire functioning of Java or what haha – fiveandten Apr 14 '14 at 05:48
  • Did he require you to use tail recursion and to use Java? – merlin2011 Apr 14 '14 at 05:51
  • Java and recursion are required. Tail recursion was strongly suggested. – fiveandten Apr 14 '14 at 06:06