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

1. Member
Join Date
Oct 2012
Posts
5
Rep Power
0

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

Hey Guys, I get the following error, when I'm trying to use the following method:

Java 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...

Java Code:
```    public long fak(int n)
{
if((n==1)||(n==0))
{ return 1;
}
else {
return (n*fak(n-1));
}
}```

2. Senior Member
Join Date
Jun 2007
Location
Bali, Indonesia
Posts
762
Rep Power
10

## 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.

3. Member
Join Date
Oct 2012
Posts
5
Rep Power
0

## 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.
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
?

4. Moderator
Join Date
Apr 2009
Posts
13,319
Rep Power
23

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

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.

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?

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•