According to the answer given in the evaluation this method, if called with a very big integer, will throw StackOverflowError. I understand the concept that stands beyond that but I was wondering if we will always get the StackOverflowError?
I mean does the JVM has some fixed amount of memory reserved or it is dependant of the system? Can we theoretically, having lots of memory and operating system ready to give it to the JVM, finish to perform this method without StackOverflowError? [ May 11, 2008: Message edited by: Ismael Upright ]
Have you tried testing this out on your own machine to see at what size Integer you get a StackOverflowError (note: it's and Error, not an Exception)?
You can use the -Xoss (Java stack size) and -Xss (native stack size) parameters to increase the JVM's stack size, but this has other implications. Usually, when you find your code generates a StackOverflowError, you will want to figure out how to reduce the depth of your recursion to eliminate the problem that way.
Of course, well before you get the StackOverflowError, the code as written will return an invalid answer.
There will always be people who are ahead of the curve, and people who are behind the curve. But knowledge moves the curve. --Bill James
Joined: Feb 15, 2007
Sorry for my mistake, it's error, not exception...
I was thinking about the following situation: assume that we run this method for Integer.MAX_VALUE. Is there ANY chance that this code will not throw StackOverflowError on ANY theoretical machine?
And my second question: does the JVM has some fixed amount of memory reserved to run independenty of the operating system?
1: It's a very theoretical question, and the answer most likely depends on the implementation of the JVM. Ofcourse someone could make a JVM that uses a really large stack that could execute this method for Integer.MAX_VALUE without going out of stack space.
2. It depends on the implementation of the JVM that you are using, but Sun's JVM running on PCs does not allocate more memory than it needs, and allocates more if needed.