You are on page 1of 47

Electrical Engineering Technology

400 Commercial Street, Manchester, NH 03101

ET601 Data Structures and Databases


Department: EET Credits: 4

Course Pre-requisite: NHTI CP235 Algorithms with OOP Intermediate Java or C# skills. (Intermediate C++ with OOP with permission ) Instructor: M. Saleem Yusuf Phone: Home (603) 424-8147

Email:

MSaleemYusuf@Yahoo.com , mohammad.yusuf@uhh.edu

Website: http://www.corlyn.com Classes meet: On Mondays, 8/30/2010 to 12/13/2010. No class on Labor day 9/6
UNH-M / NHTI - Professor Yusuf

Text Books
Required Textbook Data Structures
Data Structures and Algorithms in Java Second Edition by Robert Lafore. ISBN: 0-672-32453-9. Publisher: Sams Suggested Reference Texts For Database, I recommend, although I will not be using it in the class Mastering SQL Server 2008 , Sybex, 2009. OR

Mastering SQL Server 2005, Gunderloy, Jorden, Tschanz. ISBN 07821-4380-6. Publisher Sybex/Wiley.
It will make a big difference if you have you a C# and a Java programming textbook from the classes you have taken before. I prefer the Deitel textbooks for teaching.

UNH-M / NHTI - Professor Yusuf

Pre-requisite
Pre-requisite
NHTI CP235 Algorithms with OOP CP235 at NHTI in Concord covers first 250 pages of the current text (Data Structures & Algorithms in Java by Robert Lafore) Intermediate Java or C# skills. (Intermediate C++ with OOP experience acceptable as there will be sample model programs for transition to Java.)

UNH-M / NHTI - Professor Yusuf

Syllabus
Read the following. It is in the syllabus document
School Policies Grading Policy Late work Absences Academic honesty Disruptive behavior Disabilities Class Cancellation

Class Schedule
Subject to change. On my website (http://www.corlyn.com).

UNH-M / NHTI - Professor Yusuf

Agenda
In this course
We will use both Java and C# programming languages in this class Review fundamental container classes; stacks, queues and link lists Learn more advanced data structures and concepts Use of sorting and searching algorithms, iterators and efficiency indicators Use the built-in data structures provided by .NET Framework Class Library and Java libraries Design, Development and use of relational databases
5

UNH-M / NHTI - Professor Yusuf

Review and Getting Started Brief Review


Java Fundamentals or C# Fundamentals Arrays Simple Searching and Sorting Techniques Stacks Queues and Priority Queues Linked Lists

UNH-M / NHTI - Professor Yusuf

Getting Started Download software Download Java Development Environment


See links on the last page Java SE 6 Documentation Java JDK 6 Update 7 http://java.sun.com/javase/index.jsp http://java.sun.com/javase/6/ http://java.sun.com/products/jdk/faq.html#A (FAQ) JDK consists of executables that allow you to compile and run your Java program or applet. It also contains the Java Runtime Environment (Java Virtual Machine) and the standard class libraries

UNH-M / NHTI - Professor Yusuf

Getting Started Set Environment variables


Set Environment Variables. See Examples below. If you install java, use the path where the software is installed. If move JDK to a new location, it will not work. It remembers the path where it was originally installed
JAVA_HOME=E:\Program Files\Java\jdk1.6.0_03 JAVA_PATH=E:\Program Files\Java\jdk1.6.0_03\bin Include E:\Program Files\Java\jdk1.6.0_03\bin in your PATH variable. This allows you to access the Java executables from any folder on your computer without typing the fully qualified path.

Set the CLASSPATH variable to include classes and JAR files you will be using. Example:
CLASSPATH=.;E:\Program Files\Java\jdk1.6.0_03\LIB;C:\mysqlconnector-java-5.0.8\mysql-connector-java-5.0.8-bin.jar

UNH-M / NHTI - Professor Yusuf

Java Development Environment


Download
Eclipse Integrated Development Environment Required for this course and it is free
http://eclipse.org

TextPad (Not required) Not free, but allows you to use it for a while. Excellent editor and you can compile and run your program from the TextPad. If you plan to use it for long term, I recommend that you buy it. http://www.textpad.com/ Notepad++ An awesome editor and it is free (Not required). Highlights the code, but I dont think you can compile or run Java code from it. Highly recommended.
http://sourceforge.net/projects/notepad-plus/
UNH-M / NHTI - Professor Yusuf

C# Development Environment
NHTI Students
For Software Development with C#, Download the following software. Contact Professor Sterling Hough. All NHTI Students can get a student copy of
Windows XP Professional Visual Studio 2010 SQL Server 2008 Developer Edition

Your MSDNAA Online Software System can be found at:


http://msdn03.e-academy.com/nhti_cet

All Students
For Software Development with C#, Download
Visual Studio 2010, C# Express version SQL Server 2008, Express version Find tutorial or learning videos on Microsofts site. They are great. Download MySql if you plan to use it. Works very well with Java If you plan to use MySql, download Toad for MySQL. It is excellent and free http://www.quest.com/toad-for-mysql/

UNH-M / NHTI - Professor Yusuf

10

A Quick Into to Java


Java Application
An application that is developed using Java Programming Language. It is platform independent and requires a platform specific Java Virtual Machine (JVM) JVM interprets the code and executes it Syntax is similar C++ but there are significant improvements in Java C# syntax is very similar to Java, but there are significant improvements in C# In Java and C#, everything (code and data) is inside a class Class name must be same as filename plus .java extension The main method must be public; JVM have access to it It must also be static so JVM does not have to instantiated before it can be used public static void main( String args[] )
UNH-M / NHTI - Professor Yusuf

11

Simple Java Example Program


// HelloWorld.java - Shows three types of comments /* All java programs start with "class className */ /** ClassName must also be the file - ClassName.java used for creating help document */ public class HelloWorld { // main method begins execution of Java application public static void main( String args[] ) { System.out.print( "Hello " ); System.out.println( "World" ); } // End of method main } // End of class HelloWorld ======================================== Compile javac HelloWorld.java Run java HelloWorld Output Hello World
UNH-M / NHTI - Professor Yusuf

12

Java Language Review Primitive Data Types


Java has 8 Primitive (Basic) Data Types
Data Type byte char Short Int Long Float Range -128 to +127 0 to 65535 -32768 to +32767 -2,148,483,648 to 2,147,483,647 huge huge huge huge Description 1 byte integer value, same as C++ 2 bytes for Unicode char, in 1 C++ 2 bytes, signed integer, same as C++ 4 bytes, signed integer, same as C++ 8 bytes, signed integer 4 byte floating point value, same C++ 8 byte floating point value, same C++ A non-numeric value, true or false

double
boolean

UNH-M / NHTI - Professor Yusuf

13

Java Language Review Loops, Decision making


Selection structures same as C++ if (condition) statement If /else if /else switch (condition) { case : default: }

switch (Expression) { case label_1 : statements; break; case label_n: statements; break; default: statements break; }

?: (ternary operator)
max = (n1 > n2) ? n1 : n2;

UNH-M / NHTI - Professor Yusuf

14

Java Language Review Loops, Decision making


Repetition structures same as C++, except for each
while (condition) statement do statement while (condition) for loop for each loop (new in V5.0, also in C#, syntax different)

Logical, Relational and Arithmetic operations same as C++, C#


Relational Operators
&& (AND), || (OR), == (Equal), ! (Not), > (Greater than) >= (Greater than or equal to), < (Less than), <= (Less than or equal to)

UNH-M / NHTI - Professor Yusuf

15

Java Language Review Methods


Methods A method is a set of statements with a name. It is defined in a class They are like functions, subroutines or procedures of other languages, but exists only inside a class modularize programs by separating its tasks into self-contained units are reusable. Can be called repeatedly by this program and by other programs (library VS local method). prevent repeating code
Methods parameters are variables which are used to pass information to and from the method. These variables can only be accessed by this method (SCOPE OF VARIABLES) Method can return one value back. There are ways to more than one value Variables declared outside the methods but inside the class are called fields All methods can use the fields of their class

UNH-M / NHTI - Professor Yusuf

16

Methods - Examples
Example
double root = Math.sqrt (4.0) New method 'printf' in J2SE 5.0, Displays formatted data System.out.printf( "%s\n%s\n", "Welcome to", "Java Programming!" );

UNH-M / NHTI - Professor Yusuf

17

// Sphere.java - Java How To Program in, Deitel & Deitel public class Sphere { static float PI = 3.14159F; // static field int radius; // Non-static field public static void main(String[] args) { Sphere s = new Sphere(); s.radius = 6; float circum, volume; // Local vars of function main // can access static fields only circum = s.getCircum(); volume = s.getVolume(); System.out.printf("%s%d", "A sphere of radius ", s.radius); System.out.printf("%s%f", " has a circumference of ", circum); System.out.printf("%s%f%s\n", " and a volume of ", volume, "."); } // end of main float getCircum() { // can access static and non-static fields return radius * 2 * PI; } float getVolume() { float vol = (4.0F/3.0F) * PI * (float)Math.pow(radius, 3.0); return vol; } } // end of class Sphere
UNH-M / NHTI - Professor Yusuf

18

Java Language Review Static Fields and Methods


A method declared static can only use fields that are declared static A method declared static can directly call only other static methods If a method is NOT static, you cannot call that method until you create an object and then call the method of that object If multiple objects are created , each has it own copies of all nonstatic fields Static fields and static methods reside in the class itself, and are usable as soon as your program starts and the class is loaded. No need to create an object Fields are instance variables. Each instance of a class (object) has its own copy Static fields are shared by all instances of the class. No instances An object must be created (instantiated) before its non-static methods and non-static fields can be used
UNH-M / NHTI - Professor Yusuf

19

Java Language Review Access Specifiers


The scope of an object, method or class refers to it accessibility and visibility
Scope also refers to the lifetime of an object

The scope of a class member (a method or a data member) can be specified as public, protected, private or left unspecified
Public - can be used by anyone, all have access Private - can only be accessed by the member of that class. Not even the objects created from this class have access to it. Protected - Methods of subclasses and of any class in the same package have access. A member with unspecified scope is visible to any class in the same package. It has default scope (is protected, directory)

UNH-M / NHTI - Professor Yusuf

20

Java Language Review Access Specifiers


Guidelines
Make scope as restricted as possible. Fields and utility methods should be private. Create accessor and mutator (get and set) methods and make them public The scope of the class itself can be specified as public

UNH-M / NHTI - Professor Yusuf

21

Java Language Review Constructors


A constructor is a special method. It is executed when an objected is created Is used to initialize the object's data members It has the same name as the class There can be many constructors (overloaded). All must have the same name but different number or type of arguments (signature) A constructor cannot have a return type If you don't specify a constructor, a default one is created for you The new operator, followed by a constructor of the class instantiates an object of that class. Example: Employee emp1 = new Employee("Bob", "Dobbs"); A constructor can call another constructor by using the keyword this as a method name If you use it, this() must be the first statement in the constructor
UNH-M / NHTI - Professor Yusuf

22

Java Language Review Example of Constructors


class Employee { private String firstname; private String lastname; Employee(String fname, String lname) { firstname = fname; lastname = lname; }
// No arg constructor, calls constructor with 2 args

Employee() { this("J.", "Doe"); } }


UNH-M / NHTI - Professor Yusuf

23

Java Language Review Comparing Objects


You can compare primitive data types using the == operator With reference variables, the == operator compares references. It evaluates to true if both references refer to the same object (have the same address)
Employee emp1 = new Employee("Bob", "Dobbs"); Employee emp2 = emp1; // Refer to the same emp if (emp1 == emp2 ) { ... // True Employee emp1 = new Employee("Bob", "Dobbs"); Employee emp2 = new Employee("Bob", "Dobbs"); if (emp1 == emp2 ) { ... // False

UNH-M / NHTI - Professor Yusuf

24

Java Language Review Creating an Equals Method


class Employee {

-------public boolean equals(Object obj) { if (this == obj) // comparing same object, will be true return true; if ((obj != null) && (obj instanceof Employee)) { Employee e = (Employee)obj; return ( this.firstname.equals(e.firstname) && this.lastname.equals(e.lastname) && this.id == e.id ); } else { return false; }
} } Employee emp1 = new Employee("Bob", "Dobbs"); Employee emp2 = new Employee("Bob", "Dobbs"); if ( emp1.equals(emp2) ) { // will be true UNH-M / NHTI - Professor Yusuf

25

Java Language Review Destroying Objects


You never explicitly destroy objects in Java
After the last reference to an object is released, the JVM reallocates the object's memory at it's convenience The automatic "Garbage Collection" may happen immediately, or when the program terminates or some time in between The programmer has no control over when and in what order unreferenced objects are removed from memory Garbage collection cannot be forced, but may be suggested by setting the reference to an object equal to null.

UNH-M / NHTI - Professor Yusuf

26

Destroying Objects and Garbage Collection


If an object has a finalize() method, the VM will invoke it just before the object is removed from memory Don't count on how soon resources will be free after finalize Many programmers create a method call dispose, which can be called explicitly when you are through with an object
You cannot force a particular object to be garbage collected, but you can explicitly invoke the Garbage Collector: System.gc() IF THE CALL WORKS, this will garbage collect all objects which are no longer referenced. On some systems, you can log garbage collection events to a file, including the time in seconds since the first garbage collection event.

Java -Xloggc:file JavaClass

UNH-M / NHTI - Professor Yusuf

27

Java Language Review Arrays


An array represents a group of variables of the same type, accessible through a common name and an index The index must be an int value or a value of a type that can be promoted to int. That is, smaller than an int, like byte, short or char, but not long Array indexing begins with 0, and the array's length field holds the number of array elements A variable declared with brackets '[ ]' is an array reference
float salary[]; or float[] salary; salary = new float[4]; String[] sNames = {"John", "James"}; int[] age = new int[2]; StringBuffer[] phoneNumbers = new StringBuffer[2]; phoneNumbers[0] = new StringBuffer("657-3943"); phoneNumbers[1] = new StringBuffer("232-4432");
UNH-M / NHTI - Professor Yusuf

28

New feature for each in Java


public class ArrayTest { public static void main( String args[] ) { int arr[] = { 22, 23, 4, 6 }; int sum = 0;

for (int number : arr ) sum += number; System.out.printf( "Sum is: %d\n", sum );
} // end main } // end class ArrayTest

UNH-M / NHTI - Professor Yusuf

29

Java Language Review Arrays


Objects can also be stored in an array by creating an array of object (references) using the new operator An array of type Object can hold a reference to any object Object[] obj1 = new Object[2]; obj1[0] = "This an object of type string"; obj1[1] = new java.util.Date();
Employee[] emp = new Employee[2]; emp[0] = new Employee("Saleem Yusuf", 1, 1000000); emp[1] = new Employee(Jane Doe", 1, 5000000);

UNH-M / NHTI - Professor Yusuf

30

Java Language Review Multi-dimensional Arrays


Multidimensional Jagged arrays are simply arrays of arrays
Object[][] records = new Object[2][]; records[0][0] = new Object[10]; records[0][1] = new Object[20]; records[1][0] = new Object[30]; records[1][1] = new Object[40];

Can be created dynamically


3-by-4 array
int[][] b; b = new int[ 3 ][ 4 ];

Rows can have different number of columns


int b[][]; b = new int[ b[ 0 ] = new b[ 1 ] = new //same as 2 ][ ]; int[ 5 ]; int[ 3 ]; int[][] b //creates //creates //creates which is proper format; 2 rows 5 columns for row 0 3 columns for row 1 31

UNH-M / NHTI - Professor Yusuf

Java Language Review Simple Example of an Array


import java.util.Random; public class SimpleExample { public static void main( String args[] ) { Random randomNumbers = new Random(); final int SIZE = 30; int RandomArray[] = new int[ SIZE ]; // fill array with random numbers between 1 to 9999 for ( int i=0; i < SIZE; i++ ) RandomArray[i] = 1 + randomNumbers.nextInt( 9999 );

// output each array element's value for (int i=0; i < SIZE; i++ ) System.out.printf( "%4d%6d%s", i, RandomArray[i], ((i+1)%10 == 0 ? "\n" : "") ); } // end main } // end class SimpleExample

UNH-M / NHTI - Professor Yusuf

32

Java Language Review Command Line Arguments


Command-line arguments
Pass arguments from the command line
String args[]

Appears after the class name in the java command


java MyClass a b

Number of arguments passed in from the command line


args.length

First command-line argument


args[ 0 ]

Convert args to an integer from string int iVar = Integer.parseInt(args[0]);

UNH-M / NHTI - Professor Yusuf

33

Java Language Review toString() Method


toString Method
A useful method to provide in your class It is automatically called when an object is converted to a String or must be treated as a String Can be passed to print or println methods When an object is concatenated to a String using a + operator See example on the next page

UNH-M / NHTI - Professor Yusuf

34

class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } // Overloaded or custom toString() Method public String toString() { return "X=" + x + ", " + "Y=" + y; } } public class TestAppPoint { public static void main(String args[]) { Point point = new Point(10, 10); String s = "Testing Point: " + point; System.out.println(s); System.out.println(point); } }
UNH-M / NHTI - Professor Yusuf

35

Links
http://www.javabeginner.com/getting-started-java.htm

Java SE 6 Documentation Java JDK 6 Update 7


http://java.sun.com/javase/index.jsp http://java.sun.com/javase/6/ http://java.sun.com/products/jdk/faq.html#A (FAQ) http://eclipse.org

http://www.textpad.com/
http://sourceforge.net/projects/notepad-plus/

UNH-M / NHTI - Professor Yusuf

36

Java Technology Terminologies


What is the Struts Framework?
The Struts Framework is a standard for developing well-architected Web applications. It has the following features
Open source Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:
Model: application state View: presentation of data (JSP, HTML) Controller: routing of the application flow

Implements the JSP Model 2 Architecture Stores application routing information and request mapping in a single core file, struts-config.xml

The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the developer

UNH-M / NHTI - Professor Yusuf

http://exadel.com/tutorial/struts/5.2/guess/strutsintro.html

37

Java Struts Framework


Architecture Overview

UNH-M / NHTI - Professor Yusuf

http://exadel.com/tutorial/struts/5.2/guess/strutsintro.html

38

Java Struts Framework


MVC architecture
Model-View-Controller (MVC) architecture. Model represents the business or database code, the View represents the page design code, and the Controller represents the navigational code.

The Struts framework is designed to help developers create web applications that utilize a MVC architecture. The framework provides three key components:
A "request" handler provided by the application developer that is mapped to a standard URI. A "response" handler that transfers control to another resource which completes the response. A tag library that helps developers create interactive form-based applications with server pages.

The framework's architecture and tags are buzzword compliant. Struts works well with conventional REST applications and with nouveau technologies like SOAP and AJAX.
UNH-M / NHTI - Professor Yusuf

http://exadel.com/tutorial/struts/5.2/guess/strutsintro.html, oracle.com 39

Java Struts Framework


All incoming requests are intercepted by the Struts servlet controller. The Struts Configuration file struts-config.xml is used by the controller to determine the routing of the flow. This flows consists of an alternation between two transitions:
From View to Action A user clicks on a link or submits a form on an HTML or JSP page. The controller receives the request, looks up the mapping for this request, and forwards it to an action. The action in turn calls a Model layer (Business layer) service or function. After the call to an underlying function or service returns to the action class, the action forwards to a resource in the View layer and a page is displayed in a web browser.

From Action to View

UNH-M / NHTI - Professor Yusuf

http://exadel.com/tutorial/struts/5.2/guess/strutsintro.html

40

Java Struts Framework


The diagram below describes the flow in more detail:

UNH-M / NHTI - Professor Yusuf

http://exadel.com/tutorial/struts/5.2/guess/strutsintro.html

41

Java Struts Framework


User clicks on a link in an HTML page. Servlet controller receives the request, looks up mapping information in struts-config.xml, and routes to an action. Action makes a call to a Model layer service. Service makes a call to the Data layer (database) and the requested data is returned. Service returns to the action. Action forwards to a View resource (JSP page) Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP page. JSP file is invoked and sent to the browser as HTML. User is presented with a new HTML page in a web browser.

UNH-M / NHTI - Professor Yusuf

http://exadel.com/tutorial/struts/5.2/guess/strutsintro.html

42

Java Struts Framework


Struts Components
The Controller
This receives all incoming requests. Its primary function is the mapping of a request URI to an action class selecting the proper application module. It's provided by the framework.

The struts-config.xml File


This file contains all of the routing and configuration information for the Struts application. This XML file needs to be in the WEB-INF directory of the application.

Action Classes
It's the developer's responsibility to create these classes. They act as bridges between user-invoked URIs and business services. Actions process a request and return an ActionForward object that identifies the next component to invoke. They're part of the Controller layer, not the Model layer.

UNH-M / NHTI - Professor Yusuf

http://exadel.com/tutorial/struts/5.2/guess/strutsintro.html

43

Java Struts Framework


View Resources
View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files, Resource bundles, JavaBeans, and Struts JSP tags.

ActionForms
These greatly simplify user form validation by capturing user data from the HTTP request. They act as a "firewall" between forms (Web pages) and the application (actions). These components allow the validation of user input before proceeding to an Action. If the input is invalid, a page with an error can be displayed.

Model Components
The Struts Framework has no built-in support for the Model layer. Struts supports any model components:
JavaBeans EJB CORBA JDO any other
http://exadel.com/tutorial/struts/5.2/guess/strutsintro.html

UNH-M / NHTI - Professor Yusuf

44

Spring Framework
The Spring Framework is an open source application framework for the Java platform and .NET Framework.[1] The core features of the Spring Framework can be used by any Java application, but there are extensions for building web applications on top of the Java Enterprise platform. Although the Spring Framework does not impose any specific programming model, it has become popular in the Java community as an alternative to, replacement for, or even addition to the Enterprise JavaBean (EJB) model. http://en.wikipedia.org/wiki/Spring_framework

UNH-M / NHTI - Professor Yusuf

45

Enterprise JavaBeans
Enterprise JavaBeans (EJB) is a managed, server-side component architecture for modular construction of enterprise applications. The EJB specification is one of several Java APIs in the Java Platform, Enterprise Edition. EJB is a server-side model that encapsulates the business logic of an application. The EJB specification intends to provide a standard way to implement the back-end 'business' code typically found in enterprise applications (as opposed to 'front-end' interface code). Such code was frequently found to address the same types of problems, and it was found that solutions to these problems are often repeatedly re-implemented by programmers. Enterprise JavaBeans were intended to handle such common concerns as persistence, transactional integrity, and security in a standard way, leaving programmers free to concentrate on the particular problem at hand.
UNH-M / NHTI - Professor Yusuf http://en.wikipedia.org/wiki/Enterprise_JavaBean

46

Enterprise JavaBeans
Accordingly, the EJB specification details how an application server provides:
Persistence via the Java Persistence API (JPA) Transaction processing Concurrency control Events using Java Message Service Naming and directory services (JNDI) Security ( Java Cryptography Extension (JCE) and JAAS ) Deployment of software components in an application server Remote procedure calls using RMI-IIOP. Exposing business methods as Web Services.

Additionally, the Enterprise JavaBean specification defines the roles played by the EJB container and the EJBs as well as how to deploy the EJBs in a container

UNH-M / NHTI - Professor Yusuf

http://en.wikipedia.org/wiki/Enterprise_JavaBean

47

You might also like