**Purpose:** Learn how to do basic mathematics in java. Learn about if statements and *loops*. Learn some more about classes and functions.

## Create the Math Examples project.

Create a new NetBeans project named "MathExamples" with main class named "Factorial". Here are the step by step instructions:- Click on the
*File*menu, then select*New Project*. - A new window will pop up. On the first page select "Java" from
*categories*, and "Java Application" from*projects*. Then click*next*. - Set
*Project Name*to "MathExamples." Select a*Project Location*and*Project Folder*. - Make sure
*Create Main Class*is checked. Enter "Factorial" into the adjacent textbox. Click*finish*. - The project should be created, and the file "Factorial.java" should open.

- Click on the
## Factorial.java

Our program "Factorial.java" will read an integer n from input, then output n!.- We will place all the code for "Factorial.java" in the main method:

We will describe the content of the main function in steps below, and then summarize at the end. Everything in statements B-E will go in the main method.`public static void main(String[] args) {...}` - We read an integer from the command line with the line:

Comments:`int n=Integer.parseInt(args[0]);`- The variable args stores an array (or list) of Strings. Writing args[0] selects the first string in the array. Hopefully, it is something like "5".
- An int is a primitive data type which stores an integer whose absolute value is less than 2 trillion or so.
- The class java.lang.Integer is a helper class for dealing with ints. In particular it has a function parseInt, which converts a String to an int.
- The integer is stored in a variable named n.

- Since n! is undefined when n is negative, we will check to see if n is negative.
If it is negative we will print an error then exit. We do this with the following code:

Comments:`if (n < 0) { System.out.println("The number (" + n + ")! is undefined because " + n + " is negative."); System.exit(0); }`- The two lines in the brackets will be exectuted exactly when n is negative.
- Adding a number has the effect of converting n to a string and then concatenating the strings.
- The line System.exit(0); terminates the program.

- Now we will compute n!. To do this, we begin by defining two new integers:

The number factorial will eventually store n!. We will iterate i from 1 to n, multiplying factorial by i each time:`int factorial=1; int i=1;`

Comments:`while (i <= n) { factorial = factorial * i; i = i+1; }`- When the program reaches a while statement, it immediately checks to see if the expressions enclosed in parentheses is true. If it is true, then it executes the statements enclosed in the brackets {...}. Otherwise, the program continues to the next statement after the brackets.
- Whenever the program reaches the end of the statements in the brackets, it again checks the expression in parenthesis. If the expression is true, it executes the statements again. Otherwise, it moves on.
- Our loop exits when i=n+1.

- Finally, we will print the result of our computation so that the user can see it. We use the following statement:

The construction ""+n takes the empty string "" and concatenates the string formed my converting the integer n to a string. Then we concatenate "! = " and factorial converted to a string. We print something like "5! = 120".`System.out.println( "" + n + "! = " + factorial);`

You can also view the whole file with comments here: Factorial.java.`public static void main(String[] args) { int n=Integer.parseInt(args[0]); if ( n < 0) { System.out.println("The number (" + n + ")! is undefined because " + n + " is negative."); System.exit(0); } int factorial=1; int i=1; while (i <=n ) { factorial = factorial * i; i = i+1; } System.out.println( "" + n + "! = " + factorial); }`- We will place all the code for "Factorial.java" in the main method:
## Running Factorial.java

## Running via NetBeans:

- Using the menus select "Run > Set Main Project > MathExamples."
- If you naively click menus "Run > Run Main Project", you get an error because there are no command line arguments by default.

- To solve this select menus "File > Project Properties". A window will pop up. Select "Run" from "Categories." Enter a number like "5" under arguments. The window should look like:

- Now "Run > Run Main Project" should work.

## Running on the command line:

- From the NetBeans menu select "Run > Clean and Build Main Project."
- Now if you open a terminal and go to the "dist" folder of your NetBeans project, there should be a file named "MathExamples.jar".
- Run the java program using the command:
java -jar MathExamples.jar 10The "10" here is the command line argument. The output should be:10! = 3628800

## Exp.java.

We will make a new program "Exp.java." The program will read a real number x from the command line. Then it will compute an approximation of exp(x).## Steps to create the file "Exp.java":

- Switch to the Projects tab in the top left subwindow of netbeans.
- Make sure "MathExamples > Source Packages > <default package>" is open. See the screen shot at right.
- Right click on "<default package>", then select "New > Java Class".
- A new window will pop up. Set "Class Name" to "Exp". Then click "Finish".
- A source code subwindow should open labeled "Exp.java".

## The factorial method.

Inside the "Exp" class we will create a factorial method of the form:

The function takes as input the integer n. (Input is in parentheses). The int after static indicates that the function will return an int. The complete function is given by:`public static int factorial(int n) {...}`

The only new aspect of this code is that we used a for loop rather than a while loop. In the parentheses after the for loop, there are three expressions: The first, int i=1, is run when the loop begins, and creates an integer i with value 1. The second expression i<=n returns true or false. This has the same purpose as the expression in the while loop; the statements in brackets { ... } will be evaluated so long as this expression is true. The third expression i++ is evaluated after the statements in brackets, whenever they are evaluated. The expression i++ is equivalent to i=i+1. So a for loop is just a compact form of the while loop.`public static int factorial(int n) { int factorial=1; for (int i=1; i<=n; i++) { factorial=factorial * i; } return factorial; }`## The power method.

We will also create another function:

This function takes two inputs, a double named x and an int named n, which we assume is non-negative. A double stores an approximation of a real number. The function will also return a real number. The number returned will be x`public static double power(double x, int n) {...}`^{n}. The code for this follows:

You should be able to figure out how the function returns x`public static double power(double x, int n) { double ret=1.0; for (int i=1; i<=n; i++) { ret = ret * x; } return ret; }`^{n}.## The main method.

Recall that our goal was to evaluate exp(x). We will do this in our main method.Our method will do the following. It will read a real number x from input, then it will output exp(x). We use the Taylor series for exp(x):

exp(x)=1+x+x^{2}/2+x^{3}/6+...+x^{n}/n!+….The source code for our main function is given below:

Comments:`public static void main(String[] args) { double x=Double.parseDouble(args[0]); double sum=0; for (int i=0; i<15; i++) { sum=sum+power(x,i)/factorial(i); } System.out.println("exp("+x+") = "+sum); System.out.println("A second opinion: exp("+x+") = "+Math.exp(x)); }`- Double is a helper class for doubles. The parseDouble function converts a string to a double.
- We call our factorial and power functions repeatedly in the loop.
- Java has a class java.lang.Math class which implements many mathematical functions including exp.

## Running Exp.java

## Running via NetBeans.

Steps to run the program in NetBeans:- Select menus "File > Project Properties". A window will pop up. Select "Run" from "Categories."
- To the right of "Configuration" click "New". Enter "Exp" as the "Configuration Name" and click okay.
- Now with "Exp" selected next to configuration, enter "Exp" for the Main class (you can use the browse button if you want) and enter "1" under arguments.
- This window should look as on the right. Click okay to close the window.
- Run the program with the menus "Run > Run Main Project," or simply press F6.

## Running on the command line.

- From the NetBeans menu select "Run > Clean and Build Main Project."
- Now if you open a terminal and go to the "dist" folder of your NetBeans project, there should be a file named "MathExamples.jar".
- Run the java program using the command:
java -jar MathExamples.jar 1
- Because the program "Factorial.java" is also included in the jar, you can also run this program. Do so with the command:
java -cp MathExamples.jar Factorial 7

## Limits on primitive types.

- The types "int" and "double" store numbers which take up a fixed amount of size on the computer, and so can not store numbers of arbitrary size. For instance, if we run our Factorial program with argument "20", then our program reports "20! = -2102132736." A negative number!
- Fortunately, Java has a built in class java.math.BigInteger to work with integers of arbitrary size.
- We will demonstrate the BigInteger class by writing a factorial program using it.
- Java also has a built in class, java.math.BigDecimal, which does arbitrary precision arithmetic.

## BigFactorial Example

- Create a java class in the MathExamples project named "BigFactorial". (Follow the directions used for the class Exp, if you forgot how.)
- Open "BigFactorial.java" for editing.
- Because we want to use the BigInteger class, we need to add the following line:
`import java.math.BigInteger;`import java.math.BigInteger;This line must appear somewhere above the class definition (public class BigFactorial {...}). - Inside the BigFactorial class add the following method:
`public static BigInteger factorial(int n) { BigInteger factorial=BigInteger.valueOf(1); for (int i=1; i<=n; i++) { factorial=factorial.multiply(BigInteger.valueOf(i)); } return factorial; }` - The API (Application Programming Interface) specification is a very useful resource. You can view the documentation for BigInteger here. We are using only two functions from the BigInteger class and they are well documented: Learn to read and understand the API. Once you can do this, you can teach yourself java!
- From the API, we see the method declaration for valueOf is:

Comments on the method declaration:`public static BigInteger valueOf(long val)`- The declaration has two modifiers:
- The word public just means that we can call the function.
- The word static means that to call the function we refer directly to BigInteger, e.g. BigInteger.valueOf(7).

- The word BigInteger indicates the return type; the function will return a BigInteger.
- The word valueOf indicates the name of the function.
- The stuff in the parentheses is the parameter list. This method takes one parameter of type long. The long type is a primitive data type which stores an integer, which can be slightly bigger than an int. An int can be converted directly to a long, and so this function can be called with an int as well.

- The declaration has two modifiers:
- From the API, we see the method declaration for multiply is:

The absence of the modifier static means that to call the function you need to use an object to call it. In our code, we use:`public BigInteger multiply(BigInteger val)`

Here, factorial is an object of class BigInteger. We use it to call multiply with parameter BigInteger.valueOf(i), which is a newly constructed BigInteger with the same value as i. The function will return the product of the two BigInteger objects involved.`factorial.multiply(BigInteger.valueOf(i))` - Our main method will be:

This code simply converts the first argument to an integer, then prints the result returned from the factorial method.`public static void main(String[] args) { int n=Integer.parseInt(args[0]); System.out.println(""+n+"! = "+factorial(n)); }` - You can run this program by following the instructions used to run "Exp.java".
- Complete source code for BigFactorial.java without comments:

You can see the commented source code here: BigFactorial.java.`import java.math.BigInteger; public class BigFactorial { public static BigInteger factorial(int n) { BigInteger factorial=BigInteger.valueOf(1); for (int i=1; i<=n; i++) { factorial=factorial.multiply(BigInteger.valueOf(i)); } return factorial; } public static void main(String[] args) { int n=Integer.parseInt(args[0]); System.out.println(""+n+"! = "+factorial(n)); } }`

- Parts of the Oracle's Java Tutorial:
- Discussion of primitive types.
- Discussion of methods.
- Arrays: in case you want to do more with the argument array passed to the main method.

- Portions of the Java API:
- java.lang.Math API: This class comes with many commonly used mathematical functions such as trigonometric functions, for instance.
- java.math.BigInteger API: Handles arbitrarily large integers.
- java.math.BigDecimal API. Handles arbitrary precision floating point arithmetic.