0

The highest number that double can represent is extremely high, I thought. Though following code throws an exception. It's actually my full code.

public class Summe {
public static void main(String[] args) {
    System.out.println(summe(20000));
  }

public static double summe(double s) {
    return s == 0 ? s : s + summe(s-1); 
  }
}

Thanks for the answers so far. My question is: How can I make my code work?

ketan
  • 19,129
  • 42
  • 60
  • 98
Quatsch
  • 361
  • 1
  • 8
  • 29

2 Answers2

5

The problem here isn't the size of number a double can hold - the problem is the size of the stack. Here, you have 20K nested call to summe, which is way too much for the stack to handle, and hence, it overflows. If s were an int instead of a double, you'd have the exact same problem.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

You made too many recursive call to summe.

You should read this question carefully to get a full explanation : What is a StackOverflowError?

Community
  • 1
  • 1
ToYonos
  • 16,469
  • 2
  • 54
  • 70