• No results found

CoreJava_JSP_Servlet_Struts_EJB

N/A
N/A
Protected

Academic year: 2021

Share "CoreJava_JSP_Servlet_Struts_EJB"

Copied!
258
0
0

Loading.... (view fulltext now)

Full text

(1)

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

(2)

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

(3)

● 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

(4)

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

(5)

● 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

(6)

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

(7)

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

(8)

● 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

(9)

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

(10)

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

(11)

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

(12)

● 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

(13)

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

(14)

}

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 {

(15)

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

(16)

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

(17)

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

} }

(18)

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

(19)

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

(20)

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.

(21)

● 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

(22)

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

(23)

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

(24)

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.

(25)

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

(26)

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.

(27)

● 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

(28)

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.

(29)

● 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

(30)

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

(31)

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

(32)

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

(33)

● 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

(34)

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

(35)

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

(36)

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

(37)

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

(38)

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

(39)

● 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

(40)

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

(41)

● 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

(42)

● 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

(43)

● 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

(44)

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

(45)

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

(46)

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

(47)

}

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

(48)

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

(49)

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

(50)

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

(51)

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

(52)

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 {

(53)

}

● 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

(54)

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.

(55)

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("###,###.##");

(56)

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.

(57)

● 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

(58)

● 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

(59)

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

(60)

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

(61)

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

}

(62)

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

(63)

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

}

(64)

}

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

} }

(65)

● 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

References

Related documents

When transfecting HEK 293T cells with either “mIFP-P2A-mNG2(full)” or “mIFP- P2A-mNG211SpyCatcher and mNGX1-10 (X represent 2, 3A or 3K)”, we observed both mNG31-10

I argue that positive global coverage of Jamaica’s outstanding brand achievements in sports, music and as a premier tourism destination, is being negated by its rival brands –

The optimization goal is to compute routes (starting at the depot, visiting the locations and finishing at the depot) for all the vehicles in the given time horizon, which minimize

I problematize three family images associated with the design and implementation of housing projects: the bureaucratic family, envisaged by policymakers as conflating with a model

• Based on intention to treat, VRET achieves more rapid responses, and higher response rates, than imaginal exposure for PTSD. • Combination VRET with pharmacotherapy has

The federal grant of authority to State and local governments to franchise cable systems does not include cable systems that serve subscribers without “using” any public

○ If BP elevated, think primary aldosteronism, Cushing’s, renal artery stenosis, ○ If BP normal, think hypomagnesemia, severe hypoK, Bartter’s, NaHCO3,

Equilibrium moisture content is the limiting moisture to which a given material can be dried under specific conditions of air temperature and humidity...