Sie sind auf Seite 1von 258

Amit Kr.

Balyan

INDEX

1. Introduction of Java
2. JSP/Servlet
3. Struts 1.2
4. EJB 1.2/3.0
5. Problem Statement

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
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (1 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (2 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (3 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (4 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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).

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (5 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (6 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (7 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● 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

● There are many objects identified for any domain

● Recognizing the commonalities among the objects and defining classes help us deal with the
potential complexity

A Relationship Between Classes & Objects

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (8 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (9 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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();
}
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (10 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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 ?

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (11 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

Chapter: 2 - Implementing OO

Working with Classes & Objects

Identifying Classes

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (12 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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;
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (13 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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[]) {


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (14 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (15 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

● Write SalesOrder Super Class as follows:

import java.util.Date;

public abstract class SalesOrder


{

private int orderId;


private Date orderDate;
private int customerId;
private int quantity;
private 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) {


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (16 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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");
}
}

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (17 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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();
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (18 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

// 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

Working with Polymorphism


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (19 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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 re-compile 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 sub-class.

Overloading

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (20 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (21 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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);
}
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (22 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● 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.

Assignment(s)

Classes & Objects

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (23 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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.
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (24 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

❍ 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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (25 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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.

The Java Platform

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (26 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (27 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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.

Setting the Path & Classpath

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (28 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (29 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (30 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (31 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (32 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (33 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (34 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

System.out.println("Max of byte : " + Byte.MAX_VALUE);


System.out.println("Max of short : " + Short.MAX_VALUE );
System.out.println("Max of int : " + Integer.MAX_VALUE );
System.out.println("Max of Long : " + Long.MAX_VALUE);
System.out.println("Max of float : " + Float.MAX_VALUE);
System.out.println("Max of 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (35 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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 :

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (36 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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);

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (37 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (38 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (39 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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;
}
}

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (40 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (41 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (42 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Arithmetic Operators in Java are as follows:


❍ + (add), - (subtract), * (multiply), / (divide), % (remainder)

❍ ++, -- (pre and post increments)

❍ +=

❍ -=,

❍ *=

❍ /=

Relational Operators:
❍ >, <, >=, <=, ==, !=

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (43 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (44 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (45 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

● You can overload constructors

● The overloaded constructors will all have different signatures

● Wrtie a class called Employee.java as follows:

public class Employee


{

public Employee() {
System.out.println("The Constructor of Employee");
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (46 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (47 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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");

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (48 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (49 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

which as same as the name of the package used in the class. Remember the names- here are case-
sensitive.

Importing Classes

● 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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (50 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

❍ 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");
}
}

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (51 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (52 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● 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:

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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (53 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (54 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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);

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (55 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (56 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (57 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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 fixed-length 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (58 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (59 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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";
departmentNames[1] = "H.R.";
departmentNames[2] = "I.T";
departmentNames[3] = "P.R.";
departmentNames[4] = "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
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (60 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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:
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (61 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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++) {

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (62 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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]);
}

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (63 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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.

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);
}
}
}

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (64 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (65 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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.


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (66 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (67 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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.
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (68 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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());

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (69 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

// }
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.

The try - catch block (Contd.)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (70 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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:

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (71 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (72 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (73 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

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 () {
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (74 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (75 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (76 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (77 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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 ( . . . ) {
. . .
} . . .

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 {
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (78 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

. . .
} 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
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (79 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (80 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

● 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: " +
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (81 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (82 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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();

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (83 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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


{

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (84 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

public void creditAccount() throws InvalidBalanceException {

if (true) { // balance is not sufficient then


throw new InvalidBalanceException("Insufficient Balance");
}

● 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).
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (85 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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.)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (86 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (87 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (88 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● The Byte Code verifier traverses the bytecodes, constructs the type state information, and verifies the
type of parameters to all the bytecode instructions

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 ?

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (89 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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:

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (90 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (91 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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.
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (92 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (93 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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:

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!");
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (94 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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();
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (95 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (96 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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) {}
}
System.out.println("DONE! " + getName());
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (97 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

}
}

● 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)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (98 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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 - IO API

Java I/O Streams

Java Stream I/O

● Often a program needs to bring in information from an external source or to send out information to
an external destination.

● The information can be anywhere: in a file, on disk, somewhere on the network, in memory, or in
another program.

● Also, the informa-tion can be of any type: objects, characters, images, or sounds.

● This chapter covers the Java™ platform classes that your programs can use to read and to write data.

Overview of I/O

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (99 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● To bring in information, a program opens a stream on an information source (a file, memory, a


socket) and reads the information sequentially, as shown here

● Similarly, a program can send information to an external destination by opening a stream to a


destination and writing the information out sequentially, like this:

● No matter where the data is coming from or going to and no matter what its type, the algorithms for
sequentially reading and writing data are basically the same:

Reading Writing

open a stream open a stream


while more information while more information
read information write information
close the stream close the stream

Stream Types

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (100 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● The java.io package contains a collection of stream classes that support these algorithms for reading
and writing. To use these classes, a program needs to import the java.io package.

● The stream classes are divided into two class hierarchies, based on the data type (either characters or
bytes) on which they operate.
❍ Character Streams

❍ Byte Streams

● Reader and Writer are the abstract superclasses for character streams in java.io. Reader provides the
implementation for readers--streams that read 16-bit characters--and Writer provides the
implementation for writers--streams that write 16-bit characters.
Most programs should use readers and writers to read and write textual information. The
reason is that they can handle any character in the Unicode character set, whereas the byte
streams are limited to ISO-Latin-1 8-bit bytes.

● To read and write 8-bit bytes, programs should use the byte streams, descendants of InputStream and
OutputStream. InputStream and OutputStream provide the implementation for input streams (streams
that read 8-bit bytes) and output streams (streams that write 8-bit bytes). These streams are typically
used to read and write binary data such as images and sounds.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (101 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Byte Streams

● Programs use byte streams to perform input and output of 8-bit bytes.

● All byte stream classes are descended from InputStream and OutputStream.

● There are many byte stream classes.

● To demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream and
FileOutputStream.

mport java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyBytes {


public static void main(String[] args) throws IOException {

FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;

while ((c = in.read()) != -1) {


out.write(c);
}

} finally {
if (in != null) {
in.close();
}
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (102 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

if (out != null) {
out.close();
}
}
}
}

Notice that read() returns an int value. If the input is a stream of bytes, why doesn't read()
return a byte value? Using a int as a return type allows read() to use -1 to indicate that it has
reached the end of the stream

● Other kinds of byte streams are used in much the same way; they differ mainly in the way they are
constructed

CopyBytes seems like a normal program, but it actually represents a kind of low-level I/O that you
should avoid.

Since xanadu.txt contains character data, the best approach is to use character streams, as discussed
on the next page.

There are also streams for more complicated data types.

Byte streams should only be used for the most primitive I/O.

Character Streams

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (103 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● All character stream classes are descended from Reader and Writer.

The Java platform stores character values using Unicode conventions Character stream I/O automatically
translates this internal format to and from the local character set

● As with byte streams, there are character stream classes that specialize in file I/O: FileReader and FileWriter. The
CopyCharacters example illustrates these classes

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyCharacters {


public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;

try {
inputStream = new FileReader("xanadu.txt");
outputStream = new FileWriter("characteroutput.txt");

int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (104 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Notice that both CopyBytes and CopyCharacters use an int variable to read to and write from. However, in
CopyCharacters, the int variable holds a character value in its 16 bits; in CopyBytes, the int variable holds a byte
value in its last 8 bits.

The Java platform stores character values using Unicode conventions Character stream I/O automatically translates
this internal format to and from the local character set. In Western locales, the local character set is usually an 8-bit
superset of ASCII.

For most applications, I/O with character streams is no more complicated than I/O with byte streams. Input and
output done with stream classes automatically translates to and from the local character set. A program that uses
character streams in place of byte streams automatically adapts to the local character set and is ready for
internationalization — all without extra effort by the programmer.

If internationalization isn't a priority, you can simply use the character stream classes without paying much
attention to character set issues. Later, if internationalization becomes a priority, your program can be adapted
without extensive recoding. See the Internationalization trail for more information.

Buffered Reader

● Most of the examples we've seen so far use unbuffered I/O. This means each read or write request is handled directly by the
underlying OS.

This can make a program much less efficient, since each such request often triggers disk access, network activity, or some
other operation that is relatively expensive

● To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from
a memory area known as a buffer; the native input API is called only when the buffer is empty.

Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full

● Write the following class to see how buffered reader and writer is used

import java.io.*;

public class CopyWithBuffers {

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (105 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

public static void main(String args[]) throws IOException {


BufferedReader reader = null;
BufferedWriter writer = null;
try {

reader = new BufferedReader(new FileReader("xanadu.txt"));


writer = new BufferedWriter(new FileWriter("bufferedOutput.
txt"));
int c;
while ((c = reader.read()) != -1) {

writer.write(c);

} finally {

if (reader != null) {
reader.close();
}
if (writer != null) {

writer.close();
}

Scanners

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (106 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Objects of type Scanner are useful for breaking down formatted input into tokens and translating individual tokens
according to their data type

● By default, a scanner uses white space to separate tokens. (White space characters include blanks, tabs, and line
terminators)

● To see how scanning works, let's look at ScanXan, a program that reads the individual words in xanadu.txt and prints
them out, one per line.

import java.io.*;
import java.util.Scanner;

public class ScanXan {


public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));

while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}

Notice that ScanXan invokes Scanner's close method when it is done with the scanner object. Even though a scanner is
not a stream, you need to close it to indicate that you're done with its underlying stream

● To use a different token separator, invoke useDelimiter(). Try using "," as the delimiter and re-run the ScanXan Class.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (107 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Scanning Individual Tokens

● Scanner also supports tokens for all of the Java language's primitive types (except for char), as well as BigInteger and
BigDecimal.

● Also, numeric values can use thousands separators. Thus, in a US locale, Scanner correctly reads the string "32,767" as
representing an integer value

● We have to mention the locale, because thousands separators and decimal symbols are locale specific

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.Locale;

public class ScanSum {


public static void main(String[] args) throws IOException {
Scanner s = null;
double sum = 0;
try {
s = new Scanner(new BufferedReader(new FileReader("usnumbers.
txt")));
s.useLocale(Locale.US);

while (s.hasNext()) {
if (s.hasNextDouble()) {
sum += s.nextDouble();
} else {
s.next();
}
}
} finally {
s.close();
}

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (108 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

System.out.println(sum);
}
}

Deep Cloning

● Override clone method as follows for deep cloning

ByteArrayOutputStream baos = new ByteArrayOutputStream();


ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object deepCopy = ois.readObject();

Chapter: 6 - Colllection API

Collection Framework

The Collection Framework

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (109 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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 object-oriented 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:


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (110 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (111 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (112 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (113 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (114 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

Array Operations

● 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

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (115 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (116 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (117 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (118 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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.

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);


}
}

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (119 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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]

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (120 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (121 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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();
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.
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (122 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (123 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (124 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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(); // Optional


void set(Object o); // Optional
void add(Object o); // 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.)
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (125 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● 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

● 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<toIndex; 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:
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (126 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (127 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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();
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (128 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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);
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (129 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

}
}

● 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:

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (130 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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());

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (131 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (132 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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: 7 - 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (133 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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)

● 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

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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (134 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (135 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (136 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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.

● 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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (137 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (138 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (139 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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.


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (140 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● 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.

Using Transactions

What is one unit of Work ?

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (141 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

● which will insert 1 customer row in Customer table

● 1 or more than 1 Customer addresses for the Customer inserted

● Here Customer is a composite of CustomerAddress

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (142 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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 {
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (143 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (144 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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)

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
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (145 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (146 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (147 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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:

<HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
</HTML>

● Notice that each time you reload the page in the browser, it comes up with the current time.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (148 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● The character sequences <%= and %> 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

● 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:

<jsp:include page="includedPage" />

Transferring Control to Another Web Component (jsp:forward)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (149 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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"/>
</jsp:include>

Life Cycle of JSP Page

The Life Cycle of JSP

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (150 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (151 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (152 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● JSP allows you to write blocks of Java code inside the JSP. You do this by placing your Java code
between <% and %> characters (just like expressions, but without the = sign at the start of 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.

● <HTML>
<BODY>
<%
// 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 %>
</BODY>
</HTML>

● 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.

● <HTML>
<BODY>
<%
// 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 ));
%>
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (153 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

</BODY>
</HTML>

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:

<TABLE BORDER=2>
<%
for ( int i = 0; i < n; i++ ) {
%>
<TR>
<TD>Number</TD>
<TD><%= i+1 %></TD>
</TR>
<%
}
%>
</TABLE>

● The important things to notice are how the %> and <% characters appear in the middle of the "for"
loop, to let you drop back into HTML and then to come back to the scriptlet.
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (154 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

Exercise:

Make the above examples work. Write a JSP to output all the values returned by System.getProperties with "
" embedded after each property name and value. Do not output the "<BR>" using the "out" variable.

JSP Directives

Include Directive

● There are two mechanisms for including another Web resource in a JSP page: the include directive
and the jsp:include element.

● The include directive is processed when the JSP page is translated into a servlet class.

● The effect of the directive is to insert the text contained in another file--either static content or
another JSP page--in the including JSP page

● You would probably use the include directive to include banner content, copyright information, or
any chunk of content that you might want to reuse in another page.

● The syntax for the include directive is as follows:

<%@ include file="filename" %>

Page Directives

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (155 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● The <%@ page %> 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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (156 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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.*" %>


<HTML>
<BODY>
<%!
Date theDate = new Date();
Date getDate()
{
System.out.println( "In getDate() method" );
return theDate;
}
%>
Hello! The time is now <%= getDate() %>
</BODY>
</HTML>

● 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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (157 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (158 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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:


The context for the JSP page's servlet and any Web components
application
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
The instance of the JSP page's servlet processing the current request.
page
Not typically used by JSP page authors.
The context for the JSP page. Provides a single API to manage the
pageContect 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
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (159 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● 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:

<html>
<head>
<title>
Customer
</title>
</head>
<body bgcolor="#ffffff">
<h1>
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (160 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

Add a New Customer</h1>


<form method="post" action="AddCustomer.jsp">
<table>
<tr>
<td>
Id:
</td>
<td>
<input type="text" name="id" value=""/>
</td>
</tr>
<tr>
<td>
Name:
</td>
<td>
<input type="text" name="name" value=""/>
</td>
</tr>
<tr>
<td>
Address
</td>
<td>
<input type="text" name="address" value=""/>
</td>
</tr>
<tr>
<td>
City:
</td>
<td>
<input type="text" name="cityId" value=""/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Add Customer"/>
</td>

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (161 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

</tr>
</table>
</form>
</body>
</html>

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.)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (162 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Write a new jsp called AddCustomer.jsp as follows:

<html>
<head>
<title>
AddCustomer
</title>
</head>
<body bgcolor="#ffffff">
<h1>
Adding Customer
</h1>
<%

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

%>
<a href="Customer.jsp">Go Back</a>
</body>
</html>

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (163 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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.

Using Exception Object (Handling Errors)

The page Directive

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (164 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (165 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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 : <b>" + 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)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (166 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (167 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● 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;
}
}

● 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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (168 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

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) {
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (169 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

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 </body>

<jsp:forward page="CustomerAddress.jsp"/>

● Note how useBean method is used to initialize a java bean.

The jsp:useBean tag will look for the the object called "customerVO" - specified as id in request
object (why in request ? because the scope="request" in jsp:useBean tag). If found, it will use it or
else it will create one and put it on request object.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (170 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

jsp:setProperty

Using the jsp:setProperty tag

● Add the following code snippet in the AddCustomer.jsp

<jsp:setProperty name="customerVO" property="id" value="<%=id%>" />


<jsp:setProperty name="customerVO" property="name" value="<%=name%>" />
<jsp:setProperty name="customerVO" property="address" value="<%=address%>" />
<jsp:setProperty name="customerVO" property="cityId" value="<%=cityId%>" />

● The above statements will add the values to the object created called customerVO of class valueobjects.
CustomerValueObject. Note that this object is created and put in request using jsp:useBean tag explained in earlier tag.

● Using the jsp:setProperty to write value to name using <jsp:setProperty name="customerVO" property="name"
value="yabadabadoo" /> is as good as writing <% customerVO.setName("yabadabadoo"); />

jsp:getProperty

Using jsp:getProperty Tag

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (171 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Now Write a CustomerAddress.jsp as follows:

Enter Customer Address

Id: <jsp:getProperty name="customerVO" property="id" />

Name: <jsp:getProperty name="customerVO" property="name" />

Address <jsp:getProperty name="customerVO" property="address" />

City: <jsp:getProperty name="customerVO" property="cityId" />

Address Line 1

Address Line 2

Address Line 3

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (172 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Submit

● Note the usage of jsp:useBean tag here - right on the top. The rule is same: JSP-Servlet engine will check
whether there is bean called customerVO in request, if yes it will use it or else it will create it. Since the
control has been forwarded from AddCustomer.jsp (which creates customerVO and puts in request) to this
page, servlet engine will not recreate it - instead use it.

● See the usage of jsp:getProperty tag to get the value of attributes of the bean and set it to text boxes.

Techniques for Form Editing

Editing a Form

● A form used to accept values from the user and put it in the database can be also be used to display
the values retrieved from the database so that it can be ammended by the user

● Write a index.jsp which will have anchor to EditCustomer.jsp. The text of the anchor must display :
"Edit Customer".

● The EditCustomer.jsp must accept customer Id from the user. When the user clicks on submit,
submit the request to RetrieveCustomer.jsp. RetrieveCustomer.jsp must contain scriptlet which will
load database driver, establish connnection, retrieve data and create a javabean called customerVO of
class CustomerValueObject and put the same in request object. The customer row retrieved must be
exactly the one the id of which is entered by the user on EditCustomer.jsp

● RetrieveCustomer.jsp will finally forward the request to Customer.jsp which will display the data in
text boxes using jsp:getProperty. Needless to say, you will have to use jsp:useBean also on the top of
Customer.jsp.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (173 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Assignment(s)

Form Bean Exercise

● Extend the application you have written in "Assignments for Implicit Objects " to use Form Beans to
edit Customer, Tax etc.

Retrieve the customer the way you have done earlier and forward to Customer.jsp. Use jsp:useBean,
jsp:getProperty to display the values retrieved in the text boxes. Write EditCustomer.jsp EditTax.jsp
etc to update the edited values back to database

Chapter: 4 - Protecting Your Website

Creating the Login Page

Chapter: 5 - Servlets

Introducing Servlets

What is a Servlet

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (174 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● A servlet is a Java programming language class used to extend the capabilities of servers that host
applications accessed via a request-response programming model.

● Although servlets can respond to any type of request, they are commonly used to extend the
applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-
specific servlet classes.

● The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets.
All servlets must implement the Servlet interface, which defines life-cycle methods.

● When implementing a generic service, you can use or extend the GenericServlet class provided with
the Java Servlet API.

● The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific
services.

Servlet Life Cycle

● The life cycle of a servlet is controlled by the container in which the servlet has been deployed.

● When a request is mapped to a servlet, the container performs the following steps.
❍ If an instance of the servlet does not exist, the Web container

● Loads the servlet class.

● Creates an instance of the servlet class.

● Initializes the servlet instance by calling the init method.

❍ Invokes the service method, passing a request and response object.

● If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy
method.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (175 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Service Methods

Writing Service Methods

● The service provided by a servlet is implemented in the service method of a GenericServlet, the
doMethod methods (where Method can take the value Get, Delete, Options, Post, Put, Trace) of an
HttpServlet, or any other protocol-specific methods defined by a class that implements the Servlet
interface.

● In the rest of this chapter, the term service method will be used for any method in a servlet class that
provides a service to a client.

● The general pattern for a service method is to extract information from the request, access external
resources, and then populate the response based on that information.

● For HTTP servlets, the correct procedure for populating the response is to first fill in the response
headers, then retrieve an output stream from the response, and finally write any body content to the
output stream.

● Response headers must always be set before a PrintWriter or ServletOutputStream is retrieved


because the HTTP protocol expects to receive all headers before body content.

The doGet and doPost Methods

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (176 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● The doGet method is one of the service methods that is executed by the container when the requested
is submitted to the server and the method of submission os get

● The doPost method is no different then doGet method - the only difference is that it is executed by
the container when the method of request submitted by the client is post

● All that we did in AddCustomer.jsp and RetrieveCustomer.jsp should have been actually done in
Servlet.

● The JSP(s) are for managing presentation logic and servlets are the ones that must be used for
processing requests and managing control logic of web-navigation.

Creating a Servlet

● Create a servlet called CustomerServlet which will do all that you have written in AddCustomer.jsp

● Please note that when you create a servlet, the servlet is requested from client-side with a URL patterns and not the name
of the servlet.

● Please see the web.xml file

● Now instead of action="AddCustomer.jsp" in Customer.jsp - change it to "customerservlet" - the url pattern for
CustomerServlet

● Write the following code in doPost method as follows:

String name, address;


int id, cityId;
// Note that all the data that comes in request comes in String
id = (new Integer(request.getParameter("id"))).intValue();
name = request.getParameter("name");
address = request.getParameter("address");

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (177 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

cityId = (new Integer(request.getParameter("cityId"))).intValue();


out.println("The id is : " + id + " Name : " + name +
" Address : " + address + " City : " + cityId);
// Note the usage of out implicit object

CustomerValueObject customerVO = new CustomerValueObject();


customerVO.setId((new Integer(id)).intValue());
customerVO.setName(name);
customerVO.setAddress(address);
customerVO.setCityId((new Integer(cityId)).intValue());
request.setAttribute("customerVO", customerVO);
RequestDispatcher dispatcher = request.getRequestDispatcher("CustomerAddress.
jsp");
dispatcher.forward(request, response);

Note the RequestDispatcher object used here to forward the request to CustomerAddress.jsp. Also note how
customerVO object is created and put in request. This is not a JSP hence we have to do it without a tag

Maintaining Client State

Accessing a Session

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (178 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Many applications require a series of requests from a client to be associated with one another. For
example, the user logs on to your system and you would like to maintain his user info such as first
name and lastname across multiple request infact throughout out his interaction with the application.

● Web-based applications are responsible for maintaining such state, called a session, because the
HTTP protocol is stateless.

● To support applications that need to maintain state, Java Servlet technology provides an API for
managing sessions and allows several mechanisms for implementing sessions.

● Sessions are represented by an HttpSession object.

● You access a session by calling the getSession method of a request object.

This method returns the current session associated with this request, or, if the request does not have a
session, it creates one

Associating Attributes with a Session

● Create a Login.jsp with a form on it accepting username and password from the user

● On submitting this form - invoke (using action="loginservlet") LoginServlet

● You must create all servlets in some package - here you create LoginServlet in servlets package

● In valueobjects package create a class called UserValueObject.java as a java bean with attributes such as: userName,
firstName, lastName. (You know what is a java bean - it must have getter & setter methods for each one of these
attributes)

● Write the doPost method in LoginServlet as follows:

String userName = request.getParameter("userName");


UserValueObject userVO = new UserValueObject();
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (179 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

userVO.setUserName(userName);
// You can get firstName and lastName
// can be read from database.
userVO.setFirstName("Saurav");
userVO.setLastName("Ganguly");

HttpSession session = request.getSession();


// the following will help you to keep
// userVO server-side till the users
// session is alive.
session.setAttribute("userVO", userVO);
// dispatcher must be actually taken for index.jsp
RequestDispatcher dispatcher = request.getRequestDispatcher("Customer.jsp");
dispatcher.forward(request, response);

Using the Session Object

● Create a new JSP called Banner.jsp

● Write a scriplet in Banner.jsp as follows:

UserValueObject userVO = (UserValueObject) session.getAttribute("userVO");


String firstName = userVO.getFirstName();
String lastName = userVo.getLastName();
out.println("Welcome : " + firstName + " | " + lastName);

I said scriptlet friends. You know what is a scriplet.

● Now include this jsp in each jsp using

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (180 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

<jsp:include page="Banner.jsp" />

● Execute Login.jsp and now switch to any jsp (without closing the browser) typing the jsp name on the address bar.
See that you will get Welcome info on all the jsps

Assignment(s)

Servlet Assignment(s)

● Re-Design the entire application written earlier, to use servlets instead of all the JSP(s) which were
doing the request processing and not managing the presentation logic for e.g. AddCustomer.jsp,
RetrieveCustomer.jsp, DeleteCustomer.jsp etc. Now no jdbc code must be there in any JSP - All the
jdbc code must be in Servlets.

Using Session Objects

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (181 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Consider that each Customer has one or more Addresses. Create a Customer Data Entry Application
which will accept Customer Details like name, address etc and also one ore more Addresses which
will have line1, line2 and line3 of address. Save the entire Customer along with Address only after
user confirms. Till the time user finishes entering all the Addresses you must keep Customer Details
like name and address in Session Object. Use value objects, form beans, request and session objects.
This must be a complete master-detail application with add, modidy, delete and view options.

Struts

Chapter: 1 - Introduction to MVC

What is MVC ?

The MVC Architectural Pattern

● The early JSP specifications advocated two philosophical approaches for building applications using
JSP technology: MVC Model-1 & MVC Model-2

● Model 1 and 2 differ essentially in the location at which the bulk of the request processing was
performed

● In the Model 1 architecture, the JSP page alone is responsible for processing the incoming request
and replying back to the client.

● There is still separation of presentation from content, because all data access is performed using
beans
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (182 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

MVC Model 2

● The Model 2 architecture, is a hybrid approach for serving dynamic content, since it combines the
use of both servlets and JSP.

● It takes advantage of the predominant strengths of both technologies, using


❍ JSP to generate the presentation layer and

❍ servlets to perform process-intensive tasks

● The servlet acts as the controller and is in charge of :


❍ the request processing

❍ the creation of any beans or objects used by the JSP,

❍ deciding, depending on the user's actions, which JSP page to forward the request to.

● Note particularly that there is no processing logic within the JSP page itself

● JSP is simply responsible for retrieving any objects or beans that may have been previously created
by the servlet, and extracting the dynamic content from that servlet for insertion within static
templates

Struts Implements MVC

Struts Logical Structure


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (183 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● Struts implements MVC. Yes - MVC 2.

Chapter: 2 - Introduction to Struts

The Architecture of Struts

Struts Architecture

● Struts is comprised of a controller servlet, beans and other Java classes, configuration files, and tag
libraries.

● A controller for your application (the Struts servlet acts as a common controller for the whole
application)

● A collection of Java beans and other helper classes that you use in the "Model" part of your
application

● A collection of tag libraries used in your jsp-pages

● To glue these things together Struts uses a set of configuration files. Together this gives you the
skeleton that you can use to "strut" your application

The Flow
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (184 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● Consider, that the request sent from the client (browser) is toCreateCustomer.do - The *.do url
pattern is mapped to ActionServlet in web.xml file and hence ActionServlet service method is
executed

● The ActionServlet reads struts-config.xml file and searches for <action> element with path="/
toCreateCustomer" and detects the Action class name configured with this path

● The ActionServlet now instantiates the Action class and executes the execute method of it

● Please note: Before executing the execute method, the ActionServlet instantiates the formbean object
(if configured) and populates it with the data entered by the end-user, executes the validate method
and then passes it as the parameter to the execute() method.

Benefits of Using Struts

Benefits of Using Struts

● Struts has been designed to give you modularity and loose couplings in your application.

● If you're building a simple, small application you might find it complicated to have to create and
handle so many files.

● You might even be tempted to put all your code in a single jsp-file

● My advice to you is: don't do it! I'm sure you can build a single-page application faster using only
one jsp-page, but if we're talking about more complex applications, the extra effort put in by using a
modular framework will soon be rewarded

Only 1-Single Servlet in Your Application


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (185 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● There is one single servlet in the entire application i.e. ActionServlet. This servlet is provided by
Struts-Framework API

● All the requests coming to the application server (which requires dynamic contents / need to access
the model) is received by this ActionServlet.

● The ActionServlet reads Struts-Config.xml file and identifies the Action class to be instantiated.

● The ActionServlet instantiates the Action Class and executes the execute() method

● It is this execute() method, in the Action Class where you write your use case logic.

Note that the ActionClass you write is extended from Action class provided by Struts-Framework API. The execute
() method has 4 parameters (ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response).

The ActionForm

● If the form is to be processed the programmer-defined class of type ActionForm can be configured in
Struts-Config.xml file

● It is the responsibility of Struts-Framework to instantiate this class, read the contents entered by the
end-user and copy the same to this FormBean class.

● The best thing is that (as explained in notes of previous slide) one of the parameters passed to the
execute method of Action Class is this instantiated and populated FormBean object

● You can execute accessor (getter) methods on this form object to get the data entered by the end-user
in the execute method

The validate method of ActionForm class


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (186 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● The Struts-Framework after instatiating and populating the ActionForm object, executes the validate
method.

● You can write validations in this validate method and return object of type ActionErrors containing
the list of Errors (if there are any as per the business rule)

● The Struts-Framework will automatically forward to the input page (forcing user to re-enter the data)

● With the help of simple error tags, (provided by Struts) you can display the error messages on the
input page

Setting up Struts

The Jar Files

● There are n number of jar files provided by Struts-Framework which togethger provides all the
Struts-Functionality. The architecturally-significant among these is Struts.jar

● All the architecturally-significant components like: ActionServlet, Action, ActionForm, ActionError,


ActionErrors etc. are in this jar file.

● This and all the other jar files must be copied to your WEB-INF/lib folder

● Please download the following zip file, Unzip it and copy all the jar files in the location mentioned
above:
Download Jar Files

Any jar file put in the lib folder need not be explicity specified in the classpath of your web application. They are
implicity included in the classpath
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (187 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

The TLD Files

● As mentioned earlier, Struts offers collection of rich tags which tremendously eases the development
of presentation logic.

● All the tag classes are in struts.jar file and all the descriptors of tags are in the .tld files copied on
WEB-INF folder

● These files must be copied in WEB-INF folder

● Please download the following zip file and copy it to the location mentioned above:
Download TLDs

Struts-Config.xml

● This is the Struts Configuration file.

● It contains the configuration of form beans, action classes, forwards etc.

● This is the architecturally siginificant component of Struts-Framework. If not present, the framework
will cease to work.

● This file must be copied to WEB-INF/ folder

● Please download the following sample Struts-Config.xml file and copy it to the location mentioned
above:
Download Struts-Config

Configuring your web.xml to use Struts


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (188 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● Create a Servlet Component in web-xml file with the name action. This servlet component must be mapped to
the servlet class : ActionServlet. The fully qualified path of the this servlet is: org.apache.struts.action.
ActionServlet

● Also set the initialization parameter called "config" for this servlet. Set the value of this parameter to: /WEB-
INF/struts-config.xml. The xml code is given below

● <servlet>
<servlet-name>action</servlet-name>
<display-name>ActionServlet</display-name>
<description>Struts Controller</description>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
<description>No Description</description>
</init-param>
</servlet>

● Now add a servlet mapping in your web.xml file for the ActionServlet as follows:

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

● Now you are ready to strut your application

You will have to redeploy your application to bring all the changes in effect

Chapter: 3 - Getting Started


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (189 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

The Customer Mananagement App

The Application

● Let us develop a small sample application which will have the option of creating a new Customer.
Each customer that is recorded belong to a particular city and and we need to provide the list of cities
to the user. Also, we need to perform basic validation like customer name cannot be left blank. If this
validation fails, the system must re-present the customer form displaying the error message(s) - or
else save the Customer

● Please create the following jsp(s)


❍ index.jsp - With the anchor toCreateCustomer.do (The application will actually present the

customer.jsp form when user clicks on the anchor)


❍ customer.jsp - with the html form to accept the customer id, name, city and address

Simple Action Class

The Action Class

● Create a new package (folder) called presentationtier and then class within it called
ToCreateCustomerAction.java Extend this class from Action

● To extend from Action class, import org.apache.struts.action.Action class

● Now override execute method, the signature of which is: public ActionForward execute
(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException

● Write following lines in the execute method:


❍ SOP : Retrieving Cities

❍ return mapping.findForward("success");

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (190 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Compile the class

It is assumed that you already have created a web application and tested the same.

Setting the struts-config.xml

● When the request comes from the browser as "toCreateCustomer.do", the ActionServlet will look for action
element in the struts-config.xml file with path attribute as "toCreateCustomer",

● Hence we need to make entry in struts-config.xml file as follows:

<action type="presentationtier.ToCreateCustomerAction" validate="false"


scope="request" path="/toCreateCustomer">
<forward name="success" path="/customer.jsp"/>
</action>

● Now deploy the application and run index.jsp

● Click on the anchor to Add a new customer.

● Note that the execute method of the action class gets executed printing the SOP : Retrieving cities. Also note that
owing to the forward tag of the action, the ActionServlet forwards the request to customer.jsp.

The CityVO class

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (191 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Create a CityVO class in model.vo package with id and name as attributes and accessor and mutator methods.

● Create 3 objects of this class in execute method of ToCreateCustomerAction.java and put it in the collection. Put the
collection object in the request using request.setAttribute

● Retrieve this collection object from the request object in jsp and construct a dropdown list box to display the list of
customers. Please note: the display column must be name and data column must be id.

● Use the Following code in customer.jsp to display all the cities in dropdown:

<Select name="city">
<%
Collection cities = (Collection) request.getAttribute("cities");
for (Iterator i = cities.iterator(); i.hasNext();) {
CityVO cityVO = (CityVO) i.next(); // Please import CityVO class in this jsp
%>
<option value=<%=cityVO.getId()%>><%=cityVO.getName()%></option>
<% } %>
</Select>

Using ActionForm Beans

The ActionForm class

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (192 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Now that we have presented the customer.jsp to the end-user, the end-user enters customer details and hits the submit
button

● In customer.jsp, specify the action attribute for html form as: "toSaveCustomer.do".

● Create a new class in presentationtier package called "CustomerForm.java" and extend it from ActionForm. The
ActionForm is a class provided by Struts-Framework and is available in org.apache.struts.action package - Compile the
class

● Now go to struts-config.xml file and make an entry for "toSaveCustomer" action. Create a new action element as follows:

<action name="CustomerForm" type="presentationtier.SaveCustomerAction" input="/


customer.jsp" scope="request"
validate="false" path="/toSaveCustomer">
<forward name="success" path="/index.jsp"/>
</action>

● Please note the value of name attribute in the above xml code. This name is actually the name of FormBean - again
declared in struts-config.xml file. Once a form bean is declared, it can be used in n-number of actions (More on the next
slide...)

Declaring FormBean in struts-config.xml

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (193 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● As explained in previous slide, we need to declare the FormBean in struts-config.xml as follows:

<form-bean name="CustomerForm" type="presentationtier.CustomerForm"/>

● Please note that this entry must be made within <form-beans> and </form-beans> tags

● All the form-beans must be configured within <form-beans> and </form-beans> tags

● The name in the tag specifies the name of the formbean and the type specifies the class of the formbean

● Note that it is this name of the formbean which is used as value of name attribute in the action mapping
for "toSaveCustomer"

Accessing the FormBean in execute method of the Action Class

● Create a new Class called "SaveCustomerAction.java" in presentationtier pacakage and extend the same from Action
class of struts. (By now you know, in which package this class is).

● Note that, it is this class which has been specified in type attribute in the toSaveCustomer mapping

● Override the execute method. In the execute method write the following:

CustomerForm customerForm = (CustomerForm) form;


System.out.println("The id entered by the user is : " + customerForm.id);
System.out.println("The name entered by the user is : " + customerForm.name);
// Print all the other values also entered by the user

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (194 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Run the application and see the SOP(s) on the console

● The framework instantiates the FormBean, populates the bean with the contents entered by end-user and passes the
formbean instance as parameter to the executed method.

● Instead of you writing n-number of request.getParameter statements to get the values, entered by the user, the
framework gives you a bean with all the values Is'nt this great

Validating User Input in FormBean

Using the validate method of FormBean

● Open the CustomerForm.java and override validate method as follows:

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {


ActionErrors errors = new ActionErrors();
if (this.getName() == null || this.getName().length() == 0 ) {
ActionError error = new ActionError("error.customer.name.required");
errors.add(ActionErrors.GLOBAL_ERROR, error);

}
if (this.getId() == null || this.getId().length() == 0 ) {
ActionError error = new ActionError("error.global.message", "Idiot! How
can code be blank");
errors.add(ActionErrors.GLOBAL_ERROR, error);

}
return errors;
}

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (195 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Now open struts-config.xml file and go to action mapping for toSaveCustomer. Ensure that the input="/customer.jsp" and
validate="true"

● This tells the framework to execute the validate method of the form after populating it with the data entered by end-user.

● Also, if validate method returns an object of class ActionErrors (it is actually a collection) with size > 0, then the framework re-
presents customer.jsp (as mentioned in input attribute) for the end-user to rectify the errors

● Run the Application and See the results. Do not worry about the ActionError and displaying the errors on customer.jsp - we
will address this shortly

The ActionError

● As explained on the previous slide, we create an object of ActionError if there is any violation of
business rule, and add it to the object of type ActionErrors.

● The ActionError object constructor takes min of 1 and max of 5 parameters.

● In the code that we hae written, there are two examples 1 - with one parameter and 2 with 2
parameters.

● If you create ActionError object with 1 parameter, you provide the property name the value of which
is set in "ApplicationResources.properties" file. Create a file with this name and put it under WEB-
INF/classes folder

● Make the following enteries in the ApplicationResources.properties file

error.customer.name.required = <li>Name Cannot Be Blank</li>


error.customer.id.required = <li>Code Cannot Be Left Blank</li>
error.global.message=<li>{0}</l>>

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (196 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

The Action Error (Contd.)

● Now also check out the creation of ActionError with 2 arguments. The first argument specifies the
property name in ApplicationResources.properties file and the second parameter, the value that will
be substituted with the {0} parameter in the property.

● Now how does the framework understand that the error messages are in ApplicationResource.
properties ?

● It understands after adding the following after action-mappings element in struts-config.xml file:

<message-resources parameter="ApplicationResources" null="false"/>

Displaying the Error Messages

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (197 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Now that we have written all our code to validate and manage errors. How do we display the errors
that are set in ApplicationResources.properties

● Open customer.jsp - Before you start the html form, write the following:

<html:errors/>

In order to use this tag you will have to give a taglib directive on your jsp page as follows:

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>

● Run the application and deliberately leave name empty, hit submit and see the results. The
framework will forward the request to customer.jsp and will display the error messages

● In order to get the values in the other text boxes displayed, which were entered by the user before
submit, use the <jsp:useBean id="CustomerForm" class="presentationtier.CustomerForm"
scope="request"/> and then jsp:getProperty to get the original value. Use this value to set the value
of the text box

Assignment(s)

Struts Assignment

● Write the entire application which you have written earlier using Struts framework. Re-developing
JSP(s) write from scratch is not required. Where ever you used Servlets, now use Action Classes.
Use ActionForms for each input type jsp. Use validate method and ActionErrors and ActionError to
validate daya input and display the error messages.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (198 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

EJB 2.0

Chapter: 1 - Enterprise Beans

What is an Enterprise Bean

What is an Enterprise Bean ?

● Written in the Java programming language, an enterprise bean is a server-side component that
encapsulates the business logic of an application.

● The business logic is the code that fulfills the purpose of the application

● In an inventory control application, for example, the enterprise beans might implement the business
logic in methods called checkInventoryLevel and orderProduct

● By invoking these methods, remote clients can access the inventory services provided by the
application

Benefits of Enterprise Bean

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (199 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Enterprise beans simplify the development of large, distributed applications

● Because the EJB container provides system-level services to enterprise beans, the bean developer
can concentrate on solving business problems

● The EJB container--not the bean developer--is responsible for system-level services such as
transaction management and security authorization

● Because the beans--and not the clients--contain the application's business logic, the client developer
can focus on the presentation of the client

● The client developer does not have to code the routines that implement business rules or access
databases

Benefits of Enterprise Bean (Contd.)

● The clients are thinner, a benefit that is particularly important for clients that run on small devices.

● These applications can run on any compliant J2EE server

When to Use Enterprise Bean ?

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (200 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Consider using Enterprise beans if your application has any one of the following requuirements:

● The application must be scalable:


❍ To accommodate a growing number of users, you may need to distribute an application's

components across multiple machines.


❍ Not only can the enterprise beans of an application run on different machines, but their

location will remain transparent to the clients.

● Transactions are required to ensure data integrity

● The application will have a variety of clients

● The application will have a variety of clients.


❍ With just a few lines of code, remote clients can easily locate enterprise beans.

❍ These clients can be thin, various, and numerous

Types of Enterprise Beans

● Session: Performs a task for the client

● Entity: Represents a business entity object that exists in persistent storage

● Message-Driven: Acts as listener for Java Message Service API, processing messages
asynchronously

What is a Session Bean (SLSB & SFSB)

What is a Session Bean ?


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (201 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● A Session Bean represents a single client inside the J2EE server & is similar to an interactive session

● To access an application that is deployed on the server, the client invokes the session bean's methods.

● The session bean performs work for its client, shielding the client from complexity by executing
business tasks inside the server

● A session bean is not shared--it may have just one client, in the same way that an interactive session
may have just one user & is not persistent

● When the client terminates, its session bean appears to terminate and is no longer associated with the
client.

State Management Modes

● Stateful Session Beans

● Stateless Session Beans

Stateful Session Beans

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (202 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● The state of an object consists of the values of its instance variables.

● In a stateful session bean, the instance variables represent the state of a unique client-bean session

● Because the client interacts ("talks") with its bean, this state is called the conversational state

● The state is retained for the duration of the client-bean session

● If the client removes the bean or terminates, the session ends and the state disappears

Stateless Session Beans

● A stateless session bean does not maintain a conversational state for a particular client

● When a client invokes the method of a stateless bean, the bean's instance variables may contain a
state, but only for the duration of the invocation

● When the method is finished, the state is no longer retained

● Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB
container to assign an instance to any client

● The benefits of using Stateless Session Beans are :


❍ Fewer Stateless session beans can support multiple clients

❍ They can offer better scalability for applications that require large numbers of clients

❍ An application requires fewer stateless session beans than stateful session beans to support

the same number of clients


❍ Stateless beans may offer better performance than stateful beans

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (203 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Use Stateful Session Beans When...

● The bean’s state represent the interaction between the bean and specific client

● The bean needs to hold information about the client across method invocations

● The bean mediates between the client and the other components of the application providing a
simplified view to the client

● Behind the scenes the bean manages the workflow for several enterprise beans

Use Stateless Session Beans When...

● The bean’s state has no data for a specific client

● In a single method invocation, the bean performs a generic task for all clients. For example, you
might use a stateless session bean to send an email that confirms the online order

● The bean fetches from a database a set of read-only data that is often used by clients

What is an Entity Bean

What is an Entity Bean ?

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (204 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● An entity bean represents a business object in a persistent storage mechanism

● Some examples of business objects are customers, orders, and products

● In the J2EE SDK, the persistent storage mechanism is a relational database

● Typically, each entity bean has an underlying table in a relational database, and each instance of the
bean corresponds to a row in that table

What makes Entity Beans different from Session Beans ?

● Entity beans differ from session beans in several ways as given below:

● Entity beans are persistent

● Have primary keys

● May participate in relationships with other entity beans

● Each one of these point is discussed on following slides

Persistence in Entity Beans

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (205 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Because the state of an entity bean is saved in a storage mechanism, it is persistent.

● Persistence means that the entity bean's state exists beyond the lifetime of the application or the J2EE
server process

● There are two types of persistence for entity beans:


❍ bean-managed and

❍ container-managed

● With bean-managed persistence, the entity bean code that you write contains the calls that access
the database

● With container-managed persistence, the EJB container automatically generates the necessary
database access calls

Primary Key in Entity Beans

● Each entity bean has a unique object identifier

● A customer entity bean, for example, might be identified by a customer number

● The unique identifier, or primary key, enables the client to locate a particular entity bean

Relationships in Entity Beans

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (206 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Like a table in a relational database, an entity bean may be related to other entity beans

● For example, in a college enrollment application, StudentEJB and CourseEJB would be related
because students enroll in courses

● With bean-managed persistence, the code that you write implements the relationships

● With container-managed persistence, the EJB container takes care of the relationships for you

● For this reason, relationships in entity beans with container-managed persistence are often referred to
as container-managed relationships.

Container Managed Relationships is the excellent way of automating the relationships among business objects in
the your business object model.

Container Managed Persistence

● The term container-managed persistence means that the EJB container handles all database access
required by the entity bean

● The bean's code contains no database access (SQL) calls

● The bean's code is not tied to a specific persistent storage mechanism (database).

● Because of this flexibility, even if you redeploy the same entity bean on different J2EE servers that
use different databases, you won't need to modify or recompile the bean's code

● Your entity beans are more portable

When to use Entity Beans

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (207 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● You should probably use an entity bean when: The bean represents a business entity, not a
procedure. For example, CreditCardEJB would be an entity bean, but CreditCardVerifierEJB would
be a session bean

● Also when: The bean's state must be persistent. If the bean instance terminates or if the J2EE server
is shut down, the bean's state still exists in persistent storage (a database).

What is a Message Driven Bean

Brief Introduction of JMS

● The Java Message Service is a Java API that allows applications to create, send, receive, and read
messages

● Designed by Sun and several partner companies, the JMS API defines a common set of interfaces
and associated semantics that allow programs written in the Java programming language to
communicate with other messaging implementations

● The JMS API minimizes the set of concepts a programmer must learn to use messaging products but
provides enough features to support sophisticated messaging applications

● It also strives to maximize the portability of JMS applications across JMS providers in the same
messaging domain

● The JMS Specification was first published in August 1998 and the latest JMS API version is 1.1
which is the part of J2EE 1.4

What is a Message Driven Bean

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (208 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● A message-driven bean is an enterprise bean the allows J2EE applications to process messages
asynchronously.

● It acts as a JMS message listener

● The messages may be sent by:


❍ Any J2EE component

❍ An application client

❍ Another enterprise bean

❍ A Web component

❍ By a JMS application

❍ System does not use J2EE technology

● Message Driven-beans currently process only JMS messages, but in future they may be used to
process other kind of messages

Message Driven Beans (Contd.)

● When a message arrives, the container calls the message-driven bean's onMessage method to process
the message

● The onMessage method may call helper methods, or it may invoke a session or entity bean to process
the information in the message or to store it in a database

● A message may be delivered to a message-driven bean within a transaction context, so that all
operations within the onMessage method are part of a single transaction

● If message processing is rolled back, the message will be redelivered

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (209 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

What makes Message Driven Beans Different from Other Beans

● The most visible difference between message-driven beans and session and entity beans is that
clients do not access message-driven beans through interfaces

● A message-driven bean has only a bean class and A message-driven bean's instances retain no data
or conversational state for a specific client

● A single message-driven bean can process messages from multiple clients.

● All instances of a message-driven bean are equivalent, allowing the EJB container to assign a
message to any message-driven bean instance

● The container can pool these instances to allow streams of messages to be processed concurrently.

When to use Message Driven Beans

● Session beans and entity beans allow you to send JMS messages and to receive them synchronously,
but not asynchronously

● To avoid tying up server resources, you may prefer not to use blocking synchronous receives in a
server-side component

● To receive messages asynchronously, use a message-driven bean

Defining Client Access With Interfaces

Client Access with Interfaces

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (210 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● A client may access a session or an entity bean only through the methods defined in the bean's
interfaces

Client are dependent on Abstracton and not on Implementation

● These interfaces define the client's view of a bean.

Any method in the implementation class that is not defined on the face of the interface will not be
made available to the clients (jsp(s), servlets, midlets, swing apps)

● All other aspects of the bean--method implementations, deployment descriptor settings, abstract
schemas, and database access calls--are hidden from the client

● Well-designed interfaces simplify the development and maintenance of J2EE applications.

If you were to change the method definitions in the interfaces, then you might have to modify the
client code as well

● They also allow the beans to change internally without affecting the clients.

To isolate your clients from possible changes in the beans, it is important that you design the
interfaces carefully.

Remote Access

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (211 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● When you design a J2EE application, one of the first decisions you make is the type of client access
allowed by the enterprise beans:
❍ remote or

❍ local

● A remote client of an enterprise bean may run on a different machine and a different Java virtual
machine (JVM) than the enterprise bean it accesses. (It is not required to run on a different JVM.)

● A remote client of an enterprise bean can be a Web component, a J2EE application client, or another
enterprise bean.

● To a remote client, the location of the enterprise bean is transparent

● To create an enterprise bean with remote access, you must code a remote interface and a home
interface
❍ The remote interface defines the business methods that are specific to the bean (e.g

debitAccount(), creditAccount())
❍ The home interface defines the bean's life cycle methods--create and remove

For entity beans, the home interface also defines finder methods and home methods. Finder methods are used to
locate entity beans

Local Access

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (212 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● A local client must run in the same JVM as the enterprise bean it accesses.

● A local client may be a Web component or another enterprise bean and To the local client, the
location of the enterprise bean it accesses is not transparent

● It is often an entity bean that has a container-managed relationship with another entity bean and
hence must have local interfaces

● To build an enterprise bean that allows local access, you must code the local interface and the local
home interface

● The local interface defines the bean's business methods, and the local home interface defines its life
cycle and finder methods

Deciding on Remote or Local Access

● The decision regarding whether to allow local or remote access depends on the factors explained in
following points:

● Container-managed relationships: If an entity bean is the target of a container-managed relationship,


it must use local access

● Tight or loose coupling of related beans: Tightly coupled beans depend on one another. Since they fit
together as a logical unit, they probably call each other often and would benefit from the increased
performance that is possible with local access.

● Types of client: If an enterprise bean is accessed by J2EE application clients, then it should allow
remote access.

● If an enterprise bean's clients are Web components or other enterprise beans, then the type of access
depends on how you want to distribute your components.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (213 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Deciding on Remote or Local (Contd.)

● Component distribution: J2EE applications are scalable because their server-side components can be
distributed across multiple machines. In a distributed application, for example, the Web components
may run on a different server than the enterprise beans they access. In this distributed scenario, the
enterprise beans should allow remote access

● If you aren't sure which type of access an enterprise bean should have, then choose remote access.
This decision gives you more flexibility--in the future you can distribute your components to
accommodate growing demands on your application

● Although uncommon, it is possible for an enterprise bean to allow both remote and local access.
Such a bean would require both remote and local interfaces

Performance and Access

● Remote calls may be slower than local calls

● On the other hand, if you distribute components among different servers, you might improve the
application's overall performance

● Both of the above statements are generalizations; actual performance can vary in different
operational environments

● Nevertheless, you should keep in mind how your application design might affect performance

Method Parameters
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (214 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● The type of access affects the parameters of the bean methods that are called by clients. The
following points apply not only to method parameters, but also to method return values

● An argument in a remote call is passed by value; it is a copy of an object WHERE-AS An argument


in a local call is passed by reference, just like a normal method call in the Java programming
language

● The parameters of remote calls are more isolated than those of local calls

● With remote calls, the client and bean operate on different copies of a parameter object

● If the client changes the value of the object, the value of the copy in the bean does not change

The Contents of an Enterprise Bean

The Contents of Enterprise Beans

● Deployment descriptor: An XML file that specifies information about the bean such as its
persistence type and transaction attributes. The deploytool utility creates the deployment descriptor
when you step through the New Enterprise Bean wizard.

● Enterprise bean class: Implements the methods defined in the following interfaces.

● Interfaces: The remote and home interfaces are required for remote access. For local access, the local
and local home interfaces are required.(Please note that these interfaces are not used by message-
driven beans.)

● Helper classes: Other classes needed by the enterprise bean class, such as exception and utility
classes

● You package all of these files into an EJB JAR file, the module that stores the enterprise bean

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (215 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Portability

● An EJB JAR file is portable and may be used for different applications

● To assemble a J2EE application, you package one or more modules--such as EJB JAR files--into an
EAR file, the archive file that holds the application

● When you deploy the EAR file that contains the bean's EJB JAR file, you also deploy the enterprise
bean onto the J2EE server

Naming Conventions of Enterprise Beans

The Naming Conventions

The Case - Study

The Problem Statement

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (216 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Premier Auto Electric is a company doing trading business in Auto-Spare parts. They have 34
locations all over India. The core business processes includes Purchase and Sales. Your teams is
tasked with the development of Sales Module.

● The Salesmen bring orders from the Customers (Stockists of PAE). These orders are to be recorder
in the system by the Sales Officer or Salesman who brings the orders. Note that the customer cannot
record the orders online.

● The Sales Manager then prepares the invoices based on the sales order that are recorded.

● The system keeps track of the inventory and depletes the same when invoices are prepared. Also the
Customer can logon and record the Automobiles - the spare parts of which he deals in. This will help
PAE to identify its own stocking needs.

● The use-cases identified are: Manage Sales Order which includes: creating, updating and deleting
the order AND Manage Invoice which also includes: creating, updating and deleting the invoice.
Also a use-case: Record Automobile is required in the system

Please note that the objective is not to develop the entire application here. We will only use this case-study to help
us learn topics of the subject meaningfully. Such real-life examples adds more flavour to learning process.

Chapter: 2 - Session Beans

Creating a Stateless Session Bean

Writing the implementation Bean Class

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (217 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● This class is exactly the one which contains implementation of business methods - i.e. your business logic.

We are developing this bean as per the case-study discussed earlier. We will develop OrderManager - Session Bean
which will serve the purpose of use-case controller/manager for the "Manage Sales Order" use case in the
application.

● Create a new EJB module with the name SalesEJB and then create the package in it with the name: businesslogic.
Now within businesslogic create a package called session.

● Within this package create a class with the name OrderManagerBean.java. Please note we are following the
naming convention - Infact we must.

● Implement SessionBean interface in this class. Since, SessionBean interface is in javax.ejb package, you have to
import the class from the said package.

● As you know, implementing the interface is implementing all the methods declared on the face of the interface:
hence implement following methods:

public void ejbActivate() throws EJBException, RemoteException


{
}

public void ejbPassivate() throws EJBException, RemoteException


{
}

public void ejbRemove() throws EJBException, RemoteException


{
}

public void setSessionContext(SessionContext arg0) throws EJBException,


RemoteException
{
}

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (218 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

The methods implemented above are of hardly any use in case of Stateless Session Beans - they are useful in
Stateful beans. Since the both the type of beans implements the same interface we have to write dummy
implementations of the above mentioned methods.

Writing Business Methods in Implementation Bean Class

● Write two business methods in the OrderManagerBean.java class

public void createOrder() {


System.out.println("Creating the order....");

public void editOrder() {


System.out.println("Editing the order....");
}

● These business methods are the ones which serves the use case logic of Use Case - Manage Sales
Order.

● We have deliberately not put any processing code in these methods - only to keep the example
simple.

● We will later revisit these methods and add more code to it.

Writing ejbCreate Method


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (219 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● When the client invokes create method on the home, the EJB-Container creates the instance of the
bean and executes the ejbCreate Method in the implementation bean class

● Hence please create ejbCreate method in the implementation bean class as follows:

public void ejbCreate() throws CreateException {

// SOP - Executing ejbCreate Method.

Creating Remote Interface

● Create a new interface - OrderManager.java, in the same package in which you have created the
OrderManagerBean.java. Extend this interface from EJBObject. The interface EJBObject is in javax.
ejb package.

● Declare two methods in this interface as follows:

public void createOrder() throws RemoteException;


public void editOrder() throws RemoteException;

● Please note that the method name and signature is as same as the business methods declared in
OrderManagerBean.java.

● The business methods declared here are methods that will be made available to the client of the
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (220 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

OrderManager Bean.

Re-Collect that the bean class is made up of not just the implementation bean class but also the home
and remote interfaces. Note that what we have written now is the Remote Interface

● We have created a Remote Interface and hence (as per ejb specs), each business method must throw
RemoteException which is available in java.rmi package - Please import this class in OrderManager
interface.

Extra explore: Please open the j2ee.jar file (The name of the file may differ based on what application server you
are using). Explore the javax.ejb pacakage - you will find all the classes and interfaces we are using for e.g.
SessionBean, EJBObject, EJBHome etc.

Creating Home Interface

● Now create one more new interface called OrderManagerHome.java. Extend this interface from javax.
ejb.EJBHome. - Needless to say that this interface must also be in the same package in which you have
created the OrderManagerBean.java and OrderManager.java

● Declare a create method in this interface as follows:

public OrderManager create() throws CreateException, RemoteException;

● Note the throws clause here: Each create method must throw a CreateException (as per ejb specs). The
CreateException is in javax.ejb package.

● Re-Compile all the classes.

● Now your bean is ready to be deployed. Once again - the total number of .class files now we have is 3 -
1. The implementation bean class (OrderManagerBean.java)
2. The Remote Interface (OrderManager.java)
3. The Home Interface (OrderManagerHome.java)
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (221 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

Note that the implementation bean class does not in any way specify the names of home and remote interface. It is
the deployment descriptor where the relationship/dependency among these classes are specified.

Deploying the bean

● Now that we have created all the necessary .class files, we can deploy the same to the application
server

● There n number of ways in which you can deploy an ejb. First of all please note that an individual
bean is never deployed. It is bundled into a module (a .jar file) and then deployed

● The .jar file (ejb module) consists of


a. all the .class files of a bean (there can be more than one bean in one single module) and
b. The deployment descriptor - a .xml file which contains the bean's description (description of
one or more beans in the module)

● How do you create the ejb module ?. You can create ejb module either - with the help of
"deploytool" utility provided by the application server you are using or with the help of "ide" you are
using. IDE(s) like Pramati Studio, Sun One Studio, WebLogic WorkShop (my favourite),
WebSphere Developer Studio etc.

If you are using any IDE, it will help you to assemble the bean, create the deployment descriptor
(xml file), generate a jar file and deploy the same to the application server configured.

● Use any technique you prefer (I will help you with the IDE you are using) and deploy the bean

Accessing a Session Bean from Servlet

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (222 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Creating JSP(s)

● Create index.jsp in your Web Module (Create a new web module in your application if not yet created)

● Write the following code in index.jsp:

<h1>Welcome to Sales Management System</h1>


<hr>
<a href="order.jsp">Create New Order</a>

● Also create order.jsp and write the following code in

<h3 align="center">Enter Order Details</h3>


<form action="orderServlet">
<table border="1">
<tr>
<td>Order Id</td>
<td><input type="text" name="id"/></td>
</tr>
<tr>
<td>Customer</td>
<td><input type="text" name="customerId"/></td>
</tr>
<tr>
<td>Product</td>
<td><input type="text" name="productId"/></td>
</tr>
<tr>
<td>Quantity</td>
<td><input type="text" name="quantity"/></td>
</tr>
<tr>
<td>Rate</td>
<td><input type="text" name="rate"/></td>
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (223 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Save Order"/></td>
</tr>
</table>
</form>

● Note that from index.jsp we are moving to order.jsp and when the user clicks on submit button, we will
move to orderServlet. It is the OrderServlet from where we are going to access the Session Bean

● Deploy your web module and run the applcation. (You will get an error when you click on submit
button on order.jsp. This is because we have not yet created the OrderServlet)

Creating the OrderServlet

● Create OrderServlet.java in servlets package of your web-module and call doGet method from doPost method

● Add the following code in the doGet method of the servlet:

try {
Context ctx = new InitialContext();
Object obj = ctx.lookup("java:comp/env/ejb/OrderManager");
OrderManagerHome orderHome = (OrderManagerHome) PortableRemoteObject.narrow
(obj, OrderManagerHome.class);
OrderManager orderManager = orderHome.create();
orderManager.createOrder();

} catch (NamingException ex) {


out.println("Naming Exception : " + ex.getMessage());
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (224 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

return;

} catch (CreateException ex) {


out.println("Create Exception : " + ex.getMessage());
return;

} catch (RemoteException ex) {


out.println("Remote Exception : " + ex.getMessage());
return;
}

● Note the following in the above given code snippet:


❍ The JNDI api is used to lookup for the Home of the enterprise bean.

❍ You need to perform some low-level operations on the Remote Home object obtained and hence

PortableRemoteObject.narrow
❍ create Method is used on the Home interface to obtain the Remote Object

❍ Once the Remote Object is obtained, you can now invoke the business method on it

❍ Note the exceptions that are caught

❍ Context, InitialContext and NamingException is in javax.naming and PortableRemoteObject is in javax.rmi package

● The servlet is not dependent on implementation bean class i.e. OrderManagerBean. It is dependent / has a contract with the
Home and Remote interfaces only. Now we can say that The client class i.e. the servlet is dependent on abstraction - the
interfaces and not on implementation - the OrderManagerBean

These Home and Remote classes must be made available to the Web-Module. The best way is to bundle them into a jar file
and put the jar file in WEB-INF/lib folder. Use IDE feature to do this

● Please do not forget to configure the url pattern : orderServlet to the servlet just created. WAIT............. Do not hurry - and
run the application. We have not yet set the ejb-coded reference name for the ejb used in the above given code snippet - ctx.
lookup("java:comp/env/ejb/OrderManager"). Move to next slide for more details

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (225 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Configuring EJB Coded Reference Name

● There are two ways in which you can lookup for the enterprise bean.
1. Directly through its jndi name
2. Through Coded Reference Name

● There is nothing wrong in directly using the jndi name to lookup. But then if the jndi name of the
Remote Object changes, you will have to make changes in the entire web-app where ever you have
used the jndi name to lookup for that particular bean

● On the other hand, you can configure a ejb-coded name of your choice in your web-module which
will be mapped to the jndi name of the Remote Object. Now you use your ejb-coded ref name to
lookup instead of jndi name of the bean. This approach offers more loose coupling.

● Configure the ejb-coded ref name in your web-module so that any web-component (servlet x, y or z)
can lookup for the Remote Object mapped to the ejb-coded ref name.

You can do this with the help of IDE you are using or the deploytool provided by your app server.
What ever is the technique - please note that the configuration finally goes in web.xml file

● NOW that you have done all that was supposed to be done, Re-Compile, Re-Deploy and run your
application. Note the SOP results on app server console which you had coded in createOrder
business method of the OrderManagerBean.java

Local Access to Session Bean

Local Home and Local Object

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (226 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● In the previous example we have created two interfaces - OrderManagerHome - the home interface
(Home for remote access) and OrderManager - the remote interface again - for remote access

● Keeping the implementation bean class as it is, we can create LocalOrderManagerHome - the Local
Home Interface and LocalOrderManager - the Local Object.

● LocalOrderManagerHome will be extended from EJBLocalHome and LocalOrderManager will be


extended from EJbLocalObject.

● In such a case you will be able to access OrderManager bean locally i.e. from any component which
is deployed in the same EAR. Any J2EE component running on remote machine (remote process)
will not be able to access the bean. This will improve the performance but will no longer make this
object a distributed object

● However, please note that a particular ejb can have both : Local and Remote interfaces. In such a
case there will be 4 interfaces declared in total.

The Difference

● The business methods declared in the local interface will not throw RemoteException

● Also in the servlet when you lookup for the local object, you will not have to use
PortableRemoteObject.narrow after lookinup the bean - simply because it is not a Remote Object.

● While setting the ejb coded ref name, you will specify that the interfaces of the bean are local and
not remote.

● The performance will be very good but then as explained earlier, any j2ee component out of the ear
in which the ejb with local access is created will not be able to access the ejb

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (227 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Creating a Stateful Session Bean

Creating implementation bean class

● Re-Collect from the Case-Study that there was a use case called: Record Autmobiles, where customer (stockists of PAE) can
record the Automobiles - the spare parts of which they deal in. The user must be able to enter the automobile name for e.g.
Honda, Hyundai, Tata etc. on a jsp. After he finally confirms his entry the system must save all his selection/entries in the
database. Let us start developing this use case by first developing the SFSB called ProductLineManager

● Create a new class called ProductLineManagerBean.java in the same EJB Module in which we had created the SLSB -
OrderManagerBean.java.The package must again be businesslogic.session i.e. session package within businesslogic.

● Implement SessionBean in this class and thereby also implement all the methods of the SessionBean interface - exactly as
same as we had done in case of OrderManagerBean.java. Do not forget implement ejbCreate method as follows:

public void ejbCreate() throws CreateException {

● This time create one instance variable in the ProductLineManagerBean.java as Collection productLine = new ArrayList().
Import java.util.* in this class. It is this instance variable in which we will maintain all the Automobile-names that the user
selects/enters before saving it to the database

● Add three business methods in the ProductLineManagerBean.java as follows:

public void addAutomobileName(String name) {


productLine.add(name);
}

public Collection getAutomobileNames() {


return this.productLine;
}

public void saveAutomobileNames() {


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (228 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

// the business logic of adding the contents of productLine collection to


the database
// can be written here
System.out.println("Writing Names to the database...........");
}

Note that we are not coding how to save the data to the database through saveAutoMobileNames business method.
The objective here is to understand how the SFSB works and not how to interact with the database.

Creating Remote Interface

● Create a new interface - ProductLineManager.java, in the same package in which you have created the
ProductLineManagerBean.java. Extend this interface from EJBObject. The interface EJBObject is in javax.
ejb package.

● Declare three methods in this interface as follows:

public void addAutomobileName(String name) throws RemoteException;


public Collection getAutomobileNames() throws RemoteException;
public void saveAutomobileNames() throws RemoteException;

● Please note that the method name and signature is as same as the business methods declared in
ProductLineManagerBean.java

● The business methods declared here are methods that will be made available to the client of the
ProductLineManager Bean.

Re-Collect that the bean class is made up of not just the implementation bean class but also the home and
remote interfaces. Note that what we have written now is the Remote Interface

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (229 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● We have created a Remote Interface and hence (as per ejb specs), each business method must throw
RemoteException which is available in java.rmi package - Please import this class in OrderManager
interface

Creating Home Interface

● Now create one more new interface called ProductLineManagerHome.java. Extend this interface
from javax.ejb.EJBHome. - Needless to say that this interface must also be in the same package in
which you have created the ProductLineManagerBean.java and ProductLineManager.java

● Declare a create method in this interface as follows:

public ProductLineManager create() throws CreateException;

● Note the throws clause here: Each create method must throw a CreateException (as per ejb specs).
The CreateException is in javax.ejb package.

● Re-Compile all the classes

● Now your bean is ready to be deployed. The total number of .class files now we have is 3 -
1. The implementation bean class (ProductLineManagerBean.java)
2. The Remote Interface (ProductLineManager.java)
3. The Home Interface (ProductLineManagerHome.java)

Deploying the Bean

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (230 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Now that we have created all the necessary .class files, we can deploy the same to the application
server

● There n number of ways in which you can deploy an ejb. First of all please note that an individual
bean is never deployed. It is bundled into a module (a .jar file) and then deployed

● The .jar file (ejb module) consists of


a. all the .class files of a bean (there can be more than one bean in one single module) and
b. The deployment descriptor - a .xml file which contains the bean's description (description of
one or more beans in the module)

● How do you create the ejb module ?. You can create ejb module either - with the help of
"deploytool" utility provided by the application server you are using or with the help of "ide" you are
using. IDE(s) like Pramati Studio, Sun One Studio, WebLogic WorkShop (my favourite),
WebSphere Developer Studio etc.

If you are using any IDE, it will help you to assemble the bean, create the deployment descriptor
(xml file), generate a jar file and deploy the same to the application server configured.

● We did not anywhere in our code specifiy that the bean is stateful. Then how does the container
understand that it is a stateful bean ? - At the time of deployment. When you deploy the bean, you
have to specify in the deployment descriptor (ejb-jar.xml) that the bean is Stateful.

Accessing Stateful Session Bean

Creating the JSP(s)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (231 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Create a jsp called index.jsp (Do not recreate if you already have one in your app.). Add an anchor on it as follows: <a
href="productline.jsp">Record Product Line</a>

● Create one more jsp called productline.jsp and add the following code:

<h3 align="center">Add Automobile Names which constitutes your Product Line</h3>


<hr>
<form method="get" action="productLineServlet">
<input type="text" name="automobileName"/>
<input type="submit" name="submit" value="Add"/>
</form>
<br>
The List you have added includes
<hr>
<%
if (request.getAttribute("automobileNames") != null) {
Collection automobileNames = (Collection) request.getAttribute
("automobileNames");
for (Iterator i = automobileNames.iterator(); i.hasNext(); ) {
String automobileName = (String) i.next();
out.println(automobileName+"<br>");
}
}
%>
<hr>
<a href="">Save</a>

● Note the scriptlet written above. We will discuss the same later.

● When the user clicks on Record Product Line anchor in index.jsp the system presents productline.jsp to the user where he
can enter the Automobile name and click on add.

● When the user clicks on add, on productline.jsp, the system executes a servlet "ProductLineServlet" on the server, the
servlet will access the SFSB - ProductLineManager add the name of the product to it, return the control back to
productline.jsp - so that user can continue adding more Automobile names.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (232 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Creating ProductLineServlet

● Create ProductLineServlet.java in servlets package of your web-module and call doGet method from doPost method

● Add the following code in doGet method of the servlet:

ProductLineManager productLineManager = null;


String automobileName = request.getParameter("automobileName");
HttpSession session = request.getSession();
Object objectInHttpSession = session.getAttribute("productLineManager");
if (objectInHttpSession == null) {
try {
Context ctx = new InitialContext();
Object obj = ctx.lookup("java:comp/env/ejb/ProductLineManager");
ProductLineManagerHome productLineManagerHome =
(ProductLineManagerHome) PortableRemoteObject.narrow(obj, ProductLineManagerHome.
class);
productLineManager = productLineManagerHome.create();
session.setAttribute("productLineManager", productLineManager);

} catch (NamingException ex) {


out.println("Naming Exception : " + ex.getMessage());

} catch (CreateException ex) {


out.println("Create Exception : " + ex.getMessage());

}
} else {
productLineManager = (ProductLineManager) objectInHttpSession;
}

try {
productLineManager.addAutomobileName(automobileName);
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (233 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

Collection allNames = productLineManager.getAutomobileNames();


request.setAttribute("automobileNames", allNames);
RequestDispatcher dispatcher = request.getRequestDispatcher("productline.
jsp");
dispatcher.forward(request, response);
} catch (RemoteException ex) {
out.println("Remote Exception : " + ex.getMessage());
return;
}

● Note the following in the above given code snippet:


❍ The JNDI api is used to lookup for the Home of the enterprise bean.

❍ You need to perform some low-level operations on the Remote Home object obtained and hence PortableRemoteObject.

narrow
❍ create Method is used on the Home interface to obtain the Remote Object

❍ Once the Remote Object is obtained, you can now invoke the business method on it

❍ The exceptions : Context, InitialContext and NamingException are in javax.naming and PortableRemoteObject is in

javax.rmi package

● The servlet is not dependent on implementation bean class i.e. ProductLineManagerBean.java. It is dependent / has a contract
with the Home and Remote interfaces only. Now we can say that The client class i.e. the servlet is dependent on abstraction -
the interfaces and not on implementation - the ProductLineManagerBean

These Home and Remote classes must be made available to the Web-Module. The best way is to bundle them into a jar file and
put the jar file in WEB-INF/lib folder. Use IDE feature to do this

● Please do not forget to configure the url pattern : productLineServlet to the servlet just created. We have not yet set the ejb-
coded reference name for the ejb used in the above given code snippet - ctx.lookup("java:comp/env/ejb/ProductLineManager").
Move to next slide for more details

Configuring EJB Coded Reference Name


file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (234 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● There are two ways in which you can lookup for the enterprise bean.
1. Directly through its jndi name
2. Through Coded Reference Name

● There is nothing wrong in directly using the jndi name to lookup. But then if the jndi name of the
Remote Object changes, you will have to make changes in the entire web-app where ever you have
used the jndi name to lookup for that particular bean

● On the other hand, you can configure a ejb-coded name of your choice in your web-module which
will be mapped to the jndi name of the Remote Object. Now you use your ejb-coded ref name to
lookup instead of jndi name of the bean. This approach offers more loose coupling

● Configure the ejb-coded ref name in your web-module so that any web-component (servlet x, y or z)
can lookup for the Remote Object mapped to the ejb-coded ref name.

You can do this with the help of IDE you are using or the deploytool provided by your app server.
What ever is the technique - please note that the configuration finally goes in web.xml file

● NOW that you have done all that was supposed to be done, Re-Compile, Re-Deploy and run your
application. Note the following:
1. When the user clicks on Add button after entering the name, the ProductLineServlet gets
executed.
2. The ProductLineServlet uses the bean (from http session or creates a new one) and adds the
name to it
3. Then all the names are taken from the bean (that were added in earlier requests) and put in the
request object using getAutomobileNames() method
4. The control is then forwarded to productline.jsp
5. The productline.jsp reads the collection from the request (now see the scriptlet written in
productline.jsp) and renders the names using out.println

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (235 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Chapter: 3 - Developing Entity Beans (BMP & CMP)

Introduction to Entity Beans

Entity Beans - Heart of Business Apps

● Data is the heart of most business applications

● In J2EE applications, entity beans represent the business objects stored in a database

● For entity beans with bean-managed persistence, you must write code for the database access calls

● Writing this code is additional responsibility, but you will have more control over how the entity
bean access a database

● We will develop a BMP for Order table. We have Manage Sales Order use case in which the details
the Sales Order Details are entered by the user. The OrderServlet then makes a createOrder call to
the Session Bean - OrderManager. We will now develop a BMP - Order which we will access locally
from OrderManage session bean.

Order Entity Bean

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (236 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● We will discuss the coding technique for entity beans with bean-managed persistence taking Order
Bean from our case-study

● The Order Bean represents an Order received recorded by the Sales Office / SalesMan which is
received from the customer

● The state of OrderEJB is stored in the Order table in the database

● The structure of the table in the database is as follows:


❍ id - varchar (3) – this is the primary key

❍ customerid– varchar(5)

❍ productid - varchar (5)

❍ quantity - number (5)

❍ rate - number(5)>

● The OrderEJB requires following class files:


1. The OrderBean.java - implementation bean class
2. LocalOrder.java - local interface
3. LocalOrderHome.java - local home

Writing the Implementation Bean Class

The Entity Bean Class

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (237 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● The OrderEntityBean class must meet the following requirements like any other entity bean class:
❍ Implements EntityBean interface

❍ Zero or more ejbCreate and ejbPostCreate methods

❍ Finder methods

❍ Business methods

❍ Home methods

● In addition, an entity bean class with bean-managed persistence has following requirements:
❍ The class is defined as public

❍ The class cannot be defined as abstract or final

❍ It contains an empty constructor

❍ It does not implement the finalize method

● The EntityBean interface extends the EnterpriseBean interface, which extends the Serializable
interface

● The EntityBean interface declares number of methods, such as ejbActivate and ejbLoad, which you
must implement in your entity bean class

The OrderBean Entity Class

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (238 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Please create a new ejb module and create the following package structure: com.<your company name>.sales.model.entity. Lets
create implementation bean class which will adhere to ejb specs.

● Note the following in the implementation bean class written below:


❍ It implements EntityBean interface and hence all the methods of that interface.

❍ The ejbLoad and ejbStore methods. (We will write code in these methods later).

❍ The persistent fields declared like id, orderDate, customerId etc.

● The implementation bean class must be written as follows:

import javax.ejb.*;

public class OrderBean implements EntityBean {


EntityContext entityContext;
java.lang.Integer id;
java.util.Date orderDate;
java.lang.Integer customerId;
java.util.Date validityDate;
public java.lang.Integer ejbCreate(java.lang.Integer id, java.util.Date orderDate,
java.lang.Integer customerId, java.util.Date validityDate) throws CreateException {
setId(id);

setOrderDate(orderDate);
setCustomerId(customerId);
setValidityDate(validityDate);
return null;
}
public void ejbPostCreate(java.lang.Integer id, java.util.Date orderDate, java.lang.
Integer customerId, java.util.Date validityDate) throws CreateException {
/**@todo Complete this method*/
}
public void ejbRemove() throws RemoveException {
/**@todo Complete this method*/
}
public void setId(java.lang.Integer id) {
this.id = id;
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (239 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

}
public void setOrderDate(java.util.Date orderDate) {
this.orderDate = orderDate;
}
public void setCustomerId(java.lang.Integer customerId) {
this.customerId = customerId;
}
public void setValidityDate(java.util.Date validityDate) {
this.validityDate = validityDate;
}
public java.lang.Integer getId() {
return id;
}
public java.util.Date getOrderDate() {
return orderDate;
}
public java.lang.Integer getCustomerId() {
return customerId;
}
public java.util.Date getValidityDate() {
return validityDate;
}
public java.lang.String ejbFindByPrimaryKey(java.lang.String untitledField1) throws
FinderException {
/**@todo Complete this method*/
return null;
}
public void ejbLoad() {
/**@todo Complete this method*/
}
public void ejbStore() {
/**@todo Complete this method*/
}
public void ejbActivate() {
/**@todo Complete this method*/
}
public void ejbPassivate() {
/**@todo Complete this method*/
}

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (240 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

public void unsetEntityContext() {


this.entityContext = null;
}
public void setEntityContext(EntityContext entityContext) {
this.entityContext = entityContext;
}
public java.lang.Integer ejbFindByPrimaryKey(java.lang.Integer id) throws
FinderException {
/**@todo Complete this method*/
return null;
}
}

Connection Pool

● What we are developing is a bean managed persistent entity. Hence we have to implement database
logic (inserting, deleting etc.). For this reason we will have obtain the connection object through
which we will talk to the database.

● Now how do we get the connection object. Our entity bean will be deployed on the application
server. The application server maintains pool of connection objects. We can obtain one of the
connection objects from the pool, make database calls using this connection object and leave it back
in the pool.

● If the connection object is to be obtained from the pool, we wil need to create a connection pool in
the database. Use Admin-Console of Weblogic / Pramati Application Server / make entries in the
apprpriate xml file of JBoss (Refer to your application server documentation to know how to create a
connection pool) to create a connection pool.

● The Connection Pool creates connection objects of type: javax.sql.DataSource and maintains the
same. Please note this is an interface. The specific driver that you will use in order to create
Connection Pool has a class which implements this interface.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (241 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● In order to obtain one of the connection objects from the pool (which will be of type javax.sql.
DataSource), we will have to create a JNDI DataSource which will be mapped to the connection
pool. Please use admin console of your Application Server to create the DataSource.
Once created, you can lookup for this datasource from your bmp using JNDI to get the
connection object

Getting Connection Object in Bean

● Please note that there is a method called setEntityContext in your bean which is called by the container
when the bean is first created. This is the ideal place to lookup the datasource and keep it in instance
variable. Lets write a private method called initializeDataSource and call it from setEntityContext.

● Create a variable in the bean as follows:

private EntityContext entityContext;

● Now create a private initializeDataSoruce method as follows:

private DataSource initializeDataSource() throws NamingException {


Context ctx = new InitialContext();

ds = (DataSource) ctx.lookup("jdbc/TrainingDB");
return ds;

● Now write the following in setEntityContext method

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (242 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

this.entityContext = entityContext;
try {
ds = this.initializeDataSource();
} catch (NamingException ex) {
throw new EJBException(ex.getMessage());
}

Writing the ejbCreate Method

● The bean that we are developing is a BMP entity bean. This means that we need to implement the database logic not the
container.

● When you invoke create bean from the client class, it is the ejbCreate that gets executed. The ejbCreate method (as per ejb
specs) is expected to insert a row in the table. Note the arguments passed as parameters to ejbCreate/create method.

● Instead of writing all database logic in ejbCreatre we will simply write a private method - insertRow() which we will call
from ejbCreate method. Write the insertRow method as follows:

private void insertRow(Integer id, Date orderDate, Integer customerId, Date


validityDate) throws SQLException {
Connection con = ds.getConnection();
String sql = "Insert into SalesOrder (id, orderDate, customerId, validityDate)
values ( ?, ?, ?, ?)";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setInt(1, id.intValue());

stmt.setDate(2, new java.sql.Date(orderDate.getTime()));


stmt.setInt(3, customerId.intValue());
stmt.setDate(4, new java.sql.Date(validityDate.getTime()));
stmt.execute();

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (243 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Please note that we have obtained connection object from connection pool through a datasource - ds which was initialized
from setEntityContext method.

● Let us call insertRow from ejbCreate as follows:

try {
insertRow(id, orderDate, customerId, validityDate);
} catch (SQLException ex) {
throw new CreateException(ex.getMessage());
}
setId(id);

setOrderDate(orderDate);
setCustomerId(customerId);
setValidityDate(validityDate);
return id;

● Note that we have returned the value of id if row was successfully created (also synchronized the intsance variables with the
values that were passed as parameters) else we throw CreateException

Writing Home & Local Interfaces

Writing Local & Home Interfaces

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (244 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Please note that we are writing code for entity bean which we intend to access from session bean locally. As per
our design, we will never invoke a method on this entity bean from out of the container.

● Considering this, we need to create a local interface called Order which will extend from EJBLocalObject. Write
the interface as follows:

import javax.ejb.*;
import java.util.*;

public interface Order extends javax.ejb.EJBLocalObject {


public Integer getId();
public void setOrderDate(Date orderDate);
public Date getOrderDate();
public void setCustomerId(Integer customerId);
public Integer getCustomerId();
public void setValidityDate(Date validityDate);
public Date getValidityDate();
}

● Now let is write a local home interface called OrderHome which will be extend EJBLocalHome. Write the
interface as follows:

import javax.ejb.*;
import java.util.*;

public interface OrderHome extends javax.ejb.EJBLocalHome {


public Order create(Integer id, Date orderDate, Integer customerId, Date
validityDate) throws CreateException;
public Order findByPrimaryKey(Integer id) throws FinderException;
}

● Now your ejb is ready to be deployed. Atleast create will work We will then later write code for find, remove
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (245 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

and update.

Accessing Entity from Session

Writing Code in Session Bean

● Please reuse the OrderManager that we have already written. You have a method called createOrder
in the Session Bean. Please change the signature of the bean such that it accepts 4 parameters viz.
Integer id, Date orderDate, Integer customerId, Date validityDate.

● Here is the code that you need to write in Entity Bean:

OrderHome home = null;


Order order = null;
try {
Context ctx = new InitialContext();
home = (OrderHome) ctx.lookup("java:comp/env/ejb/Order");
order = home.create(id, orderDate, customerId, validityDate);

} catch (NamingException ex ){
throw new EJBException(ex.getMessage());
} catch (CreateException ex) {
throw new EJBException(ex.getMessage());
}

Recompile and deploy the SalesEJB module

● We have already written code in the servlet which calls createOrder method on the session bean. Only
change the signature in the servlet to call createOrder passing all the four parameters expected by the
method. Hard code the values for the time-being and then later you can accept values from the user on
jsp, call servet, from servlet invoke createOrder on session bean and finally session bean invokes
create in Entity Bean.
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (246 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

● Re-Deploy the web application and see the results.

Finding Entity Bean

findByPrimaryKey method

● You already have a findByPrimaryKey method declared in OrderHome (note that it throws
FinderException)

● There is a corresponding method called ejbFindByPrimaryKey in the bean which is called by when
the client component invokes findByPrimaryKey. You know that the client component gets the view
of Home and Local Interfaces and not of implementation bean class.

● Insead of directly writing database logic in ejbFindByPrimaryKey, we will write searchRow private
method and call from ejbFindByPrimaryKey.

The findByPrimaryKey and ejbFindByPrimaryKey accepts 1 parameter of primary key type. The
only objective of ejbFindByPrimaryKey is to find whether the bean requested is available in
persitent storage (database) or not.

● The code in searchRow private method will be written as follows :

● You need to write following in ejbFindByPrimaryKey method in the implementation bean class:

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (247 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Chapter: 4 - Life Cycle of Enterprise Beans

Life Cycle of Session Bean

Life Cycle of Entity Bean

Life Cycle of Message Driven Bean

The Case Study

Chapter: 1 - Sales & Distribution

The Problem Statement

The Problem Statement

● Premier Auto Electric is a trading company involved in buying and selling of Automobile spare
parts. There are around 28 manufactures who are suppliers to PAE. PAE buys spare parts from these
manufacturers in bulk quantities and sells it to various stockists and dealers all over India on 10% of
profit margin. PAE has 34 sales-locations all over India.

● The sales of spare parts is done to only those dealers who are registered with PAE. Dealers can
submit their registration through the system. While registering, dealer can affiliate to any one sales-
depot out of all the depots of PAE which is spread all over India. The Depot-Manager will evaluate
the credibility of the dealers who have submitted fresh registrations, before the goods are sold to
them and approve or disapprove his registration. While approving the registration, Depot-Manager
sets the credit-days of the dealer which is 45 by default.Each dealer is given the dealer ship of spare
parts of 1 or more automobiles. Dealers can order and buy only those products for which dealer ship
is given to them. This is to maintain no-competition between PAE dealers from the same area.

The dealers can place orders online. The orders can have one or more than 1 products under the
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (248 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

category (automobile) for which they have been given dealership. The order can be modified or
cancelled only before it is invoiced. Once PAE invoices/dispatches the order, the dealer cannot
modiy or cancel the order.

The Sales Manager at the sales depot has a very important responsibility. He has to scan through all
the orders placed by the dealers affiliated to his branch and generate invoices and dispatch
documents. There are high expectations from the system here. There can be many order from various
dealers ordering for one ore more products. The rationing of inventory among the dealers is
important. Hence system must provide the list of product wise orders placed by various dealers. The
sales manager can then decide, as to which product of which order must be serviced. The sales
manager takes this decision based on the credit-limit available of the customer and his receivable
status. The system must provide this status to the Sales-Manager. After Sales-Manager enters the
quantity of against each product ordered, system must auto-generate the customer-wise invoices i.e.
1 invoice per customer for the all orders against which the sales-quantity ordered by the Sales-
Manager is entered as greated than 0

● The system must deplete the inventory of the product that are invoiced, update the receivable status
of the dealer and close the order against which the invoice is created. Note that the order is
considered as closed only after all the products in the orders are invoiced. There is one more way in
which the order on the whole can be closed i.e. the Sales-Manager "marks" a particular order of
dealer as closed.

● The dealer is supposed to make the payment within the credit-days set for him by the Depot-
Manager. The cheques are recorded by the A/Cs officer along with chq date, amount and the
invoices against which the chq(s) are received. This closes the invoices and updates the dealer
receivable status of dealer.

How do you Manage Requirements ?

How do you Model Requirements ?

The Use Case Model

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (249 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Identify the Actors in the system

● Identify Use Cases for each Actor

● Create a Use Case Diagram

● Organize the Actors and Use Cases in appropriate packages in the Use Case View

● Create a Supplementary Specificaton Document illustrating the Usability, Reliability, Scalability and
other non-functional requirements. Also create a Glossary Document defining the terms (nouns of
interest) in the system.

Detail Use Cases

● Detail all the use cases identified in the use case model to illustrate the flow of events of the use case.
The detailing must be done in word document as per the use case template given by unified process.

● Create activity diagrams for each use case to illustrate the flow of events of the use cases.

● Please note: In real-life it is not necessary to do both - writing use cases in word document &
creating activity diagram for it. Any one can suffice.

How do you Model Logical View ?

Perform Architectural Analysis

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (250 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Please refer to the problem statement of Course Registration System and do the following:
❍ Create the first draft of Deployment Diagram

❍ Define the High-Level Organization of Subsystem (Identify Layers)

❍ Establish Relationship between layers

❍ Identify Key Abstractions

❍ Show the identified Key Abstractions on a class diagram called "Key Abstractions"

❍ Briefly describe each key abstraction identified

❍ Establish relationship among these key abstractions

❍ Identify the cardinality (multiplicity) on relationships identified

Perform Use Case Analysis

● Create Use Case Realizations package and realize each use case you have identified.

● Create Sequence Diagrams to illustrate the dynamic behaviour. Identify boundary and controller
classes while doing so.

● Create a VOPC class diagram to present the static structure of the use case.

Refine the Architecture

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (251 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Identify packages in Application and Business Services layers. Identify subsystems.

● Organize the classes within appropriate packages

● Identify the dependencies among these packages. Also describe Architectural Mechanisms (Data
Transfer Object Mechanism, MVC Mechanism)

● Design Database based on entity classes identified so far.

● Create and baseline the deployment diagram

Design Components

● Perform Use Case Design - Take each use can do the use case design (low level design) for each use
case under the umbrella of Architecture (high level design).

● Design Subsystems

● Update VOPC of each use case. Create class diagrams to present significant - static view of each use
case (Hint: 1 class diagram showing only the participating entity classes, the class diagram showing
only boundary and controller classes etc.)

● Design the classes further: Identify the oportunity of re-use. Refactor classes that are identified.
Refine classes to such an extent that you can start writing code.

Chapter: 2 - Purchase Management

The Problem Statement

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (252 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

The Problem Statement

● Premier Auto Electric is a trading company involved in buying and selling of Automobile spare
parts. There are around 28 manufactures who are suppliers to PAE. PAE buys spare parts from these
manufacturers in bulk quantities and sells it to various stockists and dealers all over India on 10% of
profit margin. PAE has 34 sales-locations all over India.

● The purchases are centralized and controlled by head office of PAE. The Depot-Manager constantly
keeps a check on the stock levels of various products. Specially of those which are very fast moving
products (heavly sold). He identifies those products which needs to be ordered so that inventory is
maintained. The system must provide a facility to Depot-Manager to view stock status of only his
depot. He then, identifies the product the inventory which has reached re-order level and raises a
purchase-request for such products. The Depo-Manager sends the purchase request to H.O. The
system maintains the information of the sales-depot who has sent the purchase request.

● There is one Purchase-Controller at the H.O. who receives and acts upon all the purchase requests
that were sent by various sales-depots. He has a very important job to do. He will view the purchase
requests and study the same of each product. He will then see whether the same product is available
at some other sales-depot or not. He will also make note of the age of the inventory of selected
product and only if it is more than 6 months, he will raise the transfer advice to the sales-depot
having the product to transfer it to sales-depot that needs it. The transfer quantity will be equal to
purchase-request quantity or quantity available with transfering depot which ever is lesser. If the
product is not available in any of the sales-deport with age more than or equal to 6 months, then the
Purchase-Controller will mark the product for "ordering".

● The suppliers of PAE are manufacturers. They manufacture specific products belonging to specific
automobile. For e.g. Mico Bausch manufactures clutch plates of Maruti and break pads of Tata-
Indica. This product information along with its rate is maintained in the system for each supplier.
The Purchase-Controller can generate the Purchase Orders based on all the products that were
marked for "ordering". The system must auto-detect the supplier of the product and create 1 purchase
order for each supplier containing all the products that were marked for "ordering". System must
auto-set the "dispatch to:" on the purchase order to the address of sales-depot who had initially
requested the purchase of product. Please note that 1 - Purchase Order will contain aggregate
quantity of products requested by various sales-depot. Hence the bifurcation of "despatch-to" must
be specified on the purchase order. The orders once generated, are printed and couriered to the
Supplier. The status of the Purchase-Request is made available to the Depot-Manager. If the product
has been asked to transfer from one depot to the other - the transfer advice details are shown against
the product requested, if the product was ordered to the supplier - the purchase order details will be

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (253 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

shown against the product requested or else "No-Action-Yet" must be displayed against the product
requested
The Supplier ships the ordered goods to the location specified against "dispatch to:". The Stores
keeper at the respective location will accept the goods and prepare a "Goods Receipt Note". The
GRN will be recorded against either a transfer advice or a purchase order. The system must advice
the Stores Keeper that he must accept the GRN based on transfer advice or purchase order using the
status of purchase request. This will add up the inventory of the product accepted in the stores.

● The Purchase Accounting is done by the Purchase Officer at H.O. centrally. The purchase officer
views all the Supplier Wise - GRN(s) received by various sales-depots and books the purchase.
Purchase Booking involves crediting the Supplier A/C and Debiting the Purchase A/C. This updates
Payable Info of the supplier. The Purchase Officer issues cheques to the Suppliers against the
purchases booked. This again the updates the payable info (reduces the total payable) of the Supplier.
One single cheque can be issued for 1 or more than 1 purchases booked.

How do you Manage Requirements ?

How do you Model Requirements ?

The Use Case Model

Describe Use Cases

How do you Model Logical View ?

Perform Architectural Analysis

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (254 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● Identify the layers in the system. Establish relationship between these layers.

● Identify Key Abstractions and identify the relationships among them. Identify the cardinality
(multiplicity) among these classes

Perform Use Case Analysis

● Create Use Case Realizations package and realize each use case you have identified.

● Create Sequence Diagrams to illustrate the dynamic behaviour. Identify boundary and controller
classes while doing so.

● Create a VOPC class diagram to present the static structure of the use case.

Refine the Architecture

● Identify packages in Application and Business Services layers. Identify subsystems.

● Organize the classes within appropriate packages

● Identify the dependencies among these packages. Also describe Architectural Mechanisms (Data
Transfer Object Mechanism, MVC Mechanism)

● Design Database based on entity classes identified so far.

● Create and baseline the deployment diagram

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (255 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

Design Components

● Perform Use Case Design - Take each use can do the use case design (low level design) for each use
case under the umbrella of Architecture (high level design).

● Design Subsystems

● Update VOPC of each use case. Create class diagrams to present significant - static view of each use
case (Hint: 1 class diagram showing only the participating entity classes, the class diagram showing
only boundary and controller classes etc.)

● Design the classes further: Identify the oportunity of re-use. Refactor classes that are identified.
Refine classes to such an extent that you can start writing code.

Chapter: 3 - The Course Registration System

The Problem Statement

Problem Statement

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (256 of 258)12/6/2010 2:00:24 AM


Amit Kr. Balyan

● The Problem Statement

As the head of information systems for Wylie College you are tasked with developing a new student
registration system. The college would like a new client-server system to replace its much older
system developed around mainframe technology. The new system will allow students to register for
courses and view report cards from personal computers attached to the campus LAN. Professors will
be able to access the system to sign up to teach courses as well as record grades.

Due to a decrease in federal funding the college cannot afford to replace the entire system at once.
The college will keep the existing course catalog database where all course information is
maintained. This database is an Ingress relational database running on a DEC VAX. Fortunately the
college has invested in an open SQL interface that allows access to this database from college’s Unix
servers. The legacy system performance is rather poor, so the new system must insure that access to
the data on the legacy system occurs in a timely manner. The new system will access course
information from the legacy database but will not update it. The registrar’s office will continue to
maintain course information through another system.

At the beginning of each semester students may request a course catalogue containing a list of course
offerings for the semester. Information about each course, such as professor, department, and
prerequisites will be included to help students make informed decisions.

The new system will allow students to select four course offerings for the coming semester. In
addition, each student will indicate two alternative choices in case the student cannot be assigned to a
primary selection. Course offerings will have a maximum of ten students and a minimum of three
students. A course offering with fewer than three students will be canceled. For each semester, there
is a period of time that students can change their schedule. Students must be able to access the
system during this time to add or drop courses. Once the registration process is completed for a
student, the registration system sends information to the billing system so the student can be billed
for the semester. If a course fills up during the actual registration process, the student must be
notified of the change before submitting the schedule for processing.

At the end of the semester, the student will be able to access the system to view an electronic report
card. Since student grades are sensitive information, the system must employ extra security measures
file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (257 of 258)12/6/2010 2:00:24 AM
Amit Kr. Balyan

to prevent unauthorized access.

Professors must be able to access the on-line system to indicate which courses they will be teaching.
They will also need to see which students signed up for their course offerings. In addition, the
professors will be able to record the grades for the students in each class.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (258 of 258)12/6/2010 2:00:24 AM

Das könnte Ihnen auch gefallen