# Factorial - java.lang.stackoverflow? Where's the mistake?

• 12-03-2012, 05:06 PM
SwordMaster
Factorial - java.lang.stackoverflow? Where's the mistake?
Hey Guys, I get the following error, when I'm trying to use the following method:

Code:

```    public long fak(int n)     {         if((n==1)||(n==0))         { return 1;         }         else {             return (fak(n));         }     }```
Error:
java.lang.stackoverflowerror:
null

When I use the code like this, it works... but I don't understand why the Code on top should lead to a Loop or something similar...

Code:

```    public long fak(int n)     {         if((n==1)||(n==0))         { return 1;         }         else {             return (n*fak(n-1));         }     }```
• 12-03-2012, 05:18 PM
Re: Factorial - java.lang.stackoverflow? Where's the mistake?
As you can see in your code the recursive call to fak(n) will never stop if n != 0 or n != 1. When you do something like fak(10) it will repeating the call to fak(10) until you run out of memory. Because the value of n is never change.
• 12-03-2012, 05:28 PM
SwordMaster
Re: Factorial - java.lang.stackoverflow? Where's the mistake?
Quote:

As you can see in your code the recursive call to fak(n) will never stop if n != 0 or n != 1. When you do something like fak(10) it will repeating the call to fak(10) until you run out of memory. Because the value of n is never change.

So the "return" in my Code doesnt say "give me the Value of fak(n)" but says "jump back to fak(n)"?

And why does the upper Code returns the Value "24" when I use n=4?
4 * fak(4-1)
= 4 * 3
= 12
?
• 12-03-2012, 07:05 PM
Tolls
Re: Factorial - java.lang.stackoverflow? Where's the mistake?
Quote:

Originally Posted by SwordMaster
So the "return" in my Code doesnt say "give me the Value of fak(n)" but says "jump back to fak(n)"?

It does mean "give me the Value of fak(n)", but before it can give you that value it has to actually run fak(n), which will result in it getting to the same line, which results in another call to fak(n) to find the answer...and so on, down the rabbit hole.

Quote:

Originally Posted by SwordMaster
And why does the upper Code returns the Value "24" when I use n=4?
4 * fak(4-1)
= 4 * 3
= 12
?

And fak(4-1) does what?