Java Reference
In-Depth Information
product * = i;
}
return product;
}
You can then test the method for various values with a loop:
for (int i = 0; i <= 10; i++) {
System.out.println(i + "! = " + factorial(i));
}
The loop produces the following output:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
It seems odd that the factorial method should return 1 when it is asked for 0!,
but that is actually part of the mathematical definition of the factorial function. It
returns 1 because the local variable product in the factorial method is initialized
to 1 , and the loop is never entered when the parameter n has the value 0 . So, this is
actually desirable behavior for 0!.
But what if you're asked to compute the factorial of a negative number? The method
returns the same value, 1 . The mathematical definition of factorial says that the function
is undefined for negative values of n , so it actually shouldn't even compute an answer
when n is negative. Accepting only numbers that are zero or positive is a precondition of
the method that can be described in the documentation:
// pre : n >= 0
// post: returns n factorial (n!)
Adding comments about this restriction is helpful, but what if someone calls the
factorial method with a negative value anyway? The best solution is to throw an
exception. The general syntax of the throw statement is:
throw <exception>;
 
Search WWH ::




Custom Search