ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 1 of 61
Welcome to the Training Program: Core Java, JSP & Servlets (ID:
5142 )
Brief Description This is core java training program that gives you a good head start with Java as a programming language Objectives
To get overview of Object Oriented Analysis & Design To understand java as a programming language Get aquainted with Object Oriented features in Java Learning basic packages in java for writing database applications To understand use of java in web-technologies To learn how to write Java Server Pages and Servlets
Pre-Requisites 6 months to 1 Year experience in programming (any language) is desirable. Hardware Requirements Each machine must have atleast 512 MB of RAM and 5 GB of free disk space Software Requirements Netbeans IDE will be installed by the participants during the course.Oracle 9i or above must be installed on each machine Network Requirements All the machines must be connected to the network including Trainers Machine
System Requirements & OO Modeling Chapter: 1 - Basic Concepts of OO Defining Object Technology What is Object Technology ?
Object technology is a set of principles guiding software construction together with languages, databases and other tools that support these principles
Strengths of Object Technology
A Single paradigm - A single language used by analysts, designers and implementors
Facilitates architectural and code reuse
Models more closely reflect the real world - More accurately describes corporate entities
Stability - A small change in requirements does not mean massive changes in the system under development
Resilient / Adaptive to change
Why do we model ?
We build models to better understand the system we are developing
Modeling achieves four aims. Modeling: Helps us to visualize a system as we want it to be. Permits us to specify the structure or behavior of a system Gives us a template that guides us in constructing a system Documents the decisions we have made
We build models of complex systems because we cannot apprehend a system in its entirety
Basic Principles of OO The Four Basic Principles
Abstraction
Encapsulation
Modularity
Heirarchy
Abstraction
The essential characteristics of an entity that distinguish it from all other kinds of entities is an Abstraction.
Defines boundary relative to the perspective of the viewer.
Abstraction allows us to manage complexity by concentrating on the essential characteristics of an entity that distinguish it from other kind of entities
E.g. : A student is a person enrolled in the university, A professor is a person teaching classes at the university.
Encapsulation
Hiding implementation form client - components is encapsulation.
Abstraction & Encapsulation both goes hand in hand
Clients depend on interface or the abstract view of the services that are provided by the component
Encapsulation eliminates direct dependencies on the implementation (clients depend on/use interface).
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 2 of 61
It’s possible to change the implementation without adversely affecting the clients. As long as the interface remains unchanged, the clients are not affected.
Modularity
Modularity is the breaking up of something complex into manageable pieces.
Modularity helps people understand complex systems.
E.g. : Purchase System, Sales System, Accounts System are all different modules of one large ERP system
Heirarchy
Any ranking or ordering of abstractions into a tree-like structure.
Kinds: Aggregation hierarchy, specialization hierarchy, containment hierarchy, inheritance hierarchy, partition hierarchy.
Hierarchy is not a organizational chart nor a functional decomposition
The core objective is to break down complexity which will be manageable and changeable
What is an Object ? What is an Object ?
Informally, an object represents an entity, either physical, conceptual or software. Physical – Truck or a Person Conceptual – Chemical Process Software – Invoice 101, Sales Order SO01
Formally, an object is an entity with a well defined boundary and identity that encapsulates its state & behavior: State: is represented by attributes and relationships Behavior:is represented by operations, methods, and state machines.
Object Has State
The state of an object is one of the possible conditions in which an object may exist
The state of an object normally changes over time
E.g. Kanetkar is an object of class Professor. The Kanetkar object has state: Name=Kanetkar Employee Id=2001 Hire date=02/02/1995 Status=Tenured Max Load=3
Give me some more examples of Object
Object has Behaviour
Behavior determines how an object acts and reacts
The visible behavior of an object is modeled by the set of messages it can respond to (operations the object can perform
Professor Kanetkar’s Behavior : Submit Final Grades() Accept Course Offerings() Take a vacation()
The behavior may change the state of an object - (Setter methods)
Object has Identity
Each object has a unique identity, even if the state is identical to that of another object.
E.g. Professor Kanetkar is from Nagpur. Even if there is a professor with the same name – Kanetkar in Pune teaching C++, they both are distinct objects
What is a Class ? What is a Class ?
A class is a description of a set of objects that share the same attributes, operations, relationships and semantics. - An object is an instance of class
A class is an abstraction in that it Emphasizes relevant characteristics Suppresses other characteristics
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
There are many objects identified for any domain
Recognizing the commonalities among the objects and defining classes help us deal with the potential complexity
Page 3 of 61
A Relationship Between Classes & Objects
A class is an abstract definition of an object.
It defines the structure & behavior of each object in the class
It serves as a template / blue print for creating objects
Attributes of a Class
An attribute is a named property of a class that describes a range of values that instances of the property may hold
A class may have any number of attributes or no attributes at all.
An attribute has a type, which tells us what kind of attribute it is.
Typically attributes are integer, boolean, varchar etc. These are called primitive types.
Primitive types can be specific for a certain programming language.
Operations of a Class
An operation is the implementation of a service that can be requested from any object of the class to affect behavior
A class may have any number of operations or none at all
The operations in a class describe what class can do
The operation is described with a return-type, name, zero and more parameters. This is know as signature of an operation
Often, but not always, invoking an operation on an object changes the object’s data or state
Polymorphism What is Polymorphism ?
The ability to hide many different implementations behind single interface is polymorphism.
Polymorphism is of two types: Dynamic and Static.
Overloading of member functions & Overriding member functions is static polymorphism - i.e. at compile time you can say, which implementation of the behaviour will be executed
The Object created of superclass but instantiated to any one of the subclasses based on some condition (run-time) is dynamic or run-time polymorphism For e.g.:
Employee emp = null; if (type.equalsIgnoreCase("S")) { emp = new SalariedEmployee(); } else { emp = new ContractEmployee(); } emp.processSalary();
Now this code snippet will execute processSalary of either SalariedEmployee class or ContractEmployee class depending on the value of type. Note that emp is the reference of type Employee class which is super class of ContractEmployee and SalariedEmployee
Benefits of Polymorphism
Dynamic Polymorphism helps to extend the functionality without changing the existing code.
The contract of the client-class will be with the abstract class and not with the implementation class.
Infact with the help of pattern like Factory Pattern, you can totally shield the implementation classes from the client class.
The client will not know - which is the implementation class providing the required behaviour
What is an Interface ?
Interface has declaration of services.
It does not have any default behaviour (as opposed to abstract classes - abstract classes can have default behaviour).
The interface serves as a contract between the client and the services that will be offered by the component implementing the interface
Interfaces support “plug-and-play” architectures: You can replace the existing component with a new one which implements the same interface. The client will not have to relearn how to use the component - i.e. because it has service-contract with the interface and not the component. When you use the Television Set through a remote-control, you are getting services of your television set through remote -control. You remote control acts as an interface
Interfaces formalizes polymorphism Without interfaces there was no way to enforce polymorphism
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 4 of 61
Chapter: 2 - Implementing OO Working with Classes & Objects Identifying Classes
Read the following and identify (abstractions) classes: The Salesman brings orders from customers and records these orders in the software system. The invoices are generated based on orders that are recorded. Once the invoice is created against an order, the order is considered as closed. The Stores Keeper then packs the goods into cartons and gives it to the transporter. The transporter delivers the goods to the customer. The customer makes payment within 45 days and it is recorded by the A/Cs officer. The customer always send payment against a particular invoice. Once the pmt is recieved against an invoice, the invoice is considered as closed
Identify the abstractions by identifying nouns of interest to your Sales Application.
Identify attributes
Identify methods
Give possible objects of the classes you have identified.
Writing Classes
Write a class with the name : Customer.java as follows: public class Customer { private int id; private String name; private String address;
public int getId() { return this.id; } public void setId(int aid) { this.id = aid; } public String getName() { return this.name; }
public void setName(String aname) { this.name = aname; } public String getAddress() { return this.address; } public void setAddress(String aaddress) { this.address = aaddress; } }
Note the attributes and methods defined. These attribites are known as instance variables or member data or field variables of the class
Attributes will help establish state of the object this class
Methods will help establishing behaviour of this class
Write a class called CustomerManager.java which will instantiate Customer and invoke methods on it as follows:
public class CustomerManager { public static void main(String args[]) { Customer customer1 = new Customer(); customer1.setId(101); customer1.setName("IBM"); customer1.setAddress("Pune"); Customer customer2 = new Customer(); customer2.setId(102); customer2.setName("3 I Infotech"); customer2.setAddress("Mumbai"); System.out.println("The name of customer 1 is : " + customer1.getName()); System.out.println("The name of customer 2 is : " + customer2.getName()); } }
Run this class file and see the results. Let me now explain how the classes are loaded and objects are represented in Randaom Access Memory
Understanding Objects
The CustomerManager class that you have just written instantiates 2 Customers - i.e. creates two objects of class Customer.
Note how the state of the objects are constructed. See how each attribute which constitues the state has a data type.
Note how the behaviour is invoked on the object which changes is state (setter Methods). Also see the return data types of each of the methods
Note that the state can be same of two objects but still it has unique identity
Note the significance of private and public elements in the class, We will discuss protected later.
Working with Inheritance / Generalization Writing a Super Class
Let us revisit the same case-study (Sales Management System). There are two types of order - 1) The Local Order and 2) The Export Order. The way taxes are calculated for each type of order is quite different. Hence it is decided that there will be one Super Class called SalesOrder which will have all the generalized behaviour and 2 Sub Classes of SalesOrder viz. LocalOrder and ExportOrder which will have specialized behaviour
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 5 of 61
Write SalesOrder Super Class as follows:
import java.util.Date; public abstract class SalesOrder { private private private private private
int orderId; Date orderDate; int customerId; int quantity; float taxAmount;
public void setOrderDate(Date d) { System.out.println("setOrderDate method getting executed in SalesOrder - the Super-Class"); this.orderDate = d; } public int getOrderId() { System.out.println("getOrderId method getting executed in SalesOrder - the Super-Class"); return this.orderId; } public void setOrderId(int aorderId) { System.out.println("setOrderId method getting executed in SalesOrder - the Super-Class"); this.orderId = aorderId; }
// Please write setter getter methods for all of these instance variables public abstract void calculateTax(); }
Abstract methods are those methods which are simply declaration of the services. The other class which will inherit from this class will provide the implementation
Abstract classes are those classes which cannot be instantiated. If there is even a single method in a class which is abstract, the class must be abstract. However, not all methods in the abstract class must be abstract. There can be some concrete methods as well. Note that calculateTax is the abstract method and setOrderId and getOrderId are concrete methods.
Writing Sub Classes
Write a ExportOrder class which is Sub Class of SalesOrder class as follows:
public class ExportOrder extends SalesOrder { public void calculateTax() { System.out.println("The tax is being processed by ExportOrder - the Sub-Class"); } }
Now write a LocalOrder sub class as follows:
public class LocalOrder extends SalesOrder { public void calculateTax() { System.out.println("The tax is being processed by LocalOrder - the Sub-Class"); } }
Using Inheritance Class-Structure
Now write the OrderManager class which uses the SalesOrder class structure as follows:
public class OrderManager { public static void main(String args[]) { ExportOrder expOrder = new ExportOrder(); expOrder.setOrderId(101); expOrder.calculateTax(); LocalOrder locOrder = new LocalOrder(); locOrder.setOrderId(102); locOrder.calculateTax(); // See the following technique of working with inheritence // (Example of Dynamic Polymorphsim) String userInput = null; SalesOrder order = null; if (args.length > 0 ) { userInput = args[0]; } else { userInput = "L"; } if ("L".equalsIgnoreCase(userInput)) { order = new LocalOrder(); } else { order = new ExportOrder(); } order.setOrderId(105); order.calculateTax(); } }
See the two techiniques used for using the class structure. The second technique is the example of dynamic polymorphism
In dynamic polymorphism, the ref object declared is of type super class but instantiated to subclass depending on the value of userInput.
Now Let me explain how super and sub-classes in memory and how the ClassLoader uses inheritance structure while instantiating the classes
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 6 of 61
Working with Polymorphism Overriding
In the SalesOrder class written in previous topic-discussion, we have created one abstract method called calculateTax. Writing calculate tax in subclass is NOT overriding. It is implementing because there is not default behaviour in the super class.
Now note that there is a method called setOrderId in super class which has generalized / default behaviour. Let us write the same method again with exactly same signature in the ExportOrder class. The business rule says that when ever orderId is set for Export Order, it must immediately set the order date as today's date.
So please write a method in ExportOrder as follows:
public void setOrderId(int aorderId) { System.out.println("setOrderDate of ExportOrder the Sub-Class"); super.setOrderId(aorderId); this.setOrderDate(new Date()); // import java.util.Date // Also I hope you have written setter getter methods for // order date in the SalesOrder class }
Now execute this method from OrderManager class on expOrder object. Notice that it is this method (overridden) method that gets executed. If you comment this method and recompile and run the OrderManager then the method of the super-class is executed. This is Polymorphism - Static Polymorphism
Note the use of super pro-noun here. You may totally override the method by not calling super or invoke the behaviour in the super class and add extra functionality in the subclass.
Overloading
This is pretty simple
Add two methods in the LocalOrder class with same name but two different signatures as follows:
public void calculateAmount() { System.out.println("The calculateAmount with no param"); } public void calculateAmount(boolean withTaxes) { System.out.println("The calculateAmount with 1 param"); }
Execute both of these methods from OrderManager on locOrder object and see the results.
This is also Static - Polymorphism
Working with Associations Creating the Supplier Class
Create a new class called : Customer.java and define 4 attributes as follows: private int id private String name private int cityId private String address
Write the public getter (accessor) and setter (mutator) methods for each of the attributes defined above
Compile the class
Creating the client class
Create a class called Invoice.java. Create the following instance variables: private int id provate float amount private int productId and private Customer customer
Create a constructor and a method called saveInvoice as follows:
public Invoice() { customer = new Customer(); customer.setName("IBM"); } public void saveInvoice() { String name = customer.getName(); System.out.println("The name is : " + name); }
Now create a class called InvoiceManager.java - Create a public static void main method in it and add the following code:
Invoice inv = new Invoice(); inv.saveInvoice();
Run InvoiceManager class and see the results.
When the new object of Invoice is created, the constructor of Invoice is executed. From the constructor of invoice you have instantiated the customer object which is declared as instance variable in Invoice. You have set the name of the customer in the constructor. Now when you call saveInvoice method in InvoiceManager class, the saveInvoice method prints the name of the same customer.
This proves that there is structural relationship between the Client class - Invoice and Supplier class - Customer. The state of the Invoice object includes the state of Customer object.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 7 of 61
Assignment(s) Classes & Objects
Assignment 1 Write a class - Product.java with following attributes: id, name, sellingRate, purchaseRate, discount, quantityOnHand. Write the setter & getter methods for each one of these attributes. Identify the appropriate data types for each attribute your self. The methods must be properly named for e.g. if id is the attribute, the getter method must be getId and setter method must be setId Write a class called ProductManager with main method. In main method, instantiate Product, set values , then get values that you have set and print them using SOP.
Assignment 2 There is a payroll application you need to develop. Employee is one of the abtractions you have identified, but then there are two types of employees - salaried and contract. Calculating salary is one business method expected to be offered by Employee Abstraction. The methodology of calculating salary for salaried employee is different from the way it is calculated for contract employee. We want polymorphic behaviour from employee. Write a small application to demonstrate the this. Identify the abstract class, abstract methods in the abstract class , concrete classes and methods to implement in concrete classes. Also Identify the Generalization Structure - i.e. which classes will extend which other classes. One of the business methods expected from Employee is that it must allow setting of name of Employee. Hints: The classes are: Employee, SalariedEmployee, ContractEmployee, SalaryManager (with main method). Now you have to identify which of these classes are abstract and which one of these are concrete classes.
Assignment 3 In sales application a customer may raise n number of orders. An order is created for a particular customer and then invoice is created for partly or fully for the pending orders. Identify classes, relationships (associations) and cardinality between them. Create a class diagram to show your classes, relationships and cardinality. Write a small application to demonstrate the classes, relationships and cardinality. Hints: If X is a class having an association with Y, then in X you will create an instance variable for Y. If one instance of X is related many instance of Y then in X class you will create an an array instance of Y (Y[] instanceOfY = null) Only creating the right classes is required. A class with main method executing the application is not required
Override setName method in SalariedEmployee and demonstrate the same.
Java Chapter: 1 - Introduction The JAVA Technology About Java Technology
The Java programming language is a high-level language
With most programming languages, you either compile or interpret a program so that you can run it on your computer.
The Java programming language is unusual in that a program is both compiled and interpreted. With the compiler, first you translate a program into an intermediate language called Java bytecodes —the platform-independent codes interpreted by the interpreter on the Java platform.
The interpreter parses and runs each Java bytecode instruction on the computer.
Compilation happens just once; interpretation occurs each time the program is executed. The following figure illustrates how this works.
About Java Technology (Contd.)
You can think of Java bytecodes as the machine code instructions for the Java Virtual Machine (Java VM).
Every Java interpreter, whether it's a development tool or a Web browser that can run applets, is an implementation of the Java VM.
Java bytecodes help make "write once, run anywhere" possible.
You can compile your program into bytecodes on any platform that has a Java compiler.
The bytecodes can then be run on any implementation of the Java VM. That means that as long as a computer has a Java VM, the same program written in the Java programming language can run on Windows 2000, a Solaris workstation, or on an iMac.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 8 of 61
The Java Platform
A platform is the hardware or software environment in which a program runs.
Some of the most popular platforms like Windows 2000, Linux, Solaris, and MacOS.
Most platforms can be described as a combination of the operating system and hardware.
The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.
The Java platform has two components: The Java Virtual Machine (Java VM) The Java Application Programming Interface (Java API) Java VM is the base for the Java platform and is ported onto various hardware-based platforms.
The Java Platform (Contd.)
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets
The Java API is grouped into libraries of related classes and interfaces; these libraries are known as packages.
The following figure depicts a program that's running on the Java platform. As the figure shows, the Java API and the virtual machine insulate the program from the hardware
The Java 2 SDK, Standard Edition v. 1.3. The Java 2 Runtime Environment (JRE) consists of the virtual machine, the Java platform core classes, and supporting files. The Java 2 SDK includes the JRE and development tools such as compilers and debuggers
Understanding Classpath Path & the ClassPath
Path is an enviornmental variable which is used by the operating system and not your java virtual machine
Where as ClassPath is used by Java - (Java Virtual Machine)
When a folder is included in the "path" environmental variable, the exe(s) that are there in that folder now can be executed from any where in the entire application. So in order to work with java.exe (the java interpreter) and javac.exe (the java compiler) you must have bin folder of your java installation in the path
After writing your java classes, you would like to execute them using java.exe. Now it is the classpath variable which will be used by java to find the classes you want to execute.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 9 of 61
Setting the Path & Classpath
Both - the Path and Classpath are environmental variables. They must be set using Control Panel >> System >> Advanced >> Environmental Variables- Option
Set the path (or add to existing path) the jdk (which ever version)/bin folder. This will make javac.exe and java.exe available for execution from any folder
Now set the classpath to (or add to existing classpath) . - The dot indicates that the current folder in which your focus is, while executing your application will be considered to be in the classpath
Now write a simple class (the name of the file must be MyFirstJavaClass.java) using notepad as follows:
public class MyFirstJavaClass { public static void main(String args[]) { System.out.println("My First Program In java"); } }
Compile the program using the following command on the dos prompt:
javac MyFirstJavaClass.java
Now run the program using the following command:
java MyFirstJavaClass
Creating a class in other folder
Now create a class called :MySecondJavaClass.java in c:\working\learningclasspath as follows:
public class MySecondJavaClass { public static void main(String agrs[]) { System.out.println("My Second Java Class"); } }
Compile the class
Now add this folder in the classpath - you know from where and how
Go to any folder other than c:\working\learningclasspath. Execute the class as using java.exe as follows: java MySecondJavaClass
Note that the class will execute. This is because the folder in which MySecondJavaClass.class file is created is in the classpath
Repeat this exercise with some MyThirdJavaClass in some other folder and see the results
Please Note: When the you append a ; to the end of your classpath, the current folder is automatically considered to be in classpath. It is as good as appending a . the end of classpath
The Jar Files
The Jar files are simply zip files that contain the .class files
See the rt.jar file
All the classes that you have used till now for e.g. String, System class etc. are all in rt.jar file
Note that the classes are organized in appropriate folders
The Classpath Trick(s)
Create a folder called c:\working\c1\sales and create a class called SalesManager.java in it. Write a simple method addInvoice in the same with simple SOP - printing "Adding Invoice in c1". Not create a folder called c:\working\c2\sales and create a class called SalesManager.java in it. Write a simple method addInvoice in the same with simple SOP printing "Adding Invoice in c2". Compile both of these classes in their respective folders.
Now create a folder called c:\working\java and create SalesApp.java in this folder with main method. import sales.* in this SalesApp class. In the main method write :
SalesManager manager = new SalesManager(); manager.AddInvoice();
Save the file. Now set the classpath to c:\working\c1;c:\working\c2;. Compile, execute and see the results : JVM will by default take the SalesManager of the folder that is mentioned in the classpath.
This is However, bad design because now the behavior is dependent on the classpath and not your application.
NEVER DESIGN AN APPLICATION LIKE THIS
Also note one more important point: The java compiler (javac.exe) reads the classpath - not for the .java file which you ask it to compile. Once it gets the file you want it to start compilation, it then checks for the availability of other classes used, thereafter, in the classpath. This point will be very clear to you only after you do assignment 1 and assignment 2 in "ClassPath Assignments"
Data Types in Java Primitive Data Types
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Primitive Data types are those data types which are not classes and are the basic and fundamental data types offered by the programming language. The structure of these data types may be different in different operating systems. For e.g. an int may be 2 bytes in DOS where as it may be 4 bytes in Unix.
Following are the primitive data types in java: byte short int long float double char boolean
Using Literals: ‘c’ – char 178 – int 8864 – long 37.266D – double 38.99F – float true - boolean false - boolean
byte, short, int, float and double are all numeric - primitive data types.
byte, short and int are the ones which does not hold decimal values. Where as float and double can hold decimal values
Page 10 of 61
More on float and double
A given double should always be able to handle any mathemetical operation a given float could.
A float can be type casted to double but a double cannot be type casted to float
This is because a double can hold value greater than float
If at all you try to convert a double into a float using Wrapper classes (float f = objectOfTypeDouble.floatValue()) then it will convert the value and put it in float if the value is lesser than or equal to max value of float or else it will put infinity as the value in variable: f
The above metioned type-casting can be done using bracket methods also i.e. float f = (float) d where d is a variable of primitive data type. The end results will also be as same as discussed above
Working with Primitive Data-Types
Please create a new java class called DataTypes.java and add the following code in its main method :
int i = 5; System.out.println("The value of i is : " + i); float f = 2.5f; float result = f + 1.3f;
System.out.println("The value of f is : " + f); System.out.println("The value of result is : " + result); double d = 2.22; System.out.println("The value of d is : " + d); d = f; // below given is not possible - un comment - you will get compilation error //f = d; /* Below given line gives an error - because L is not added at the end indicating its a long */ // long l = 122222222222; long l = 1222222222222L; System.out.println("The value of l is : " + l); byte b = 3; short s = 2; s++; f++; d++; l++; System.out.println("The value of s is : " + s); // Use SOP to print the value of all the variables incremented above System.out.println("Max System.out.println("Max System.out.println("Max System.out.println("Max System.out.println("Max System.out.println("Max
of of of of of of
byte : " + Byte.MAX_VALUE); short : " + Short.MAX_VALUE ); int : " + Integer.MAX_VALUE ); Long : " + Long.MAX_VALUE); float : " + Float.MAX_VALUE); double is : " + Double.MAX_VALUE);
Very important: Please note that when you assign a constant to double type variable, even if you do not suffix d at the end of the constant, java implicity considers to be a double. Where as if you want a constant to be a float you have explicity suffix f to it.
In the same DataTypes.java add the following code for char and boolean and see the results:
char c = 'a'; System.out.println("The value of a is : " + c); boolean isMarried = true; boolean orderDispatched = true; System.out.println("The value of isMarried is : " + isMarried + " And orderDispatched : " + orderDispatched);
The Wrapper Classes
All the number - primitive data types has wrapper classes.
You can create objects of these classes to hold its respective primitive value.
The wrapper classes are very useful to exchange values with other primitive data types.
Write the following code in the DataTypes.java, compile and execute and see the results :
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 11 of 61
int age = 25; Integer theAge = new Integer(age); double dAge = theAge.doubleValue(); double ddd = 10200.20222; System.out.println("ddd : " + ddd); Double salary = new Double(10200.20); int intPartOfSalary = salary.intValue(); System.out.println("The intPartofSalary is : " + intPartOfSalary); Double taxAmount = new Double(300000.25); float fTax = taxAmount.floatValue(); System.out.println("Byte value of taxAmount : " + fTax);
Type Casting of primitive data types
As such, typecasting is auto. You just have to assign the value of one to the other.
However, you can assign the higher capacity variable with the value of lower capacity of variable. Vice-a-versa is not true.
Write the following code again in same DataTypes.java and see the results:
byte bb = 4; short ss = 23; int ii = 3; long ll = 56; float ff = 4; double dd = 9.4; //bb = ss; // not possible ss = bb; // possible //ss = ii; // not possible ii = ss; // possible // ii = ll; not possible ll = ii; // possible // ll = ff; // not possible ff = ll; // possible //ff = dd; // not possible dd = ff ; //possible
Still type-casting is possible without bringing the Wrapper classes in picture as follows:
byte b = 27; int i = 129; b = (byte) i; System.out.println("The value of b : " + b);
Note that it prints -127 because 129 exceeds the MAX_VALUE of byte.
Variables and their scope Local Variables
When you declare variables in a method its scope is limited to the scope of the method.
Such variables are known as local variables
Local variables are automatically garbage collected after the method is over and its value is no longer available
Within the method if you declare a variable within a block - it will considered as private to the block and will not be available to the code out of the block. The block can be a plain block, a if block, try catch block or any other type of block. Try the following code:
{ int empId = 505; } /* Following line will throw a compilation error * This is because, empId is declared above is in a block * It will not be available out of the block */ System.out.println("The value of empId is : " + empId);
Instance variables
The class you declare have instance variables (object variables). These are nothing but the attributes / fields of the class.
When the object is created of a class, the state of the object is constructed with the help of these instance / object variables.
Each object has its own copy of instance variable
The instance variable is definitely available to all the methods of the class in which is defined.
Scope of instance variables
You can specify any of the following modifiers for the instance variables: public, private and protected
The private variables can be accessed from within the class in which they are defined
The protected variables can be accessed from within the class, its subclasses and from any class which is within the same package
The public instance variables can be accessed from any where in the entire application
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 12 of 61
Write a Customer class and define the variables in it as follows:
private int id; public int cityId; protected int stateId;
Instantiate this class from the main method of class called : CustomerManager.java. Try to access all of these variables against the object of Customer class. Compile and study the compilation errors you get
Class variables
Class variables are defined as static variables in the class.
Their value remains the same for each instance of the class - in fact each instance refers to the same copy of the static variable
Static variables can be accessed by the name of the class and also by the object name (Instance Variables can be accessed only through instance/object name)
Write SalesMan.java class as follows:
public class SalesMan { private String name; private static int totalSalesMen = 0; public SalesMan() { totalSalesMen ++; } public void setName(String aname) { this.name = aname; } public String getName() { return this.name; } public int getTotalSalesMen() { return this.totalSalesMen; } }
Now write SalesManManager.java (with a main method) to instantiate 3 SalesMan objects. obtain the value of totalSalesMen using getTotalSalesMen method. Invoke this method using any one of the objects declared and also directly by using Class name for e.g. SalesMan.getTotalSalesMen(). See the results. Note that the static variable - totalSalesMen value remains the same and can be accessed through the name of the class and also through the object. Where as the instance variable - name values are all different for each instance
Final variables
Local, instance , class - any of these variables can be final variables
Final variables are those whose values do not change - once initialized
When a class / instance variable is created as final, you must initialize the value at the time of creating the variable
If a local variable in a method is defined as final, the value can be assigned later, but once assigned, the value cannot be changed
The final variables are nothing but constants in java. As per naming convention in java the final variables are defined in all caps. Re-Collect the Byte.MAX_VALUE, Double.MAX_VALUE etc.
Methods and their Scope Method Scope
The methods in a class can be private, public or protected
The scope rules applicable to methods are same as those applicable to instance variables
Methods either return a value of a particular data type (primitive or object) or returns void i.e. no return value
Methods can have arguments of any data type (primitive or object).
Final Methods and Abstract methods
Final Methods are those which cannot be overriden
Abstract methods are those which simply declared - no implementation of method is provided
Operators Arithmetic Operators
Arithmetic Operators in Java are as follows: + (add), - (subtract), * (multiply), / (divide), % (remainder) ++, -- (pre and post increments) += -=, *= /= Relational Operators: >, <, >=, <=, ==, !=
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 13 of 61
Write your own class to test each one of these. Develop your own mini-sample classes for the same.
Conditional Operators
op1 && op2: second expression is evaluated only of first is true;
Op1 || op2: evaluates only until one is found as true
! Op1: op1 not true
Op1 & Op2: evaluates both the expressions
Op1 | Op2: evaluates both the expressions Again - develop your own examples to practice each one of these
Ternary Operator
Op1 ? Op2 : Op3 - If the expression is true, then the second argument is returned or else the third
Write the following code in main method of TernaryOperator.java and see the results:
int theSal = 10000; String department = "Information Technology"; boolean isSalAcceptable = theSal >= 10000 && department.equalsIgnoreCase("Information Technology") ? true : false; System.out.println("isSalAcceptable : " + isSalAcceptable);
Inheritance & Abstract Classes Extending Classes
Inheritance is the feature where one class inherits its features from the super class.
The super class defines the generalized behavior and subclass defines the specialized behaviour
The generalized behaviour can be overriden by the specialized class
Also note that all the features (whether public private or protected) are inherited not just the public. The only point is that the private features are accessible only from the class in which they are defined
Please refer to Basic OOAD UML Tutorial for working examples
Final Classes & Methods
Final Classes are those classes that cannot be specialized or inherited
Final methods are those methods that cannot be overriden
Please develop the examples based on following specs: Create a class as follows: public final class Employee..... (complete the rest of the class with some attributes and methods) and now try to create another class called SalariedEmployee which will extend from Employee class - try to compile - you will get a compilation error
Now declare method a final method as follows: public final void processSalary() ... in Employee class. Remove the final keyword from the declaration of Employee class so that it can be inherited. Now create a SalariedEmployee class that extends from Employee class - override processSalary method - You will get a compilation error.
Abstract Classes
Abstract classes are those classes that cannot be instantiated.
Create an abstract class called Employee and try to instantiate this class from some other class. You will get a compilation error.
Abstract classes serve as contract between the client classes and the components that subclass the Abstract Classes
Clients depend on abstraction and not implementation
Constructors and Overloading them What are constructors
Constructors are the methods that are executed as soon as memory is grepped for a particular object - in other words when the object is created in Random-Access-Memory, the constructor is executed
The constructor method has name as same as class name.
The constructors may take argument or may not take any argument
If no constructor is defined for a class then a default constructor without any parameter is considered implicitly
But if there is any constructor defined, then only those that are defined is considered to be valid constructors.
Overloading Constructors
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
You can overload constructors
The overloaded constructors will all have different signatures
Wrtie a class called Employee.java as follows:
Page 14 of 61
public class Employee { public Employee() { System.out.println("The Constructor of Employee"); }
public Employee(int id) { System.out.println("The Constructor in Employee with 1 parameter"); } }
Now also write EmployeeManager class as follows:
public class EmployeeManager { public static void main(String args[]) { Employee emp1 = new Employee(); Employee emp2 = new Employee(301); } }
Execute EmployeeManager and see the results
Constructors in inherited classes
In the inherited class what ever constructor you write, by default i.e. implicity java makes a call to the default constructor of the super class.
Write a new SalariedEmployee.java class as follows:
public class SalariedEmployee extends Employee { public SalariedEmployee() { System.out.println("The SalariedEmployee Constructor is executed"); }
public SalariedEmployee(int id) { System.out.println("The SalariedEmployee Constructor with 1 parameter is executed"); } public SalariedEmployee(int id, String name) { super(2); System.out.println("The SalariedEmployee Constructor with 2 parameters is executed"); } }
Add the following lines in EmployeeManager class and execute the same and see the results:
SalariedEmployee s1 = new SalariedEmployee(); SalariedEmployee s2 = new SalariedEmployee(2); SalariedEmployee s3 = new SalariedEmployee(2, "Mr. Menon");
If there is no default constructor (the one without any parameters) in the super class, then java will compel you to make an explicit call to non-default constructor from the constructor of sub-class. Remove the default constructor (the with no parameters) from Employee class and compile it. Now try to re-compile SalariedEmployee - you will get compilation errors
Now from the sub-class SalariedEmployee, from each constructor make a call to the constructor of the super class as follows:
super(345);
Now compile SalariedEmployee - it will get compiled successfully.
Packages & Importing Classes & Interfaces Package in Java
A package in java is like namespace in C++.
It helps you to group the functionally related classes and interfaces. We will discuss interfaces a bit later.
As said earlier - its determines the namespace. i.e. if a class is defined in a package as public, it will be visible to all classes within the package as well as all classes out of the package - Whereas - if the class in package is declared with no modifier class Employee { then it will be visible to only those classes which are in the same package and not to the classes which are out of the package.
The package statement must be included right-on-top in the class as follows:
package sales;
When a package statement is used in a class, it is a must for the class to be in the folder the name of which as same as the name of the package used in the class. Remember the names- here are case-sensitive.
Importing Classes
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 15 of 61
If you have a class in sales package and you want to instantiate and use a class which is in accounts package, you must import the class you want to use from accounts package. Consider the following:
package sales; import accounts.CreditAccount public class OrderManager { // attributes // methods public void saveOrder() { CreditAccount account = new CreditAccount(); } }
You have a class called CreditAccount which is in accounts package. You want to use it in OrderManager class in sales package. Note the how the package statement is declared and also the import statement
You can use * in order to import all classes of a particular package.
* does not mean recursive import. For e.g. if you give import accounts.* - it will tell the compiler that : "ALL THE CLASSES FROM ACCOUNTS PACKAGE MUST BE IMPORTED". It does NOT mean that all the packages and classes within recurssive packages are to be imported
Do the following to learn packages in java practically: Create a new folder structure is your c drive as c:\working\learningpackages Set class path to . using the command: set Classpath=. Now create two folders in c:\working\learningpackages - sales and accounts. Create a class called OrderManager.java in c:\working\learningpackages (the source code is given below) Create SalesOrder.java in sales folder (source code is given below) Create Account.java in accounts folder (source code is given below) Compile all classes keeping your command prompt at c:\working\learningpackages using javac *.java
Following lines for OrderManager.java:
import sales.SalesOrder; import accounts.Account; public class OrderManager { public static void main(String args[]) { // Note that following will be successfully executed SalesOrder order = new SalesOrder(); Account account = new Account(); // Now comment the above two import statements and recompile // It will give you compilation error. } }
Following lines for SalesOrder.java (in sales folder) :
package sales; public class SalesOrder { public SalesOrder() { System.out.println("SalesOrder Object successfully created"); } }
Following lines for Account.java (in accounts folder):
package accounts; public class Account {
public Account() { System.out.println("Account Object successfully created"); } }
Writing Interface
Write an interface called TaxCalculator as follows:
public interface TaxCalculator { public void calculateTax(); public float getTax() ; }
Now write a class called Invoice which implements this interface as follows :
public class Invoice implements TaxCalculator { // you will have to implement all the methods in TaxCalcualtor }
Compile Invoice without implementing methods of TaxCalculator - You will get compilation errors.
You must implement all the method of the interface that a class implements or else declare the class abstract. What you must do is dependent on how you design your application.
Java Behaviour to Resolve Ambiguity
You have a Date class in java.util package. You also have Date class in java.sql package. If you write import statements in SalesManager.java as follows:
import java.util.*; import java.sql.*;
Java will force you to qualify Date with its package name in all the methods of the class which you are writing.
Now consider that the import statements in your SalaryManager.java are written as follows:
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 16 of 61
import java.util.Date; import java.sql.*;
Now if you do not qualify Date with the package any where in SalaryManager.java, java will not complaint. Since you explicity specified the exact class to be imported from util package, it will consider that you intend to you java.util.Date
Test this out and see the results.
Assignment(s) ClassPath Assignments
Assignment 1 Please create some a class in c:\working\assignments\sales\SalesManager.java. Write a simple main method in the class having one single SOP statement. Set the classpath in such a way that you must be able to compile this class from c:\working\assignments\purchase folder.
Assignment 2 Create a class in c:\working\assignments\accounts\Account.java. Write a method called debitAccount - write a simple SOP in this method. Now go to SalesManager.java class in c:\working\assignments\sales and instantiate Account class from main method of SalesManager. Set the classpath in such a way that keeping the focus in c:\working\assignments\sales folder, you must be able to compile your SalesManager.
Assignment 3 Write classes : ClassA, ClassB, ClassC in 3 different folders in c:\. Compile all these classes. Write a class called ClientClass in c:\working\assignments\sales. Instantiate all the 3 classes. Set the classpath in such a way that you must be able to compile ClientClass being in c:\working\assignments\sales folder.
Data Type Assignments
Assignment 1 In Sales application there is a class called Invoice which has a method called calculateInvoiceAmount. Write this class and method. In this method demonstrate the calculation of invoice amount as follows: Calculate list amount as 50 units of quantity multiplied by Rs 300 and 25 paise as rate Then deduct discount of 4.5 % Then add Octroi of Rs 200 and 50 paise Then add Handling Charges of Rs 200 Add Sales Tax of 5.2 % This gives you the final amount. Print this final amount after all the calculations and see the results.
Assignment 2 Create a program that reads an unspecified number of integer arguments from the command line and adds them together. For example, suppose that you enter the following:
java Adder 1 3 2 10
The program should display 16 and then exit. The program should display an error message if the user enters only one argument.
Assignment 3 Create a program that is similar to the previous one but has the following differences: Instead of reading integer arguments, it reads floating-point arguments. It displays the sum of the arguments, using exactly two digits to the right of the decimal point. You can use the following code to format your answer to 2 digits right to the decimal point
//format the sum, do not forget to import java.text.DecimalFormat DecimalFormat myFormatter = new DecimalFormat("###,###.##"); String output = myFormatter.format(sum);
Assignment 4 We have already written code to view the max values of byte, short, int, long, double and float. Now write a program to display the min values of each one of these data types
Assignment 5 Write a program that calculates the number of Indian Rs equivalent to a given number of US Dollars. Assume an exchange rate of 44.85062 Rs per dollar.
Variable & Method Scope Assignments
Assignment 1 Write a class TaxValueObject with attributes as private and methods as public. Attributes are : id, name, taxRate. Write public setter getter methods for all of these attributes. Create another class called TaxManager.java with a main method. In main method instantiate TaxValueObject and try to put values in id and name of the instance directly without using the method. Compile and note the error messages you get. Now make each one of those variables as protected in TaxValueObject and re-compile it. Now Re-Compile TaxManager - now see the results.
Constructor Assignments
Create a Class called Tax.java. There is an instance variable in this class called taxRate. Write a public getter method for this instance variable - only getter. Write a overloaded constructor with 1 parameter to initialize the value of taxRate in this constructor.
Create a class called LocalTax - sub class of Tax. Create two constructor here as well. 1 - with no parameter and the other with 1 parameter - Do not write any thing in any constructor. Now instantiate LocalTax using the constructor with 1 parameter in main method of TaxManager.java . Execute getter method to get the value of taxRate and print the same. What value gets printed ?. Now make appropriate changes in the constructor in LocalTax with 1 parameter so that now when you execute TaxManager.java - you get the value that you passed while creating LocalTax object.
Package Assignments
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 17 of 61
Redo all the examples specified in "Classpath Assignments" page. This time each class must contain the package statement right on the top. The package name must be as same as the folder in which the classes are. The classpaths must now be set accordingly and also the import statements in each class so that it is accessible. This is very important assignment as you will finally make your understanding of packages, import statements, classpaths crystal clear
Chapter: 2 - Arrays What are Arrays What is an Array
An array is a structure that holds multiple values of the same type. The length of an array is established when the array is created (at runtime). After creation, an array is a fixedlength structure.
An array element is one of the values within an array and is accessed by its position within the array
Array of Primitive-Types Array of primitive-types
You can create arrays of primitive types.
You can access array elements by its subscript
The array once declared, by itself is an object (which may contain primitive or objects as elements)
Once array is declared of a particular type, you can put only those elements in the array which are of that type
The .length gives you the total number of elements in an array
Working Examples
Write the following code in main method of PrimitiveTypeArrays.java
int arrayOfInt[] = new int[] {2, 3, 5}; for (int i = 0; i < arrayOfInt.length; i++) { System.out.println("The " + i + " element has value : " + arrayOfInt[i]); } int arrayOfSalaries[] = null; arrayOfSalaries = new int[5]; arrayOfSalaries[0] = 50000; arrayOfSalaries[1] = 20000; arrayOfSalaries[2] = 30000; for (int i = 0; i < arrayOfSalaries.length; i++) { System.out.println("The " + i + " salary has value : " + arrayOfSalaries[i]); } char arrayOfChars[] = new char[] {'c', 'r', '1'}; // Use for loop to print the values char arrayOfDeptType[] = null; arrayOfDeptType = new char[3]; arrayOfDeptType[0] = 'A'; arrayOfDeptType[1] = 'I'; arrayOfDeptType[2] = 'H'; // Use for loop to print the values /* Uncomment the below given line and run the class * You will get ArrayIndexOutOfBoundsException - runtime exception. */ // arrayOfDeptType[4] = 'X'; double arrayOfIncrements[] = new double[] {23.4, 45.44, 12.33}; // Use for loop to print the values
Create the arrays of other primitive data types in the above class and see the results
Array of Wrapper Classes Array of Wrapper Classes
The way you create array of primitive data types, you can also create array of objects.
Once an array of a particular object is created you can put only that type of object in the array
Create a class called StringArray.java and write the following in main method :
String names[] = new String[] {"Shakir", "Priyanka", "Sumeet"}; for (int i = 0; i < names.length; i++) { System.out.println("The " + i + " name is : " + names[i]); } String departmentNames[] = new String[5]; departmentNames[0] = "Accounts";
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
departmentNames[1] departmentNames[2] departmentNames[3] departmentNames[4]
= = = =
Page 18 of 61
"H.R."; "I.T"; "P.R."; "Sales";
// Use for loop to display all the values
Also write 3 more java classes : IntegerArray.java, DoubleArray.java & FloatArray.java and write the code of your own (the way I have demonstrated in StringArray.java) in main method and see the results
Array of User-Defined Objects Array of User-Defined Objects
You can also create array of objects which belongs to classes defined by you in your application
Write a new class called Customer.java as follows:
public class Customer { private int id; private String name; public void setName(String aname) { this.name = aname; } public String getName() { return this.name; } public void setId(int aid) { this.id = aid; } public int getId() { return this.id; } }
Now create CustomerManager.java and write the following in main method, compile and see the results:
Customer myCustomers[] = new Customer[] {new Customer(), new Customer(), new Customer()}; myCustomers[0].setId(101); myCustomers[0].setName("IBM"); myCustomers[1].setId(102); myCustomers[1].setName("3I-Infotech"); myCustomers[2].setId(103); myCustomers[2].setName("Info Sys"); // Following line will throw ArrayIndexOutOfBoundsException myCustomers[3].setId(104); Customer customers[] = new Customer[5]; customers[0] = new Customer(); customers[0].setId(201); customers[0].setName("CapGemini"); customers[1] = new Customer(); customers[1].setId(202); customers[1].setName("i-flex"); customers[2] = new Customer(); customers[2].setId(203); customers[2].setName("GTL"); customers[3] = new Customer(); customers[3].setId(204); customers[3].setName("Wipro"); // please note that we are not setting the values for 5th element // Also note that we have given i < 4 and not i < 5 - I ll explain Why. for (int i = 0; i < 4; i++) { System.out.println("The id of " + i + " Customer is :" + customers[i].getId() + " and name is : " + customers[i].getName()); } /* Uncomment the following line and execute this class. It will throw NullPointerException runtime exception */ //customers[4].setId(205);
Double Dimension Arrays Double Dimension Array of int
You can also create double dimension arrays in java.
In double dimension arrays each element will be an array itself. So you can say - it is an array of arrays
Write the following code in main method of a class - DoubleDimensionArray.java and see the results
int doubleDimension[][] = new int[][] {{1, 2}, {3, 4}, {5, 6}}; System.out.println("The length is : " + doubleDimension.length + " And of Col : " + doubleDimension[0].length); for (int i = 0; i < doubleDimension.length; i++) { for (int j = 0; j < doubleDimension[i].length; j++) { System.out.println("The " + i + " row and " + j + " column has value : " + doubleDimension[i][j]); } }
Please write your own example with float as the data type for double dimension array and see the results.
One more exercise: Write a new class that will create two dimensional array for Customer objects.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 19 of 61
Assignment(s) Array Assignments
The following program, WhatHappens, contains a bug. Find it and fix it.
// // This program compiles but won't run successfully. // public class WhatHappens { public static void main(String[] args) { StringBuffer[] stringBuffers = new StringBuffer[10]; for (int i = 0; i < stringBuffers.length; i ++) { stringBuffers[i].append("StringBuffer at index " + i); } } }
Write a program which will have the following array declared:
String[] skiResorts = { "Whistler Blackcomb", "Squaw Valley", "Brighton", "Snowmass", "Sun Valley", "Taos" };
Print the index of "Brighton"
Ammend above program to print only 2nd and the last element of the array. Increase the number of elements in the array and still your program must print exactly 2nd and which ever is the last element of the array.
Create array of TaxValueObject (You know the structure of this class) having 5 elements in it. Initialize the state of each object in the array and print the same using a for loop. Print
Create a class called InvoiceValueObject containing following fields : id, customerId, amount. Create a constructor accepting 3 parameters to initialize the value of all the instance variables. You know the data-types of each one of these attributes and also include the getter methods for them - only getter methods. Now create InvoiceMISManager.java class which will create 5 objects of class InvoiceValueObject in an array. The array must and must be initialized on the same line in which it created for e.g. String[] names = new String[] {new String("Delhi"), new String("Mumbai"), new String("Bangalore")}. This code snippet has created array of String objects having 3 elements. This technique must be used to create 5 objects of class InvoiceValueObject in array. Calculate the total of all the invoice amount and display the same.
Chapter: 3 - Exception Handling What is an Exception What is an Exception
The Java language uses exceptions to provide error-handling capabilities for its programs
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
When such an error occurs within a Java method, the method creates an exception object and hands it off to the runtime system.
The exception object contains information about the exception, including its type and the state of the program when the error occurred.
The runtime system is then responsible for finding some code to handle the error. In Java terminology, creating an exception object and handing it to the runtime system is called throwing an exception.
Who Handles the Exception
After a method throws an exception, the runtime system leaps into action to find someone to handle the exception. The set of possible "someones" to handle the exception is the set of methods in the call stack of the method where the error occurred.
The runtime system searches backwards through the call stack, beginning with the method in which the error occurred, until it finds a method that contains an appropriate exception handler.
An exception handler is considered appropriate if the type of the exception thrown is the same as the type of exception handled by the handler.
Thus the exception bubbles up through the call stack until an appropriate handler is found and one of the calling methods handles the exception.
The exception handler chosen is said to catch the exception.
Advatages of Exception
Advantage 1: Separating Error Handling Code from "Regular" Code
Advantage 2: Propagating Errors Up the Call Stack
Advantage 3: Grouping Error Types and Error Differentiation
Throwable class & its sub-classes
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 20 of 61
Errors
When a dynamic linking failure or some other "hard" failure in the virtual machine occurs, the virtual machine throws an Error
Typical Java programs should not catch Errors
In addition, it's unlikely that typical Java programs will ever throw Errors either
Exception class
Most programs throw and catch objects that derive from the Exception class.
Exceptions indicate that a problem occurred but that the problem is not a serious systemic problem.
The Exception class has many descendants defined in the Java packages.
These descendants indicate various types of exceptions that can occur. For example, IllegalAccessException signals that a particular method could not be found, and NegativeArraySizeException indicates that a program attempted to create an array with a negative size.
One Exception subclass has special meaning in the Java language: RuntimeException
Runtime Exceptions
The RuntimeException class represents exceptions that occur within the Java virtual machine (during runtime).
An example of a runtime exception is NullPointerException, which occurs when a method tries to access a member of an object through a null reference.
A NullPointerException can occur anywhere a program tries to dereference a reference to an object. The cost of checking for the exception often outweighs the benefit of catching it. Because runtime exceptions are so ubiquitous and attempting to catch or specify all of them all the time would be a fruitless exercise (and a fruitful source of unreadable and unmaintainable code), the compiler allows runtime exceptions to go uncaught and unspecified.
Working with try - catch The try - catch block
Write a class called InputFile.java as follows:
private FileReader in; public InputFile(String filename) { //try { in = new FileReader(filename); //} catch (FileNotFoundException ex) { // System.out.println("The FileNotFoundException has occurred: " + ex.getMessage()); //}
} // following function returns the first word in the text file public String getWord() { int c = 0; StringBuffer buf = new StringBuffer(); do { // try { c = in.read(); // } catch (IOException ex) { // System.out.println("The IOException is : " + ex.getMessage()); // } if (Character.isWhitespace((char)c)) return buf.toString(); else buf.append((char)c); } while (c != -1); return buf.toString(); }
Try to compile this class - and note that you will get compilation error
Now uncomment the try catch block and compile. Yes - it will compile successfully now.
When you read a file into FileReader object, it is quite possible that the file you are trying to read does not exist. An in such a case the FileReader constructor throws a FileNotFoundException
You must catch this exception or else your .java file will fail to compile.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 21 of 61
The try - catch block (Contd.)
Write a new class called FileManager.java and write the following code in its main method:
InputFile f = new InputFile("c:/working/learningexceptions/TheTextFile.txt"); System.out.println(f.getWord());
Create text file in c:\working\learningexceptions called TheTextFile.txt and write a statement :"Java is the best programming language" - Execute FileManager and see the results.
In FileManager.java change the name of the file to Yabadabadoo instead of TheTextFile.txt and then re-compile and execute it - see the results. Specially note that the catch part now gets executed.
The catch block is executed when the exception specified in the catch clause occurs.
There can be more than one catch blocks for a single try
Adding more than one catch
Modiy the InputFile written earlier to accomodate the following lines in the constructor just after the line where you have written: in = new FileReader(filename);
Class.forName("learningexceptions.InputFile");
You will again get the compilation error.
Now add one more catch to the existing try in the constructor as follows:
catch (ClassNotFoundException ex) { System.out.println("The ClassNotFoundException : " + ex.getMessage()); }
Now the class will compile successfully.
There can be as many catch blocks as it would take to successfully write all the code that throws exception.
Java's Catch or Specify Requirement Catch
Java requires that a method either catch or specify all checked exceptions that can be thrown within the scope of the method. This requirement has several components that need further description: "catch", "specify," "checked exceptions," and "exceptions that can be thrown within the scope of the method."
A method can catch an exception by providing an exception handler for that type of exception.
The page, Dealing with Exceptions, introduces an example program, talks about catching exceptions, and shows you how to write an exception handler for the example program.
Specify
If a method chooses not to catch an exception, the method must specify that it can throw that exception.
Why did the Java designers make this requirement? Because any exception that can be thrown by a method is really part of the method's public programming interface:
callers of a method must know about the exceptions that a method can throw in order to intelligently and consciously decide what to do about those exceptions.
In the method signature you specify the exceptions that the method can throw.
The next page, Dealing with Exceptions, talks about specifying exceptions that a method throws and shows you how to do it.
Checked Exceptions
Java has different types of exceptions, including I/O Exceptions, runtime exceptions, and exceptions of your own creation, to name a few. Of interest to us in this discussion are runtime exceptions.
Runtime exceptions are those exceptions that occur within the Java runtime system. This includes arithmetic exceptions (such as when dividing by zero), pointer exceptions (such as trying to access an object through a null reference), and indexing exceptions (such as attempting to access an array element through an index that is too large or too small).
Runtime exceptions can occur anywhere in a program and in a typical program can be very numerous. The cost of checking for runtime exceptions often exceeds the benefit of catching or specifying them.
Thus the compiler does not require that you catch or specify runtime exceptions, although you can. Checked exceptions are exceptions that are not runtime exceptions and are checked by the compiler; the compiler checks that these exceptions are caught or specified.
Some consider this a loophole in Java's exception handling mechanism, and programmers are tempted to make all exceptions runtime exceptions. In general, this is not recommended. Runtime Exceptions--The Controversy contains a thorough discussion about when and how to use runtime exceptions. Exceptions throws withing the scope of method
The statement "exceptions that can be thrown within the scope of the method" may seem obvious at first: just look for the throw statement.
However, this statement includes more than just the exceptions that can be thrown directly by the method: the key is in the phrase within the scope of. This phrase includes any exception that can be thrown while the flow of control remains within the method. This statement includes both Exceptions that are thrown directly by the method with Java's throw statement. Exceptions that are thrown indirectly by the method through calls to other methods
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 22 of 61
Dealing with Exceptions The List Number Example
The following example defines and implements a class named ListOfNumbers. The ListOfNumbers class calls two methods from classes in the Java packages that can throw exceptions.
import java.io.*; import java.util.Vector; public class ListOfNumbers { private Vector victor; private static final int size = 10; public ListOfNumbers () { victor = new Vector(size); for (int i = 0; i < size; i++) victor.addElement(new Integer(i)); } public void writeList() { PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt")); for (int i = 0; i < size; i++) out.println("Value at: " + i + " = " + victor.elementAt(i)); out.close(); } }
Upon construction, ListOfNumbers creates a Vector that contains ten Integer elements with sequential values 0 through 9. The ListOfNumbers class also defines a method named writeList that writes the list of numbers into a text file called OutFile.txt. The writeList method calls two methods that can throw exceptions. First, the following line invokes the constructor for FileWriter, which throws an IOException if the file cannot be opened for any reason: out = new PrintWriter(new FileWriter("OutFile.txt"));
Second, the Vector class's elementAt method throws an ArrayIndexOutOfBoundsException if you pass in an index whose value is too small (a negative number) or too large (larger than the number of elements currently contained by the Vector). Here's how ListOfNumbers invokes elementAt: out.println("Value at: " + i + " = " + victor.elementAt(i));
If you try to compile the ListOfNumbers class, the compiler prints an error message about the exception thrown by the FileWriter constructor, but does not display an error message about the exception thrown by elementAt.
This is because the exception thrown by the FileWriter constructor, IOException, is a checked exception and the exception thrown by the elementAt method, ArrayIndexOutOfBoundsException, is a runtime exception.
Java requires that you catch or specify only checked exceptions
Catching & Handling Exceptions
Now that you've familiarized yourself with the ListOfNumbers class and where the exceptions can be thrown within it, you can learn how to write exception handlers to catch and handle those exceptions.
The three pages that follow cover the three components of an exception handler -- the try, catch, and finally blocks.
They show you how to write an exception handler for the ListOfNumbers class's writeList method, described in The ListOfNumbers Example.
Catching & Handling Exceptions (try block)
The first step in constructing an exception handler is to enclose the statements that might throw an exception within a try block. In general, a try block looks like this:
try { Java statements }
The segment of code labelled Java statements is composed of one or more legal Java statements that could throw an exception.
To construct an exception handler for the writeList method from the ListOfNumbers class, you need to enclose the exception-throwing statements of the writeList method within a try block. There is more than one way to accomplish this task. You could put each statement that might potentially throw an exception within its own try statement, and provide separate exception handlers for each try. Or you could put all of the writeList statements within a single try statement and associate multiple handlers with it. The following listing uses one try statement for the entire method because the code tends to be easier to read.
PrintWriter out = null; try { System.out.println("Entering try statement"); out = new PrintWriter( new FileWriter("OutFile.txt")); for (int i = 0; i < size; i++) out.println("Value at: " + i + " = " + victor.elementAt(i)); }
The try statement governs the statements enclosed within it and defines the scope of any exception handlers associated with it. In other words, if an exception occurs within the try statement, that exception is handled by the appropriate exception handler associated with this try statement.
A try statement must be accompanied by at least one catch block or one finally block.
Catching & Handling Exceptions (catch block)
As you learned on the previous page, the try statement defines the scope of its associated exception handlers. You associate exception handlers with a try statement by providing one or more catch blocks directly after the try block:
try { ... } catch ( . . . ) { ... } catch ( . . . ) { ...
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 23 of 61
}...
There can be no intervening code between the end of the try statement and the beginning of the first catch statement. The general form of Java's catch statement is:
catch (SomeThrowableObject variableName) { Java statements }
The catch statement requires a single formal argument. The argument to the catch statement looks like an argument declaration for a method. The argument type, SomeThrowableObject, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class defined in the java.lang package.
You access the instance variables and methods of exceptions in the same manner that you access the instance variables and methods of other objects. getMessage is a method provided by the Throwable class that prints additional information about the error that occurred.
The writeList method from the ListOfNumbers class uses two exception handlers for its try statement, with one handler for each of the two types of exceptions that can be thrown within the try block -- ArrayIndexOutOfBoundsException and IOException.
try { ... } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); }
Catching & Handling Exceptions (catch block) - Contd.
The two exception handlers used by the writeList method are very specialized. Each handles only one type of exception. The Java language allows you to write general exception handlers that handle multiple types of exceptions.
Java exceptions are Throwable objects; they are instances of Throwable or a subclass of Throwable. The Java packages contain numerous classes that derive from Throwable and thus, build a hierarchy of Throwable classes.
Your exception handler can be written to handle any class that inherits from Throwable. If you write a handler for a "leaf" class (a class with no subclasses), you've written a specialized handler: it will only handle exceptions of that specific type.
If you write a handler for a "node" class (a class with subclasses), you've written a general handler: it will handle any exception whose type is the node class or any of its subclasses.
Let's modify the writeList method once again. Only this time, let's write it so that it handles both IOExceptions and ArrayIndexOutOfBoundsExceptions. The closest common ancester of IOException and ArrayIndexOutOfBoundsException is the Exception class. An exception handler that handles both types of exceptions looks like this:
try { ... } catch (Exception e) { System.err.println("Exception caught: " + e.getMessage()); }
The Exception class is pretty high in the Throwable class hierarchy. So in addition to the IOException and ArrayIndexOutOfBoundsException types that this exception handler is intended to catch, it will catch numerous other types.
Generally speaking, your exception handlers should be more specialized. Handlers that can catch most or all exceptions are typically useless for error recovery because the handler has to determine what type of exception occurred anyway to determine the best recovery strategy. Also, exception handlers that are too general can make code more error prone by catching and handling exceptions that weren't anticipated by the programmer and for which the handler was not intended Catching & Handling Exceptions (finally block)
The final step in setting up an exception handler is providing a mechanism for cleaning up the state of the method before (possibly) allowing control to be passed to a different part of the program. You do this by enclosing the cleanup code within a finally block.
The try block of the writeList method that you've been working with opens a PrintWriter. The program should close that stream before allowing control to pass out of the writeList method. This poses a somewhat complicated problem because writeList's try block has three different exit possibilities: 1. The new FileWriter statement failed and threw an IOException. 2. The victor.elementAt(i) statement failed and threw an ArrayIndexOutOfBoundsException. 3. Everything succeeded and the try block exited normally.
The runtime system always executes the statements within the finally block regardless of what happens within the try block. Regardless of whether control exits the writeList method's try block due to one of the three scenarios listed previously, the code within the finally block will be executed.
This is the finally block for the writeList method. It cleans up and closes the PrintWriter.
finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } }
Putting it all together
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 24 of 61
The is how the writeList method is finally written:
public void writeList() { PrintWriter out = null; try { System.out.println("Entering try statement"); out = new PrintWriter( new FileWriter("OutFile.txt")); for (int i = 0; i < size; i++) out.println("Value at: " + i + " = " + victor.elementAt(i)); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } } }
This try block in this method has three different exit possibilities: 1. The new FileWriter statement fails and throws an IOException. 2. The victor.elementAt(i) statement fails and throws an ArrayIndexOutOfBoundsException. 3. Everything succeeds and the try statement exits normally.
Create situation (Change the name of the file to invalid name - make the filename start with '?') or any thing else to run your program through each one of the situations mentioned above
How to Throw Exceptions The Throw Statement
Before you can catch an exception, some Java code somewhere must throw one.
Any Java code can throw an exception: your code, code from a package written by someone else (such as the packages that come with the Java development environment), or the Java runtime system.
Regardless of who (or what) throws the exception, it's always thrown with the Java throw statement.
All Java methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. In the Java system, throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement:
throw someThrowableObject;
If you attempt to throw an object that is not throwable, the compiler refuses to compile your program and displays an error message similar to the following:
testing.java:10: Cannot throw class java.lang.Integer; it must be a subclass of class java.lang.Throwable. throw new Integer(4);
Let's look at the throw statement in context. The following method is taken from a class that implements a common stack object. The pop method removes the top element from the stack and returns it:
public Object pop() throws EmptyStackException { Object obj; if (size == 0) throw new EmptyStackException(); obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj; }
Make note of the statements in bold.
Creating Your Own Exceptions
Create your own exception called InvalidBalanceException as follows:
public class InvalidBalanceException extends Exception { public InvalidBalanceException() { } public InvalidBalanceException(String msg) { super(msg); } }
Now write Account.java as follows:
public class Account {
public void creditAccount() throws InvalidBalanceException {
if (true) { // balance is not sufficient then throw new InvalidBalanceException("Insufficient Balance"); } } }
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 25 of 61
Write AccountsApp.java as follows:
public class AccountsApp { public static void main(String args[]) {
Account acc = new Account(); /* please note that following method invocation must * be in try catch block. Surround it with try catch block * and print the error message in the catch block. */ acc.creditAccount();
} }
Note that you can also extend one of your own exceptions from any of your own (some other exception) or from any exception already defined in java api(s).
More on Java Architecture Java Virtual Machine
What is JRE It is JavaTM runtime environment. A subset of the Java Development Kit (JDK) for users and developers who want to redistribute the runtime environment. The Java runtime environment consists of the Java virtual machine (JVM), the Java core classes, and supporting files.
The JRE does not contain any of the development tools (such as appletviewer or javac) or classes that pertain only to a development environment.
The JRE for Win 32 platforms is bundled with its own installer program.
The availability of an easily installable JRE adds flexibility to the ways in which software suppliers can deliver software to their customers.
Vendors of applications have the option of not bundling a copy of the JRE with their software.
Java Virtual Machine (Contd.)
End-users can download and install the Windows JRE themselves.
Once a user has installed the JRE, it can be used to run any number of applications written in the Java programming language.
(JVM)—A component of the Java runtime environment that JIT-compiles Java bytecodes, manages memory, schedules threads, and interacts with the host operating environment (e.g., a Web browser running the Java program).
The JVM is the Java equivalent of the .NET Framework's CLR.
Java Virtual Machine (JVM) is a Java interpreter and runtime environment. Java source code is compiled into a format called bytecode (files with a .class extension), which can then be executed by a Java interpreter. Web browsers are often equipped with Java virtual machines.
JIT (Just-In-Time) Compilers
You first run "javac", the Java Compiler, which turns the Java code into what is known as "bytecodes" and puts them into the "hello.class" file.
This class file can then be interpreted on any machine which has a Java Virtual Machine on it. The key word here is "interpreted".
The Java Virtual Machine processes each of the bytecodes in the .class file and executes them. This is similar to what other interpreted languages do, such as Basic, LISP, and Smalltalk.
When a JIT is present, after reading in the .class file for interpretation, it hands the .class file to the JIT.
The JIT will take the bytecodes and compile them into native code for the machine that you are running on. It can actually be faster to grab the bytecodes, compile them, and run the resulting executable than it is to just interpret them. The JIT is an integral part of the Java Virtual Machine
Some environments allow you to choose whether or not to JIT code. The Byte Code Verification Process
Although Java compiler ensures that the source code doesn’t violate the safety rules, what if the runtime environment receives a .class file which is compiled by a hostile compiler.
The answer is simple: the Java run-time system does not trust the incoming code, but subjects it to bytecode verification.
The tests range from the simple verification of the code that the format of the code fragment is correct, to passing each code fragment through a simple theorem prover to establish that it plays by the rule: It doesn’t forge (fake) pointers. It doesn’t violate access restrictions It accesses objects as what they are (for e.g. Thread objects are used as thread objects and not anything else) Object field accesses are known to be legal – private public or protected.
Java is a language that is safe, plus run-time verification of generated code, establishes a base set of guarantees that interfaces cannot be violated
The Byte Code Verifier
The Byte Code verifier traverses the bytecodes, constructs the type state information, and verifies the type of parameters to all the bytecode instructions
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 26 of 61
Assignment(s) Exception Handling Assignment
Write a class Invoice which will have a method called saveInvoice. It must throw InsufficientInventoryException, InsufficientCustomerCreditLimitException and InvalidOrderException.
Write a class InvoiceManager with a main method and invoke saveInvoice method on Invoice from it. Catch the appropriate exceptions and compile the class
Chapter: 4 - Threads What is a Thread ? What is a Thread ?
We write lot of programs where each has a beginning, an execution sequence, and an end.
A thread is similar to the sequential programs.
A single thread also has a beginning, a sequence, and an end and at any given time during the runtime of the thread, there is a single point of execution.
However, a thread itself is not a program; it cannot run on its own. Rather, it runs within a program. The following figure shows this relationship.
Definition of Thread
A thread is a single sequential flow of control within a program (Process)
There is nothing new in the concept of a single thread.
The real hoopla surrounding threads is not about a single sequential thread.
Rather, it's about the use of multiple threads in a single program, running at the same time and performing different tasks.
This is illustrated by the following figure:
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 27 of 61
Definition of Thread (Contd.)
Some texts use the name lightweight process instead of thread.
A thread is similar to a real process in that a thread and a running program are both a single sequential flow of control.
A thread is considered lightweight because it runs within the context of a full-blown program and takes advantage of the resources allocated for that program and the program's environment.
As a sequential flow of control, a thread must carve out some of its own resources within a running program.
The code running within the thread works only within the context of the program (process). Thus, some other texts use execution context as a synonym for thread.
Using Timer & Timer Task Using Timer & Timer Task
In version 1.3, support for timers was added to the java.util package. The Timer class in that package schedules instances of a class called TimerTask . See: Remider.java
import java.util.Timer; import java.util.TimerTask; /** * Simple demo that uses java.util.Timer to schedule a task to execute * once 5 seconds have passed. */ public class Reminder { Timer timer; public Reminder(int seconds) { timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); } class RemindTask extends TimerTask { public void run() { System.out.println("Time's up!"); timer.cancel(); //Terminate the timer thread } } public static void main(String args[]) { System.out.println("About to schedule task."); new Reminder(5); System.out.println("Task scheduled."); } }
When you run the example, you first see this:
Task scheduled.
Five seconds later, you see this: Time's up!
This simple program illustrates the basic parts of implementing and scheduling a task to be executed by a timer thread. Implement a custom subclass of TimerTask. The run method contains the code that performs the task. In this example, the subclass is named RemindTask. Create a thread by instantiating the Timer class. Instantiate the timer task object (new RemindTask()). Schedule the timer task for execution. The example uses the schedule method, with the timer task as the first argument and the delay in milliseconds (5000) as the second argument.
Another way of scheduling a task is to specify the time when the task should execute. For example, the following code schedules a task for execution at 11:01 p.m.:
//Get the Date corresponding to 11:01:00 pm today. Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 0); Date time = calendar.getTime(); timer = new Timer(); timer.schedule(new RemindTask(), time);
Stopping Timer Threads
By default, a program keeps running as long as its timer threads are running. You can terminate a timer thread in more than 1 ways: Invoke cancel on the timer. You can do this from anywhere in the program, such as from a timer task’s run method. Invoke the System.exit method, which makes the entire program (and all its threads) exit. The Reminder example uses the first scheme, invoking the cancel method from the timer task’s run method.
Sometimes, timer threads aren’t the only threads that can prevent a program from exiting when expected. For example, if you use the AWT at all—even if only to make beeps—the AWT automatically creates a nondaemon thread that keeps the program alive.
The following modification of Reminder adds beeping, which requires us to also add a call to the System.exit method to make the program exit. Significant changes are in boldface:
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 28 of 61
import java.util.Timer; import java.util.TimerTask; import java.awt.Toolkit; /** * Simple demo that uses java.util.Timer to schedule a task to execute * once 5 seconds have passed. */ public class ReminderBeep { Toolkit toolkit; Timer timer; public ReminderBeep(int seconds) { toolkit = Toolkit.getDefaultToolkit(); timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); } class RemindTask extends TimerTask { public void run() { System.out.println("Time's up!"); toolkit.beep(); //timer.cancel(); //Not necessary because we call System.exit System.exit(0); //Stops the AWT thread (and everything else) } } public static void main(String args[]) { System.out.println("About to schedule task."); new ReminderBeep(5); System.out.println("Task scheduled."); } }
Performing a Task Repeatedly
Write the following AnnoyingBeep.java to repeat the task after evey 1 second:
import java.util.Timer; import java.util.TimerTask; import java.awt.Toolkit; /** * Schedule a task that executes once every second. */ public class AnnoyingBeep { Toolkit toolkit; Timer timer; public AnnoyingBeep() { toolkit = Toolkit.getDefaultToolkit(); timer = new Timer(); timer.schedule(new RemindTask(), 0, //initial delay 1 * 1000); //subsequent rate } class RemindTask extends TimerTask { int numWarningBeeps = 3; public void run() { if (numWarningBeeps > 0) { toolkit.beep(); System.out.println("Beep!"); numWarningBeeps--; } else { toolkit.beep(); System.out.println("Time's up!"); //timer.cancel(); //Not necessary because we call System.exit System.exit(0); //Stops the AWT thread (and everything else) } } } public static void main(String args[]) { System.out.println("About to schedule task."); new AnnoyingBeep(); System.out.println("Task scheduled."); } }
Customizing Threads run Method Customizing a Thread's run Method
The run method gives a thread something to do. Its code implements the thread's running behavior.
It can do anything that can be encoded in Java statements: compute a list of prime's, sort some data, perform some animation.
The Thread class implements a generic thread that, by default, does nothing. That is, the implementation of its run method is empty. This is not particularly useful, so the Thread class defines API that lets a Runnable object provide a more interesting run method for a thread.
You can provide a run method for a thread by Subclassing Thread and Overriding run
Subclassing Thread and Overriding run
The first way to customize what a thread does when it is running is to subclass Thread (itself a Runnable object) and override its empty run method so that it does something. Let's look at the SimpleThread class (we will write a class to use this class later), the first of two classes in this example, which does just that:
public class SimpleThread extends Thread { public SimpleThread(String str) { super(str); } public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + getName()); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {}
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 29 of 61
} System.out.println("DONE! " + getName()); } }
The first method in the SimpleThread class is a constructor that takes a String as its only argument. This constructor is implemented by calling a superclass constructor and is interesting to us only because it sets the Thread's name, which is used later in the program.
The next method in the SimpleThread class is the run method. The run method is the heart of any Thread and where the action of the Thread takes place.
The run method of the SimpleThread class contains a for loop that iterates ten times. In each iteration the method displays the iteration number and the name of the Thread, then sleeps for a random interval of up to 1 second.
After the loop has finished, the run method prints DONE! along with the name of the thread. That's it for the SimpleThread class. The TwoThreadsDemo class provides a main method that creates two SimpleThread threads: one is named "Jamaica" and the other is named "Fiji". (If you can't decide on where to go for vacation you can use this program to help you decide--go to the island whose thread prints "DONE!" first.)
public class TwoThreadsDemo { public static void main (String[] args) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); } }
The main method also starts each thread immediately following its construction by calling the start method.
Assignment(s) Thread Assignments
Convert AnnoyingBeep.java (that we have already written) so that the initial delay is 5 seconds, instead of 0.
Write a class called TraningNomination.java which help you decide which subject you must nominate for training - J2EE or .NET. Hint: Use the same concept we have used in TwoThreadsDemo class.
Chapter: 5 - Colllection API Collection Framework The Collection Framework
A Collection (sometimes called as container) is simple an object that groups multiple objects in single element
Collections are used to store, retrieve and manipulate data, and to transmit data from one method to another
A collections framework is a unified architecture for representing and manipulating collections
All collections frameworks contain three things: Interfaces: abstract data types representing collections. Interfaces allow collections to be manipulated independently of the details of their representation. In objectoriented languages like Java, these interfaces generally form a hierarchy. Implementations: concrete implementations of the collection interfaces. In essence, these are reusable data structures. Algorithms: methods that perform useful computations, like searching and sorting, on objects that implement collection interfaces. These algorithms are said to be polymorphic because the same method can be used on many different implementations of the appropriate collections interface. In essence, algorithms are reusable functionality
The Collection Framework API
The core collection interfaces are the interfaces used to manipulate collections, and to pass them from one method to another.
The basic purpose of these interfaces is to allow collections to be manipulated independently of the details of their representation.
The core collection interfaces are the heart and soul of the collections framework.
When you understand how to use these interfaces, you know most of what there is to know about the framework.
The core collections interfaces are shown on the next slide:
Collection Framework API (Contd).
The core collection interfaces form a hierarchy includes A Set is a special kind of Collection, and a SortedSet is a special kind of Set, and so forth.
Note also that the hierarchy consists of two distinct trees: a Map
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 30 of 61
The Collection Interface
The Collection interface is the root of the collection hierarchy.
A Collection represents a group of objects, known as its elements.
Some Collection implementations allow duplicate elements and others do not.
Some are ordered and others unordered.
Collection is used to pass collections around and manipulate them when maximum generality is desired.
The Set Interface
A Set is a collection that cannot contain duplicate elements.
This interface models the mathematical set abstraction.
It is used to represent sets like the cards comprising a poker hand, the courses making up a student's schedule, or the processes running on a machine
The List Interface
A List is an ordered collection (sometimes called a sequence).
Lists can contain duplicate elements.
The user of a List generally has precise control over where in the List each element is inserted.
The user can access elements by their integer index (position).
If you've used Vector , you're already familiar with the general flavor of List
The Map Interface
A Map is an object that maps keys to values.
Maps cannot contain duplicate keys: Each key can map to at most one value.
If you've used Hashtable , you're already familiar with the general flavor of Map
The Collection Interface Features on Collection Interface
This interface, given that a Collection represents a group of objects, it has methods to tell you how many elements are in the collection (size, isEmpty), to check if a given object is in the collection (contains), to add and remove an element from the collection (add, remove), and to provide an iterator over the collection (iterator).
The add method is defined generally enough so that it makes sense for collections that allow duplicates as well as those that don't.
The add method guarantees that the Collection will contain the specified element after the call completes, and returns true if the Collection changes as a result of the call.
Similarly, the remove method is defined to remove a single instance of the specified element from the Collection, assuming the Collection contains the element, and to return true if the Collection was modified as a result
Your first Collection program
Write a new class called SimpleCollection.java as follows:
import java.util.Collection; import java.util.ArrayList; import java.util.Iterator; public class SimpleCollection { public SimpleCollection() { }
public static void main(String agrs[]) { Collection myCustomers = new ArrayList(); myCustomers.add("IBM"); myCustomers.add("ATOS Origin"); myCustomers.add("3I - Infotech");
Iterator i = myCustomers.iterator(); while (i.hasNext()) { String customer = (String) i.next(); System.out.println("The Customer Name is : " + customer); } } }
Compile and run this class and see the results.
Note the use of implementation class : ArrayList
Also Note the use of Iterator which provides standard mechanism of iterating through the
Array Operations
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input.
They allow the contents of a Collection to be translated into an array. The simple form with no arguments creates a new array of Object. The more complex form allows the caller to provide an array or to choose the runtime type of the output array.
Write the following snippet in the program written earlier
Page 31 of 61
Object[] arrayOfObjects = myCustomers.toArray()
Use a for loop and display the contents of the Object array.
Suppose myCustomers is known to contain only strings. The following snippet dumps the contents of c into a newly allocated array of String whose length is identical to the number of elements in myCustomers.
String[] arrayOfStrings = (String[]) myCustomers.toArray(new String[0]);
Write a for loop to display the contents of the String array
Bulk Operations
The bulk operations perform some operation on an entire Collection in a single shot. They are shorthands in the sense that each of them can be simulated, perhaps less efficiently, using the operations described above. containsAll: Returns true if the target Collection contains all of the elements in the specified Collection (c). addAll: Adds all of the elements in the specified Collection to the target Collection. removeAll: Removes from the target Collection all of its elements that are also contained in the specified Collection. retainAll: Removes from the target Collection all of its elements that are not also contained in the specified Collection. That is to say, it retains only those elements in the target Collection that are also contained in the specified Collection. clear: Removes all elements from the Collection.
The addAll, removeAll, and retainAll methods all return true if the target Collection was modified in the process of executing the operation.
As a simple example of the power of the bulk operations, consider following idiom to remove all instances of a specified element, e from a Collection, c.: c.removeAll(Collections.singleton(e));
More specifically, suppose that you want to remove all of the null elements from a Collection: c.removeAll(Collections.singleton(null));
This idiom uses Collections.singleton, which is a static factory method that returns an immutable Set containing only the specified element. Use these methods in the program specified on previous slide and see the results.
The Set Interface The Set
A Set is a Collection that cannot contain duplicate elements.
Set models the mathematical set abstraction.
The Set interface extends Collection and contains no methods other than those inherited from Collection.
It adds the restriction that duplicate elements are prohibited
One of the general-purpose implementation of Set interface is : HashSet which stores its elements in Hashtable and the other implementation is TreeSet
Methods on Set Interface
The Set interface is shown below:
public interface Set { // Basic Operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); // Optional boolean remove(Object element); // Optional Iterator iterator(); // Bulk Operations boolean containsAll(Collection c); boolean addAll(Collection c); // Optional boolean removeAll(Collection c); // Optional boolean retainAll(Collection c); // Optional void clear(); // Optional // Array Operations Object[] toArray(); Object[] toArray(Object a[]); }
Here's a simple but useful Set idiom. Suppose you have a Collection, c, and you want to create another Collection containing the same elements, but with all duplicates eliminated. The following one-liner does the trick: Collection noDups = new HashSet(c);
It works by creating a Set (which, by definition, cannot contain duplicates) initially containing all the elements in c.
Try the above in your program written earlier. Create a collection which will have duplicates, loop through it and then create another collection as shown above and then again loop through it so that only unique values are displayed
Basic Operations
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
The size operation returns the number of elements in the Set (its cardinality).
The isEmpty method does exactly what you think it does.
The add method adds the specified element to the Set if it's not already present, and returns a boolean indicating whether the element was added.
Similarly, the remove method removes the specified element from the Set if it's present, and returns a boolean indicating whether the element was present.
The iterator method returns an Iterator over the Set.
Page 32 of 61
Basic Operations (Contd.)
Here's a little program that takes the words in its argument list and prints out any duplicate words, the number of distinct words, and a list of the words with duplicates eliminated:
import java.util.*; public class FindDups { public static void main(String args[]) { Set s = new HashSet(); for (int i=0; i<args.length; i++) if (!s.add(args[i])) System.out.println("Duplicate detected: "+args[i]); System.out.println(s.size()+" distinct words detected: "+s); } }
Now let's run the program and pass the following command line arguments: java FindDups i came i saw i left
The results will be as follows:
Duplicate detected: i Duplicate detected: i 4 distinct words detected: [came, left, saw, i]
The implementation type of the Set in the example above is HashSet, which makes no guarantees as to the order of the elements in the Set.
If you want the program to print the word list in alphabetical order, all you have to do is to change the set's implementation type from HashSet to TreeSet.
Making this trivial one-line change causes the command line in the previous example to generate the following output:
% java FindDups i came i saw i left Duplicate word detected: i Duplicate word detected: i 4 distinct words detected: [came, i, left, saw]
Note that the example code always refers to the collection by its interface type (Set), rather than by its implementation type (HashSet). This is a strongly recommended programming practice, as it gives you the flexibility to change implementations merely by changing the constructor. If the variables used to store a collection, or the parameters used to pass it around, are declared to be of the collection's implementation type rather than its interface type, then all such variables and parameters must be changed to change the collection's implementation type. Furthermore, there's no guarantee that the resulting program will work; if the program uses any non-standard operations that are present in the original implementation type but not the new one, the program will fail. Referring to collections only by their interface keeps you honest, in the sense that it prevents you from using any non-standard operations. Bulk Operations
The bulk operations are particularly well suited to Sets: they perform standard set-algebraic operations. Suppose s1 and s2 are Sets.
s1.containsAll(s2): Returns true if s2 is a subset of s1. (For example, set s1 is a subset of s2 if set s2 contains all the elements in s1.)
s1.addAll(s2): Transforms s1 into the union of s1 and s2. (The union of two sets is the set containing all the elements contained in either set.)
s1.retainAll(s2): Transforms s1 into the intersection of s1 and s2. (The intersection of two sets is the set containing only the elements that are common in both sets.)
s1.removeAll(s2): Transforms s1 into the (asymmetric) set difference of s1 and s2. (For example, the set difference of s1 - s2 is the set containing all the elements found in s1 but not in s2.) Work out each one of these with a set The array operations don't do anything special for Sets beyond what they do for any other Collection.
The List Interface The List Interface
A Listis an ordered Collection(sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for: Positional Access: manipulate elements based on their numerical position in the list. Search: search for a specified object in the list and return its numerical position. List Iteration: extend Iterator semantics to take advantage of the list's sequential nature. Range-view: perform arbitrary range operations on the list.
The List interface is shown below:
public interface List extends Collection { // Positional Access Object get(int index); Object set(int index, Object element); // Optional void add(int index, Object element); // Optional Object remove(int index); // Optional abstract boolean addAll(int index, Collection c); // Optional // Search int indexOf(Object o); int lastIndexOf(Object o); // Iteration ListIterator listIterator();
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 33 of 61
ListIterator listIterator(int index); // Range-view List subList(int from, int to); }
The JDK contains two general-purpose List implementations. ArrayList, which is generally the best-performing implementation, and LinkedListwhich offers better performance under certain circumstances. Also, Vector has been retrofitted to implement List.
Collection Operations
The remove operation always removes the first occurrence of the specified element from the list.
The add and addAll operations always append the new element(s) to the end of the list. Thus, the following idiom concatenates one list to another:
list1.addAll(list2);
Here's a non-destructive form of this idiom, which produces a third List consisting of the second list appended to the first:
List list3 = new ArrayList(list1); list3.addAll(list2);
Two List objects are equal if they contain the same elements in the same order
Positional Access
Create a list object in the new class called MySimpleList.java and write the following as follows:
List listOfCustomers = new ArrayList(); listOfCustomers.add("IBM"); listOfCustomers.add("3I"); listOfCustomers.add("Infy"); listOfCustomers.add("i-flex"); for (int i = 0; i < listOfCustomers.size(); i++) { System.out.println("The customer is : " + listOfCustomers.get(i)); }
Note that the list can accessed using its position.
Now create a list using: Arrays.asList(args) - which helps you to create a list out of an array and see the results
ListIterator
As you'd expect, the Iterator returned by List's iterator operation returns the elements of the list in proper sequence.
Additionally, List provides a richer iterator, called a ListIterator, that allows you to traverse the list in either direction, modify the list during iteration, and obtain the current position of the iterator.
The ListIterator interface is summarized below (including the three methods it inherits from Iterator):
public interface ListIterator extends Iterator { boolean hasNext(); Object next(); boolean hasPrevious(); Object previous(); int nextIndex(); int previousIndex(); void remove(); void set(Object o); void add(Object o);
// Optional // Optional // Optional
}
The three methods that ListIterator inherits from Iterator (hasNext, next, and remove) are intended to do exactly the same thing in both interfaces.
The hasPrevious and previous operations are exact analogues of hasNext and next. The former operations refer to the element before the (implicit) cursor, whereas the latter refer to the element after the cursor
ListIterator (Contd.)
Here's the standard idiom for iterating backwards through a list:
for (ListIterator i=l.listIterator(l.size()); i.hasPrevious(); ) { Foo f = (Foo) i.previous(); ... }
Try out this code snippet in your program. And also write code to traverse forward and see the results.
Range-View Operations
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 34 of 61
The range-view operation, subList(int fromIndex, int toIndex), returns a List view of the portion of this list whose indices range from fromIndex, inclusive, to toIndex, exclusive. This half-open range mirrors the typical for-loop:
for (int i=fromIndex; i
As the term view implies, the returned List is backed by the List on which subList was called, so changes in the former List are reflected in the latter.
This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a List can be used as a range operation by passing a subList view instead of a whole List. For example, the following idiom removes a range of elements from a list:
list.subList(fromIndex, toIndex).clear();
Similar idioms may be constructed to search for an element in a range:
int i = list.subList(fromIndex, toIndex).indexOf(o); int j = list.subList(fromIndex, toIndex).lastIndexOf(o);
Note that the above idioms return the index of the found element in the subList, not the index in the backing List.
Try out each one of the above given code snippets in your prorgam and see the results.
Algorithms
Most of the polymorphic algorithms in the Collections class apply specifically to List. Having all of these algorithms at your disposal makes it very easy to manipulate lists.
Here's a summary of these algorithms, which are described in more detail in the Algorithms lesson. sort(List): Sorts a List using a merge sort algorithm, which provides a fast, stable sort. (A stable sort is one that does not reorder equal elements.) shuffle(List): Randomly permutes the elements in a List. (Shown above.) reverse(List): Reverses the order of the elements in a List. fill(List, Object): Overwrites every element in a List with the specified value. copy(List dest, List src): Copies the source List into the destination List. binarySearch(List, Object): Searches for an element in an ordered List using the binary search algorithm. Returns positive integer if found and negative if not found
Try out each one of these in your program and see the results
The Map Interface The Map Interface
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. The Map interface is shown below:
public interface Map { // Basic Operations Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); // Bulk Operations void putAll(Map t); void clear(); // Collection Views public Set keySet(); public Collection values(); public Set entrySet(); // Interface for entrySet elements public interface Entry { Object getKey(); Object getValue(); Object setValue(Object value); } }
The JDK contains two new general-purpose Map implementations. HashMap, which stores its entries in a hash table, is the best-performing implementation. TreeMap, which stores its entries in a red-black tree, guarantees the order of iteration.
The Basic Operations
The basic operations (put, get, remove, containsKey, containsValue, size, and isEmpty)
Here's a simple program to generate a frequency table of the words found in its argument list. The frequency table maps each word to the number of times it occurs in the argument list.
import java.util.*; public class Freq { private static final Integer ONE = new Integer(1); public static void main(String args[]) { Map m = new HashMap(); // Initialize frequency table from command line for (int i = 0; i < args.length; i++) { Integer freq = (Integer) m.get(args[i]); m.put(args[i], (freq == null ? ONE : new Integer(freq.intValue() + 1))); } System.out.println(m.size() + " distinct words detected:"); System.out.println(m); } }
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
The only thing even slightly tricky about this program is the second argument of the put statement. It's a conditional expression that has the effect of setting the frequency to one if the word has never been seen before, or one more than its current value if the word has already been seen.
Execute the program as follows:
Page 35 of 61
java Freq if it is to be it is up to me to delegate 8 distinct words detected: {to=3, me=1, delegate=1, it=2, is=2, if=1, be=1, up=1}
Suppose you'd prefer to see the frequency table in alphabetical order. All you have to do is change the implementation type of the Map from HashMap to TreeMap. Make this change and execute your program and see the results.
Bulk Operations
The clear operation does exactly what you think it does: it removes all of the mappings from the Map.
The putAll operation is the Map analogue of the Collection interface's addAll operation.
The following one-liner creates a new HashMap initially containing all of the same key-value mappings as m:
Map copy = new HashMap(m);
Try out each one of these and see the results
Collection Views
The Collection-view methods allow a Map to be viewed as a Collection in three ways: keySet: the Set of keys contained in the Map. values: The Collection of values contained in the Map. This Collection is not a Set, as multiple keys can map to the same value. entrySet: The Set of key-value pairs contained in the Map. The Map interface provides a small nested interface called Map.Entry that is the type of the elements in this Set.
The Collection-views provide the only means to iterate over a Map. Here's an example illustrating the standard idiom for iterating over the keys in a Map:
for (Iterator i=m.keySet().iterator(); i.hasNext(); ) System.out.println(i.next());
The idiom for iterating over values is analogous. Here's the idiom for iterating over key-value pairs:
for (Iterator i=m.entrySet().iterator(); i.hasNext(); ) { Map.Entry e = (Map.Entry) i.next(); System.out.println(e.getKey() + ": " + e.getValue()); }
With all three Collection-views, calling an Iterator's remove operation removes the associated entry from the backing Map
With the entrySet view, it is also possible to change the value associated with a key, by calling a Map.Entry's setValue method during iteration Try out each of above code snippets and see the results
Assignment(s) The Collection Assignment(s)
Write a class to demonstrate the adding and reading employee names using Collection Interface
Write a class to demonstrate the adding and reading department names in your company using List Interface
Write a program which will initialize one Collection with some names and then copy the same to another List.
Write a class which will demonstrate a Set which will accept only unique values. Try putting duplicate values, still it must contain only unique values.
Create a Map which will hold id and names of Customers. Put the values, read them and then display the same.
Chapter: 6 - JDBC API Getting Started What is JDBC
JDBC is the mechanism of talking to the database.
It involves: Loading the appropriate database driver, Establishing Connection and then Executing the SQL statements as per your business logic
In the following sub-topics and pages we are going to discuss all of these.
Setting up the Database Driver
We are going to use JDBC-ODBC Bridge driver to get connected to Oracle / MS-SQL server database.
Go to Control Panel >> Administrative Tools >> Data Sources (ODBC)
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Click on Add button to add a new DSN (Data Source Name). This will provide you with the list of ODBC Drivers installed on your machine. Select Oracle or MS SQL Server. If it is Oralce, enter the name for your datasource, enter the username, password and servicename (put service name only if the database is not on your machine - The service name is as same as service name given in tnsnames.ora file).
Test your DSN settings by clicking on Test Connection and then save the Data Source
Now you are goiing always going to use the DSN name just given to the data-source each time you get connection after loading the driver. - We will come to this very soon. - For now please remember the DSN name
Page 36 of 61
Create Tables
Please create the following tables in your database:
Customer (id number (5), name varchar (25), address varchar(25), cityId number (5)) Product (id number (5), name varchar (25), rate number (7) )
Put some meaningful data in to the tables created (please put meaningful data - do not put something like: yabadabadoo). Use Sql-Plus (If Oracle) or SQL Query Manager (If MS Sql Server) to insert at least 7 to 10 rows in each table.
Loading Driver
The first thing you need to do is establish a connection with the DBMS you want to use. This involves two steps: (1) loading the driver and (2) making the connection.
Loading Drivers Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code:
Class.forName("jdbc.DriverXYZ");
You do not need to create an instance of a driver and register it with the DriverManager because calling Class.forName will do that for you automatically. If you were to create your own instance, you would be creating an unnecessary duplicate, but it would do no harm.
When you have loaded a driver, it is available for making a connection with a DBMS.
Establishing Connection
The second step in establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:
Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");
This step is also simple, with the hardest thing being what to supply for url . If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: . The rest of the URL is generally your data source name or database system. So, if you are using ODBC to access an ODBC data source called "Sales" for example, your JDBC URL could be jdbc:odbc:Sales. In place of "myLogin" you put the name you use to log in to the DBMS; in place of "myPassword" you put your password for the DBMS.
If you are using a JDBC driver developed by a third party, the documentation will tell you what subprotocol to use, that is, what to put after jdbc: in the JDBC URL. For example, if the driver developer has registered the name acme as the subprotocol, the first and second parts of the JDBC URL will be jdbc:acme: . The driver documentation will also give you guidelines for the rest of the JDBC URL. This last part of the JDBC URL supplies information for identifying the data source.
If one of the drivers you loaded recognizes the JDBC URL supplied to the method DriverManager.getConnection , that driver will establish a connection to the DBMS specified in the JDBC URL.
The connection returned by the method DriverManager.getConnection is an open connection you can use to create JDBC statements that pass your SQL statements to the DBMS. In the previous example, con is an open connection, and we will use it in the examples that follow.
Retrieving Values from DBMS Retrieving Values from Database
The SELECT statements can be executed from a program written in the Java programming language and we get the results we showed.
JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results.
The following code demonstrates declaring the ResultSet object rs and assigning the results of our earlier query to it:
ResultSet rs = stmt.executeQuery("Select id, name, address, cityId from Customer");
Surround all the code you write in try catch block catching SQLException.
Using the next method
The variable rs , which is an instance of ResultSet , contains the rows of Customers shown in the result set example above.
In order to access the id, name, address and cityId, we will go to each row and retrieve the values according to their types.
The method next moves what is called a cursor to the next row and makes that row (called the current row) the one upon which we can operate.
The cursor is initially positioned just above the first row of a ResultSet object, the first call to the method next moves the cursor to the first row and makes it the current row.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 37 of 61
Successive invocations of the method next move the cursor down one row at a time from top to bottom. Note that with the JDBC 2.0 API, covered in the next section, you can move the cursor backwards, to specific positions, and to positions relative to the current row in addition to moving the curs or forward.
Using the getter Methods on ResultSet
We use the getXXX method of the appropriate type to retrieve the value in each column.
For example, the first column in each row of rs is id , which stores a value of SQL type NUMBER . The method for retrieving a value of SQL type NUMBER is getInt.
The second column in each row stores a value of SQL type VARCHAR , and the method for retrieving values of that type is getString.
The following code accesses the values stored in the current row of rs and prints a line with the id followed by name. Each time the method next is invoked, the next row becomes the current row, and the loop continues until there are no more rows in rs:
String query = "SELECT id, name, address, cityId from Customer"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println(id + " " + name); }
Write the program now, execute it and see the results.
So if you wanted to retrieve a float value then you will use getFloat, for date - getDate and so on. Also, you can get the values from ResultSet using getter methods passing number as parameter specifying the number of the column, the value of which you want to retrieve You can retrieve any data type column with getSring method. Java wll implicitly convert the data retrieved to String
Updating & Deleting Values Updating Values
Suppose the address a customer with id = 101 changes to "Mumbai".
Write a new class called UpdateData.java. Load the drivers, get the connection and create statement the same way you did in earlier program.
Only, this time write
String sql = "Update Customer set address = 'Mumbai' where id = 101"; stmt.executeUpdate(sql);
Compile and execute your program. Re-Run the program written earlier to print values, and see that the address is changed (Only do not forget to change the previous program to get address and include it in SOP)
Now try Deleting. You figure out what you need to write in DeleteData.java
Using Prepared Statements When to Use Prepared Statement
Sometimes it is more convenient or more efficient to use a PreparedStatement object for sending SQL statements to the database. This special type of statement is derived from the more general interface, Statement, that you already know.
The PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first.
Although PreparedStatement objects can be used for SQL statements with no parameters, you will probably use them most often for SQL statements that take parameters.
The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it. You will see an example of this in the following sections.
Creating the PreparedStatement
Write a new class called MyPreparedStatement.java with the following code in it (Load Drivers, and Establish Connection as done earlier)
if (args.length == 0) { System.out.println("Invalid Parameter"); } String sql = "Select name, address, cityId from Customer where id = ?"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setInt(1, new Integer(args[0]).intValue()); ResultSet rs = stmt.executeQuery();
Note that this program expects a command line argument. The data retrieved will be based on the id passed as argument. Write while loop to traverse through the ResultSet as done earlier.
Try out the PreparedStatement for update & delete as well.
executeUpdate method returns int value - which indicates the total number of rows that were affected.
Using Joins
Create a one more table called City (id number (5), name varchar(5)). Put atleast 7-to-10 rows in it. Now update the Customer table to set the value of cityId of each row to any one of the id specified in City table. For e.g. If there is a city with id: 101 and name Mumbai in city table then make atleast 1 row in Customer table where value of cityId = 101. Do this using Sql-Plus (If Oracle) or Query Analyzer (If MS-Sql Server)
Now write a program to retrieve all Customers joining it with City table and display id, name, address from customer table and corresponding city name from City table.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 38 of 61
Using Transactions What is one unit of Work ?
There are times when you do not want one statement to take effect unless another one also succeeds.
Consider: you have some business logic to execute which involves inserting rows in few tables, delete rows from some other tables and also updating a row or a two in some tables. You say this is one single unit of work
As per your business logic - either everything must be successful or everything must be undone.
This is called committing or rolling back.
In order to make this happen, you will have to make all your inserts, updates and deletes a part of transaction and either commit or rollback the transaction as per your exception-handling mechanism.
Setting the Auto Commit attribute of Connection
Before you start inserting, updating or deleting, invoke con.setAutoCommit(false). Then after everything was successful, you use con.commit() or else invoke con.rollback().
In order to get hands-on practice on this, do the following: Create a table Called CustomerAddress (customerId number (5), addressline1 varchar (20), addressline2 varchar (20), addressline3 varchar (20)) The primary key in this table is customerId + addressline1 The addressline1 cannot be left null Write a program called CustomerManager.java a. which will insert 1 customer row in Customer table b. 1 or more than 1 Customer addresses for the Customer inserted c. Here Customer is a composite of CustomerAddress d. Hence it must be ensured that atleast 1 address of the customer and also that if any one of the customer address creation fails, the insert in Customer must also fail Use con.setAutoCommit(false) immediately after creating connection object Use con.commit() only after customer and customer addresses are all successfully inserted Use con.rollback(), even if one address creation fails
Write this prorgam and execute it and see the results. Deliberately keep addressline1 null for one of the addresses and see that everything gets rolled back.
Below is just a hint for you - write a complete prorgam yourself:
try { String sql = "Insert into Customer values (?, ?, ?, ?)"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setInt(1, 210); // set the other parameters using appropriate stmt.setter Method stmt.executeUpdate(); sql = "Insert into CustomerAddress (customerId, addressline1,"+ "addressline2, addressline3) values (?, ?, ?, ?)"; PreparedStatement addressStmt = con.prepareStatement(sql); stmt.setInt(1, 210); stmt.setString(2, "Lokhandwala"); stmt.setString(3, "Andheri W"); stmt.setString(3, "Suburban Mumbai"); addressStmt.executeUpdate(); // set the parameter values for the second address addressStmt.executeUpdate();
/* set the parameter values for the second address this time, deliberate set the value for addressLine 1 as null */ addressStmt.executeUpdate(); } catch (SQLException ex) { System.out.println("The error occurred [Rolling Back]: " + ex.getMessage()); con.rollback(); } try { con.commit(); } catch (SQLException ex) { }
Stored Procedures What is a Stored Procedure ?
A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. Stored procedures are used to encapsulate a set of operations or queries to execute on a database server.
For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code.
Stored procedures can be compiled and executed with different parameters and results, and they may have any combination of input, output, and input/output parameters.
Stored procedures are supported by most DBMSs, but there is a fair amount of variation in their syntax and capabilities.
Lets now see how Stored Procedures can be executed from java.
Executing a Procedures
Create a procedure which returns a result set returning list of all Customers
Execute by creating a Callable Statement and then executing as follows:
CallableStatement cs = con.prepareCall("{call SHOW_CUSTOMERS}"); ResultSet rs = cs.executeQuery();
Assignment(s)
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 39 of 61
JDBC Assignments
Consider a Payroll application. The tables identified for the same are as follows Employee (id number(5), firstname varchar(20), lastname varchar(20), address varchar(30), cityId number(5)) SalarySlip (id number(10), dateOfSlip date, employeeId number(5), amount number(8,2)) Department (id number(5), name varchar(20)) employeeId in SalarySlip is the foreign key of Employee.id.
Write 1 program to write, 1 to read, 1 to delete and 1 to update each of the tables mentioned above. When you insert rows in SalarySlip see to it that the employee id is any one of the id(s) in Employee table. Use prepared statement in each program
Write a program to display SalarySlips with Employee names from Employee table.
Write a program called SearchEmployee with main method that will accept command line argument as employee id. Your program must search an employee based on the id passed as command line argument and display firstname, lastname and address. If not found, it must display error message: "Employee with specified id does not exist".
Write another program called CreateEmployee to accept 5 arguments from command line. Insert a row in Employee table with exactly the values specified.First argument must be considered as id, second as firstname and so on. Remember that the command line argument are all strings - so convert it to appropriate type as per the requirement of your program.
JDBC Assignment(s) (Contd.)
Create program called DeleteEmployee as same as SearchEmployee written earlier, but instead of retrieving, delete the employee.
JSP & Servlets Chapter: 1 - JSP Basics What is a JSP Page ? The JSP
A JSP page is a text-based document
It contains two types of text: static template data, which can be expressed in any text-based format, such as HTML, WML, and XML; and JSP elements
It is the JSP elements that make up the dynamic content
The JSP elements also includes java code in scriplets (We will see scriplets in detail a bit later)
The java code is executed server side and if java code writes some contents to the response obect, the contents written to response object is rendered to the client
The response object is an implicit object (instantiated by the server). What ever contents are written to response object are rendered to the client. This is the standard concept of Web-Apps and not just specific to JSP. Your First JSP
JSP simply puts Java inside HTML pages. You can take any existing HTML page and change its extension to ".jsp" instead of ".html". In fact, this is the perfect exercise for your first JSP.
Create a html file which prints "Hello, world". Change its extension from ".html" to ".jsp". Now load the new file, with the ".jsp" extension, in your browser.
You will see the same output, but it will take longer! But only the first time. If you reload it again, it will load normally.
What is happening behind the scenes is that your JSP is being turned into a Java file, compiled and loaded. This compilation only happens once, so after the first load, the file doesn't take long to load anymore. (But everytime you change the JSP file, it will be re-compiled again.)
Creating Static & Dynamic Content Creating Static Content
You create static content in a JSP page by simply writing it as if you were creating a page that consisted only of that content.
Static content can be expressed in any text-based format, such as HTML, WML, and XML. The default format is HTML
If you want to use a format other than HTML, you include a page directive with the contentType attribute set to the format type at the beginning of your JSP page. For example, if you want a page to contain data expressed in the wireless markup language (WML), you need to include the following directive: <%@ page contentType="text/vnd.wap.wml"%>
A registry of content type names is kept by the IANA at : ftp://ftp.isi.edu/in-notes/iana/assignments/media-types Adding Dynamic Content Via Expressions
What makes JSP useful is the ability to embed Java. Put the following text in a file with .jsp extension (let us call it hello.jsp), place it in your JSP directory, and view it in a browser: Hello! The time is now <%= new java.util.Date() %>
Notice that each time you reload the page in the browser, it comes up with the current time.
The character sequences enclose Java expressions, which are evaluated at run time
This is what makes it possible to use JSP to generate dyamic HTML pages that change in response to user actions or vary from user to user.
Exercise: Write a JSP to output the values returned by System.getProperty for various system properties such as java.version, java.home, os.name, user.name, user.home, user.dir
jsp:include
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
The jsp:include element is processed when a JSP page is executed. The include action allows you to include either a static or dynamic resource in a JSP file
The results of including static and dynamic resources are quite different.
If the resource is static, its content is inserted into the calling JSP file. If the resource is dynamic, the request is sent to the included resource, the included page is executed, and then the result is included in the response from the calling JSP page.
The syntax for the jsp:include element is as follows:
Page 40 of 61
<jsp:include page="includedPage" />
Transferring Control to Another Web Component (jsp:forward)
The mechanism for transferring control to another Web component from a JSP page uses the functionality provided by the Java Servlet API
You access this functionality from a JSP page with the jsp:forward element: <jsp:forward page="/main.jsp" />
Param Element When an include or forward element is invoked, the original request object is provided to the target page.
If you wish to provide additional data to that page, you can append parameters to the request object with the jsp:param element: <jsp:include page="..." > <jsp:param name="param1" value="value1"/>
Life Cycle of JSP Page The Life Cycle of JSP
A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of JSP pages (in particular the dynamic aspects) are determined by Java Servlet technology.
When a request is mapped to a JSP page, it is handled by a special servlet that first checks whether the JSP page's servlet is older than the JSP page.
If it is, it translates the JSP page into a servlet class and compiles the class.
During development, one of the advantages of JSP pages over servlets is that the build process is performed automatically
Translation and Compilation
During the translation phase, template data is transformed into code that will emit the data into the stream that returns data to the client.
JSP elements are treated as follows: Directives are used to control how the Web container translates and executes the JSP page Scripting elements are inserted into the JSP page's servlet class. Elements of the form <jsp:XXX ... /> are converted into method calls to JavaBeans components or invocations of the Java Servlet API
Translation And Compilation Errors
Both the translation and compilation phases can yield errors that are only observed when the page is requested for the first time. However, some ide(s) can compile jsp(s) for you so that you can rectify the errors before you deploy
If an error occurs while the page is being translated (for example, if the translator encounters a malformed JSP element), the server will return a ParseException, and the servlet class source file will be empty or incomplete
The last incomplete line will give a pointer to the incorrect JSP element.
If an error occurs while the JSP page is being compiled (for example, there is a syntax error in a scriptlet), the server will return a JasperException and a message that includes the name of the JSP page's servlet and the line where the error occurred
JSP Instance Life - Cycle
Once the page has been translated and compiled, the JSP page's servlet for the most part follows the servlet life cycle
1. If an instance of the JSP page's servlet does not exist, the container: a. Loads the JSP page's servlet class b. Instantiates an instance of the servlet class c. Initializes the servlet instance by calling the jspInit method 2. Invokes the _jspService method, passing a request and response object.
Scriplets Adding Scriplets
JSP allows you to write blocks of Java code inside the JSP. You do this by placing your Java code between characters (just like expressions, but without the = sign at the start of
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 41 of 61
the sequence.)
This block of code is known as a "scriptlet". By itself, a scriptlet doesn't contribute any HTML (though it can, as we will see down below.) A scriptlet contains Java code that is executed every time the JSP is invoked.
<% // This is a scriptlet. Notice that the "date" // variable we declare here is available in the // embedded expression later on. System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <%= date %>
By itself a scriptlet does not generate HTML. If a scriptlet wants to generate HTML, it can use a variable called "out". The following example shows how the scriptlet can generate HTML output.
<% // This scriptlet declares and initializes "date" System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <% // This scriptlet generates HTML output out.println( String.valueOf( date )); %>
Mixing Scriplets & HTML
We have already seen how to use the "out" variable to generate HTML output from within a scriptlet. For more complicated HTML, using the out variable all the time loses some of the advantages of JSP programming. It is simpler to mix scriptlets and HTML.
Suppose you have to generate a table in HTML. This is a common operation, and you may want to generate a table from a SQL table, or from the lines of a file. But to keep our example simple, we will generate a table containing the numbers from 1 to N. Not very useful, but it will show you the technique.
Here is the JSP fragment to do it:
<% for ( int i = 0; i < n; i++ ) { %> Number | <%= i+1 %> |
<% } %>
The important things to notice are how the %> and directive applies to an entire JSP file and any of its static include files, which together are called a translation unit.
You can use the <%@ page %> directive more than once in a translation unit, but you can only use each attribute, except import, once. Because the import attribute is similar to the import statement in the Java programming language, you can use a <%@ page %> directive with import more than once in a JSP file or translation unit.
No matter where you position the <%@ page %> directive in a JSP file or included files, it applies to the entire translation unit. However, it is often good programming style to place it at the top of the JSP file.
Import Page Directive
import="{package.class | package.* }, ..." A comma-separated list of Java packages that the JSP file should import. The packages (and their classes) are available to scriptlets, expressions, and declarations within the JSP file. If you want to import more than one package, you can specify a comma-separated list after import or you can use import more than once in a JSP file. The following packages are implicitly imported, so you don't need to specify them with the import attribute: java.lang.* javax.servlet.* javax.servlet.jsp.* javax.servlet.http.* You must place the import attribute before the element that calls the imported class.
If you need to include a long list of packages or classes in more than one JSP file, you can create a separate JSP file with a <%@ page %> directive that contains the import list and include that file in the main JSP file. JSP Declarations Declarations in JSP
The JSP you write turns into a class definition. All the scriptlets you write are placed inside a single method of this class.
You can also add variable and method declarations to this class. You can then use these variables and methods from your scriptlets and expressions.
To add a declaration, you must use the <%! and %> sequences to enclose your declarations, as shown below.
<%@ page import="java.util.*" %> <%! Date theDate = new Date(); Date getDate() { System.out.println( "In getDate() method" ); return theDate; }
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 42 of 61
%> Hello! The time is now <%= getDate() %>
The example has been created a little contrived, to show variable and method declarations. Please NoteThe date will be the same, no matter how often you reload the page.
Declarations in JSP (Contd.)
You might have noted that the example given on previous page displays the same date each time it is executed
This is because these are declarations, and will only be evaluated once when the page is loaded! (Just as if you were creating a class and had variable initialization declared in it.)
Please refer to notes given below
It is in general not a good idea to use variables as shown here. The JSP usually will run as multiple threads of one single instance. Different threads would interfere with variable access, because it will be the same variable for all of them. If you do have to use variables in JSP, you should use synchronized access, but that hurts the performance. In general, any data you need should go either in the session objet or the request objectc (these are introduced a little later) if passing data between different JSP pages Assignment(s) JSP Basic Assignments
Create a Banner.jsp which will display today's date. Create an index.jsp and provide anchor on it to Customer.jsp, Product.jsp, Tax.jsp and Invoice.jsp. On each of these jsp(s) include Banner.jsp on the top. Use both the methods (include directive and jsp:include)
Write a scriplet in Customer.jsp to retrieve (use jdbc) all the data from Customer table (if Customer table is not created, create one). Use out.println("....."); to display the data retrieved
Modify the above program to give an anchor on Customer.jsp to display index.jsp
Chapter: 2 - Implicit Objects What are Implicit Objects The JSP-Implicit Objects
Implicit objects are created by the Web container and contain information related to a particular request, page, or application.
Many of the objects are defined by the Java Servlet technology underlying JSP technology and are discussed at length later while discussing Servlets
These implicit objects are: application
The context for the JSP page's servlet and any Web components contained in the same application
config
Initialization information for the JSP page's servlet.
exception
Accessible only from an error page
out
The output stream - Type: javax.servlet.jsp.JspWriter
page
The instance of the JSP page's servlet processing the current request. Not typically used by JSP page authors.
pageContect
The context for the JSP page. Provides a single API to manage the various scoped attributes. This API is used extensively when implementing tag handlers
request, response, session Discussed in Detail on next pages
Using Request Object What is a request
When the end-user submits a request to the server (usually through a browser), the Servlet Engine at the server side receives it and creates a request object and makes it available to your JSP.
This request object contains data that is submitted by the client. So you see, if you want to catch hold of data which was sent by the client to the server, it is this request object in which this data is available
You can get this data in your code using request.getParameter(<parameterName>).
Note one very important point: The request object is alive only till the time the response (we will discuss more on response later) is sent back to the client.
Once the client gets his response, the data that was available in the previous request he had sent is all gone. Now when he comes back to the server, he will be coming back with a new request. To put it in plain simple language : Each time you hit a link or a submit button on a web page, a new request is created server side for that client
Reading Data from request Object
Lets get to hands-on to get the concepts more clear.
Write a JSP called Customer.jsp as follows:
Customer Add a New Customer
Which looks like as follows:
Add a New Customer Id: Name: Address City: Add Customer
Deploy this JSP and ensure that you get the JSP displayed on the browser as per expectations. Well, there is not JSPness in this JSP. All that you have written here could be written in Html and still make it work. But the real work goes in next JSP.
Note the action attribute in the Form tag. This means that when the user clicks on the submit button, the request will be sent to AddCustomer.jsp on the server - needless to say that this request is sent by the browser.
On the next slide we will see what goes in AddCustomer.jsp
Reading Data from request Object (Contd.)
Write a new jsp called AddCustomer.jsp as follows:
AddCustomer Adding Customer
<% String id, name, address, cityId; // Note that all the data that comes in request comes in String id = request.getParameter("id"); name = request.getParameter("name"); address = request.getParameter("address"); cityId = request.getParameter("cityId"); out.println("The id is : " + id + " Name : " + name + " Address : " + address + " City : " + cityId); // Note the usage of out implicit object %>
Go Back
Now once again run the Customer.jsp, enter data and click on submit button.
Note that the data you have entered on Customer.jsp is made available to you on AddCustomer.jsp
Also note the anchor that helps you to go back to Customer.jsp
Using Response Object The response Object
The response object is also constructed by the server. All that is put in response object is rendered to the client.
You can write to the response object using the PrintWriter object of response object as follows:
PrintWriter myWriter = response.getWriter(); myWriter.println("Hi, This is my Writer");
The above technique is of no use in JSP because we already have implicit object called out which is nothing but an object of type PrintWriter pointing to response writer.
Still, try the above code snippet in your AddCustomer.jsp and print the the data entered by the user on Customer.jsp - What I mean is, use myWriter after initializing it to response.getWriter() instead of out.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 44 of 61
Using Exception Object (Handling Errors) The page Directive
Any number of exceptions can arise when a JSP page is executed.
To specify that the Web container should forward control to an error page if an exception occurs, include the following page directive at the beginning of your JSP page:
<%@ page errorPage="file_name" %>
If there is any exception thrown while the jsp (which includes above oage directive) is executing, the server will automatically forward the request to the page specified in errorPage="file_name"
In AddCustomer.jsp, deliberately throw an SQLException as follows (do not forget to import the java.sql.SQLException)
throw new SQLException("Duplicate Value");
Also include the page directive in AddCustomer.jsp as follows:
<%@ page errorPage="Error.jsp" %>
The Error Page
Create a new JSP called Error.jsp. The following directive is important in Error.jsp :
<%@ page isErrorPage="true|false" %>
The page directive indicates that it is serving as an error page
This directive makes the exception object (of type javax.servlet.jsp.JspException) available to the error page, so that you can retrieve, interpret, and possibly display information about the cause of the exception in the error page.
In Error.jsp write the following:
<% out.println("The Error Occurred is :
" + exception.getMessage() + ">"); %>
Execute Customer.jsp, put some data and hit submit. Since you deliberately throwing an exception from AddCustomer.jsp the server forwards the request to Error.jsp
Assignment(s) Implicit Objects Assignment(s)
Create an index.jsp with anchors to Customer, Tax, Invoice and Product. When the user clicks on any one of these options, display him/her the form with all the fields that are there in the tables Customer, Tax, Invoice & Product respectively.
Now implement the following: When the user clicks on Submit on the Customer.jsp (or any other jsp mentioned above) your browser must submit the request to AddCustomer.jsp or AddTax.jsp or AddInvoice.jsp or AddProduct.jsp - depending on which form the user has clicked on submit. Using jdbc, add data entered by the user in the respective tables. i.e. AddCustomer.jsp must use jdbc to add to Customer table, AddTax to tax table and so on.
Continue with the above application to provide search facility. Display Customer, Tax etc based on id provided by the user.
Continue with the above application to provide delete facility. Delete Customer, Tax etc based on id provided by the user
Chapter: 3 - Beans & Form Processing jsp:UseBean What is a Java Bean
JavaBeans brings component technology to the Java platform.
With the JavaBeans API you can create reuseable, platform-independent components.
Using JavaBeans-compliant application builder tools, you can combine these components into applets, applications, or composite components. JavaBean components are known as Beans.
Any java class that has private attribute(s) and public get and set methods in it can be called a java bean. For e.g a CustomerValueObject java bean can created as follows:
public class CustomerValueObject { public CustomerValueObject() { } private int id; private String name; public int getId() { return id; } public String getName() { return name; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } }
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir
Page 45 of 61
You will need to create such hundreds of java beans in real-life application, so that you can instantiate it one component, put data in it and pass it over to the other component so that it can use it.
Creating a Java Bean
Create a new package in your application called valueobjects and then create a class called CustomerValueObject.java as follows:
package valueobjects; public class CustomerValueObject { public CustomerValueObject() { } private int id; private String name; private String address; private int cityId; public int getId() { return id; } public String getName() { return name; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getCityId() { return cityId; } public void setCityId(int cityId) { this.cityId = cityId; } }
Now we can use jsp:UseBean method create the bean
Go to AddCustomer.jsp and add the following jsp code after the closing of java scriplet you have already written :
<jsp:useBean id="customerVO" class="valueobjects.CustomerValueObject" scope="request"/>
Do not forget to import CustomerVO class using
<%@ page import="valueobjects.CustomerValueObject" %>
Now we would like to forward our request to the other jsp called CustomerAddress.jsp. Write the following line just before