# Question Regarding Error

• 03-27-2014, 04:09 AM
AlexGraal
Question Regarding Error
The code:
Code:

```public boolean makeBricks(int small, int big, int goal) {   if(goal == 0) return true;   if(small > 0 && big > 0) {   return makeBricks(small - 1, big, goal - 1) || makeBricks(small, big - 1, goal - 5);   }   if(small > 0)   return makeBricks(small - 1, big, goal - 1);   if(big > 0) return makeBricks(small, big - 1, goal - 5);   return false; }```

Input of this:
makeBricks(1000000, 1000, 1000100)

gives me Exception:java.lang.StackOverflowError (line number:4)

Input of this:
makeBricks(2, 1000000, 100003)

gives me Exception:java.lang.StackOverflowError (line number:8)

I've been working with Python recently, so I decided to grab some easy recursion stuff from codingbat to maintain my java knowledge.

Why am I getting these errors? As far as I understand, its because the numbers are simply too big? It works on all smaller inputs.
• 03-27-2014, 05:37 AM
thesloth
Re: Question Regarding Error
The total amount of stuff on the stack exceeds that default value, so you get that error.

let consider the case: makeBricks(1000000, 1000, 1000100)
from line 4, it will call makeBricks(999999, 1000, 1000099) and makeBricks(1000000,999, 1000095)
inside they will both call another two makeBricks
then numbers of call will be 1+2^2
So, the class will call at least 2^1000times to reach one end makeBricks(?,0,?)
But it is not the final end of the program and the class will still go on and go on.......

therefore you better edit your program to reduce the number of the calling-class loop

This is only my view, so correct me if i am wrong
• 03-27-2014, 04:29 PM
jashburn
Re: Question Regarding Error
This is a great question that deserves further study. The (very) short answer is big numbers cause the method calls to recurse too deeply exceeding the size of the call stack. See StackOverflowError (Java Platform SE 7 ) for the official one-liner on this error.

The relationship between recursion and the call stack is well-described in Part I of this article: Data Structures: Recursion, Stacks, And Trees - Java Tutorials | Dream.In.Code.

There's recursion, and there's recursion. See Java Recursion with examples on the different types of recursion. Some programming languages perform tail recursion optimisation/elimination to prevent errors like this (see Tail Call Optimization) but unfortunately Java does not, nor does Python (see Neopythonic: Tail Recursion Elimination).

Finally, see Inspired by Actual Events: Diagnosing and Resolving StackOverflowError on the different ways in which StackOverflowError can occur.