The factorial of an integer is the product of that
number and all of the positive integers smaller than it. Thus the
factorial of 5, written 5!
, is the
product of 5*4*3*2*1
, or 120. Example 1-7 shows a class, Factorial
, that contains a method, factorial( )
, that computes factorials. This
class is not a program in its own right, but the method it defines can
be used by other programs. The method itself is quite simple; we’ll
see several variations of it in the following sections. As an
exercise, you might think about how you could rewrite this example
using a while
loop instead of a
for
loop.
Example 1-7. Factorial.java
package je3.basics; /** * This class doesn't define a main( ) method, so it isn't a program by itself. * It does define a useful method that we can use in other programs, though. **/ public class Factorial { /** Compute and return x!, the factorial of x */ public static int factorial(int x) { if (x < 0) throw new IllegalArgumentException("x must be >= 0"); int fact = 1; for(int i = 2; i <= x; i++) // loop fact *= i; // shorthand for: fact = fact * i; return fact; } }
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.