## Timing Code Execution in Java

Here’s a method for calculating the nth Fibonacci number, written in Java.

``` static int fibN(int n) { if(n <= 1) { return n; } else { return fibN(n-1) + fibN(n-2); } } ```

This method is great for demonstrating recursion but it’s terribly inefficient for the task at hand. A more efficient method of computing the nth Fibonacci sequence would be to literally count from the first to the nth sequence number. To demonstrate this, I’ll be timing the code execution of both the method above, fibN(), and the method below, fibN2().

``` static int fibN2(int n) { int current = 1; int previous = 0; int next = 1; int temp = 0; for(int i = 1; i < n; i++ ) { temp = current; next = previous+current; current = next; previous = temp; } return next; } ```
I’ll be using Java’s

`System.nanoTime()` to time this code. Each method will be called from within a loop 45 times, the nanoTime() being noted before the loop starts and when the loop ends in order to calculate execution time. Remember, end time minus start time equals duration. So, here’s the full class for this process:

``` class Fib { static long startTime = 0; static long endTime = 0; static long duration = 0; static long duration2 = 0; public static void main(String[] args) { System.out.println("Recursive: "); startTime = System.nanoTime(); for(int i=1; i <= 45; i++) System.out.println(fibN(i)); endTime = System.nanoTime(); duration = (endTime - startTime); System.out.println("execution took " + duration + " nanoseconds"); System.out.println("Non-Recursive: "); startTime = System.nanoTime(); for(int i=1; i <= 45; i++) System.out.println(fibN2(i)); endTime = System.nanoTime(); duration2 = (endTime - startTime); System.out.println("execution took " + duration2 + " nanoseconds"); System.out.println(duration + " vs \n" + duration2); } static int fibN(int n) { if(n <= 1) { return n; } else { return fibN(n-1) + fibN(n-2); } } static int fibN2(int n) { int current = 1; int previous = 0; int next = 1; int temp = 0; for(int i = 1; i < n; i++ ) { temp = current; next = previous+current; current = next; previous = temp; } return next; } } ``` This image shows the result of this code. As you can see, fibN2() is considerably faster than fibN(), thus proving that it’s much more efficient to count up to the nth Fib number than it is to use recursion to find the nth number.

A final note, nanoseconds are pretty rubbish to work with to be honest. At least, in this example. So change

`System.nanoTime()`
to

`System.currentTimeMillis()`

instead to time the processes in milliseconds. This will give a more friendly result.

## Creating jar file with MySQL JDBC Connector

So after trying to make a simpler method of executing some Java code that depends on MySQL JDBC drivers via CLI I came up with this solution. It basically involves 3 stages:

1. Extract contents of MySQL JDBC connector (mysql-connector-java-5.1.28-bin.jar in this example)
2. Create a manifest file and compile your Java files
3. Package them all up nice and neatly into your very own jar

These steps assume you are in the correct directory with the required file(s) present when executing commands.

##### 1. To extract the contents of the mysql-connector-java-5.1.28-bin.jar file you execute the following command:-

jar xf mysql-connector-java-5.1.28-bin.jar

This will put all the contents of the jar file in the current directory. This includes 3 directories (META-INFcom and org)

##### 2. Create a manifest.txt file and compile your Java file(s).

The manifest just needs to include the main class of your program for this objective and will be written like so: ‘Main-Class: mainClass’ where you replace mainClass with the class name of your program containing the main() method (if you have a Java file called Dinosaur.java, you replace mainClass with Dinosaur).

###### a. Create the manifest file:-

echo Main-Class: Dinosaur>manifest.txt

javac *.java

##### 3. Finally, you need to put it all back together again in one big box …or jar

jar cvfm jarName.jar manifest.txt *.class META-INF com org

This will add all of the contents extracted from the MySQL JDBC Driver, your manifest information and any class files that were created via stage 2b.

To run this .jar file, use this command:-

java -jar jarName.jar

###### The code I am using for database connection testing and jar creation:-
``` import java.sql.*; class className { public static void main(String[] args) throws Exception { Connection con = null; Statement st = null; ResultSet rs = null; int numberOfColumns=6; String url = "jdbc:mysql://host/database"; String user = "username"; String password = "password"; try { con = DriverManager.getConnection(url, user, password); st = con.createStatement(); rs = st.executeQuery("SELECT * FROM table"); while (rs.next()) { for(int i=1; i<numberOfColumns;i++) { System.out.print(rs.getString(i) + " "); } } } catch (SQLException ex) { System.out.println(ex); } finally { try { if (rs != null) { rs.close(); } if (st != null) { st.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.out.println(ex); } } } } ```

``` import java.io.*; import java.util.*; //class public class search { public int n,j,k,l; private ArrayList<String> fc = new ArrayList<String>(); //file content //main public static void main(String[] argz) { search s = new search(); //instance of class s.n=0; s.j=0; s.k=0; s.l=0; s.loadFile(); //load file content to ArrayList s.results(); } //ask user for path to file and load contents word by word into arraylist public void loadFile() { System.out.println("Enter path to text file for brace counting"); //ask for file path Scanner scan = new Scanner(System.in); //create scanner object to obtain file path String filename=scan.next(); //get file path and store in string var File loadedFile=null; //create null File var try { loadedFile = new File(filename); //instantiate File obj using given file path scan = new Scanner(loadedFile); //instantiate new Scanner object using File object } catch(FileNotFoundException e) //handle file not found exception { //notify user that file not found and ... System.out.println("File '"+filename+"' not found."); //...exit System.exit(0); } String newword=""; //string var to hold each word while (scan.hasNextLine ()) //while next line is available ... { String line =scan.nextLine(); //...get next line from text file //for the length of the line, go through each character to locate next word in line //and store word in the newword var for adding to the file content arraylist for (int i=0;i<line.length();i++) { //if character does not equal , ; : ? . [whitespace] [line-break] [carriage-return]... add char to newword var... if (line.charAt(i) == '(') { n++; } if (line.charAt(i) == ')') { j++; } if (line.charAt(i) == '{') { k++; } if (line.charAt(i) == '}') { l++; } else //...else store word in file content arraylist and set newword var to "" aka empty string value { } } } } private void results() { System.out.println("( found: " + n); System.out.println(") found: " + j); System.out.println("{ found: " + k); System.out.println("} found: " + l); } } ```