An Example Program
Example 1-1 shows a Java program to compute factorials.[3] Note that the numbers at the beginning of each line are not part of the program; they are there for ease of reference when we dissect the program line-by-line.
Example 1-1. Factorial.java: a program to compute factorials
1 /**
2 * This program computes the factorial of a number
3 */
4 public class Factorial { // Define a class
5 public static void main(String[] args) { // The program starts here
6 int input = Integer.parseInt(args[0]); // Get the user's input
7 double result = factorial(input); // Compute the factorial
8 System.out.println(result); // Print out the result
9 } // The main() method ends here
10
11 public static double factorial(int x) { // This method computes x!
12 if (x < 0) // Check for bad input
13 return 0.0; // If bad, return 0
14 double fact = 1.0; // Begin with an initial value
15 while(x > 1) { // Loop until x equals 1
16 fact = fact * x; // Multiply by x each time
17 x = x - 1; // And then decrement x
18 } // Jump back to start of loop
19 return fact; // Return the result
20 } // factorial() ends here
21 } // The class ends hereCompiling and Running the Program
Before we look at how the program works, we must first discuss how to run it. In order to compile and run the program, you need a Java development kit (JDK) of some sort. Sun Microsystems created the Java language and ships a free JDK for its Solaris operating system and also for Linux and Microsoft Windows platforms. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access