What follows is the highlighted source code with comments. You can also download this file directly: Factorial.java.

/* * This work by W. Patrick Hooper is free of known copyright restrictions. * The work is in the public domain. * * Author's website: <a href="http://wphooper.com">http://wphooper.com</a>. */ /** Compute n! * * @author Pat Hooper */ public class Factorial { /** * Prints out n!, where n is the first command line argument. * * @param args the command line arguments */ public static void main(String[] args) { // Convert the first argument to an integer and store it as n. int n=Integer.parseInt(args[0]); if ( n < 0) { // Execute the following statements if n is negative. // When you add a number to a string, Java converts the number to a string, // and then concatenates the two strings. System.out.println("The number ("+n+")! is undefined because "+n+ " is negative."); // Print an error message. System.exit(0); // Exit the program. } // We will compute n factorial via the formula // n!=1*2*3*4*5*... int factorial=1; // create an integer named factorial and set it to one int i=1; // Create another integer with value one. while (i <=n ) { // Exectute the following two lines as long as i<=n. factorial = factorial * i; // Update factorial. i = i+1; // Increase the value of i by one. } System.out.println(""+n+"! = "+factorial); } }

- View more source code for the MathExamples project.
- Return to the Java Tutorial.

HOOPER >>>>> JAVA TUTORIAL