Y23 Aoop Notes
Y23 Aoop Notes
( AOOP - R/A/E )
Lecture Notes
Prepared By
Dr MSR PRASAD
SEC-11 Adv
SYLLABUS
CO-1
1. Design Patterns
Creational Patterns
Structural Patterns
Behavioral Patterns
SOLID Principles
Code Smells
Refactoring Techniques
CO-2
Introduction to Generics, Usage of Generics with Interfaces, Building Stacks, Queues, and
Priority Queues
Introduction to Multithreading and Parallel Programming, Thread Concepts & States, Creating
Tasks & Threads, Thread Classes, Thread Pools, Thread Synchronization & Locks, Cooperation
Among Threads, Case Study: Producer/Consumer, Blocking Queues, Semaphores, Deadlock
Avoidance, Synchronized Collections & Parallel Programming
CO-4
JDBC: API, Components, Architecture (2-Tier & 3-Tier), Drivers & Their Types, Packages for JDBC
Connection, Steps to Connect to Databases (PostgreSQL)
7. Servlets
Overview, Life Cycle of a Servlet, Attributes in Servlets, Interaction Between Client & Servlet,
Servlet Demo Application Development with Sessions
Overview & Advantages Over Servlets, Features and Syntax, Life Cycle of JSP, Environmental
Setup for JSP, Interaction Between Client, JSP & Server, JSP Demo Application Development
CO - 1
SHORT ANSWER QUESTIONS ( from CO-1 )
1. Types of inheritance
Answer:
a) multilevel b) multiple c) Hierarchical d) hybrid inheritance
Answer:
The observer design pattern is a behavioral design pattern that's useful when you
want to be notified of changes to an object's state. In this pattern, the object being
monitored is called the subject, and the object that monitors it is called the observer.
It supports the principle of loose coupling between objects that interact with each
other. It allows sending data to other objects effectively without any change in the
Subject or Observer classes. Observers can be added/removed at any point in time.
the strategy design pattern is a behavioral pattern that allows for the selection of an
algorithm during runtime. It provides flexibility and reusability by enabling the
calling code to choose from a set of algorithms instead of implementing a single
one.
It allows you to define a family of algorithms, encapsulate each one, and make them
interchangeable. It enables you to select and use an algorithm at runtime without
tightly coupling the client code to a specific implementation.
Implementation comments - The target audience is the developers that work on the
codebase.
Variables are used to represent data items in program. Variables are declared with
data types.
Eg . int marks;
boolean flag;
a) length
b) begin with small letter or underscore
c) special characters used
Class methods: they are static methods called by its class or by any object.
Instance method : they are non static methods , called by only object of the class.
Eg.
Class Hamper{
Static void show(){
}
Void display(){
}
Public static void main(String[] args){
Hamper h1 = new Hamper();
Hamper. Show(); // static method call
h1.dispaly(); // non static method call
}
}
LONG ANSWER QUESTIONS ( from CO-1 )
class DemoInh1{
public static void main(String[] args){
Animal aa = new Animal();
Human hh = new Human();
Monkey mm = new Monkey();
aa.eat();
aa.sleep();
mm.eat();
mm.jump();
hh.study();
hh.eat();
hh.sleep();
}
}
Answer:
Method Overriding: redefining a method from its super class. method overriding,
is an example of runtime polymorphism where as method over loading is the
example for compile time polymorphism.
Program:
class Monkey implements Animal{
public void eat(){
System.out.println("Monkeys eat vegitarian food");
}
public void sleep(){
System.out.println("Monkeys sleep on trees");
}
void jump(){
System.out.println("Monkeys jumps from tree to tree");
}
}
mm.eat();
mm.jump();
hh.study();
hh.eat();
hh.sleep();
}
}
Program:
abstract class Car {
abstract void steering();
abstract void breaking();
}
Class Maruthi extends Car{
@override
void steering(){
System.out.println(“ steering helps in turning the car
towards right and left”);
}
void breaking(){
System.out.println(“ breaks helps in slow down/stopping
the car”);
}
}
Class Demo{
Public static void main(String[] args){
Car c1 = new Maruthi();
c1. Steering();
c1.breaking();
}
}
Program:
abstract class Brazo {
abstract void callMe();
}
Class Carzo extends Brazo{
@override
void callMe(){
System.out.println(“ overriding callMe method from Brazo
calss”);
}
}
Class Demo{
Public static void main(String[] args){
Brazo b1 = new Carzo();
b1. callMe();
}
}
Program:
interface Animal {
void eat();
void sleep();
}
class DemoInh1{
public static void main(String[] args){
Human hh = new Human();
Monkey mm = new Monkey();
mm.eat();
mm.jump();
hh.study();
hh.eat();
hh.sleep();
}
}
6. Interface - Example program -2
Answer:
overridden methods of interface are public only, demonstration of the statement is
the following statement.
Program :
interface One {
void callMe();
}
void show(){
System.out.println(" Today is Sunny day ");
}
}
class DemoIntf1 {
public static void main(String[] args){
IntImpl if1 = new IntImpl();
if1.callMe();
if1.show();
}
}
7. Interface –Example program -3 ( Extends key word)
Answer:
Interfaces can be extended, as they follow inheritance of OOP concept.
Program :
interface One {
void callMe();
}
interface Two extends One {
void callMeToo();
}
// concrete class
class IntImpl implements Two {
public void callMe(){
System.out.println("callme: output");
}
public void callMeToo(){
System.out.println("callmeToo: output");
}
void show(){
System.out.println(" Today is wednesday");
}
}
class DemoIntf3 {
public static void main(String[] args){
IntImpl if1 = new IntImpl();
if1.callMe();
if1.callMeToo();
if1.show();
}
}
Program :
interface One{
void callMe();
}
class Hello{
void greet(){
System.out.println("Hello world");
}
}
class DemoIntf5{
public static void main(String[] args){
HelloOne ho1 = new HelloOne();
ho1.callMe();
ho1.greet();
ho1.show();
}
}
1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can have static methods, Interface can't have static methods, main
main method and constructor. method or constructor.
5) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Important points:
1. Private default constructor
2. Static object
3. Static method to return the object to the caller.
4. Number of utility methods to be used by the object
Program :
class Hello{
private Hello(){
}
static Hello obj = new Hello();
void show(){
System.out.println("Hello World");
}
}
class DemoSing1 {
public static void main(String[] args){
Hello h1 = Hello.getObject();
h1.show();
}
}
The pattern encapsulates object creation logic in a separate class, making the code
more flexible and maintainable. It also promotes loose coupling by eliminating the
need to bind application-specific classes into the code. This means the code only
interacts with the abstract class or resultant interface, so it can work with any
classes that extend or implement that interface.
Program:
import java.util.Scanner;
interface Shape{
void draw();
}
class ShapeFactory {
Shape getShape(int x){
if (x==1)
return new Circle();
else if(x==2)
return new Square();
else if(x==3)
return new Rectangle();
else
return null;
}
}
class DemoFact1 {
public static void main(String[] args){
Shape sh;
int x;
ShapeFactory shft= new ShapeFactory();
Scanner in = new Scanner(System.in);
System.out.println("Enter 1/2/3 for circle/square/rect
:");
x=in.nextInt();
sh= shft.getShape(x);
sh.draw();
}
}
class BankFactory {
Service getService(int x){
if (x==1)
return new SBI();
else if(x==2)
return new HDFC();
else if(x==3)
return new ICICI();
else return null;
}
}
class FactoryDemo{
public static void main(String[] args){
Service sh;
int bank;
Scanner in = new Scanner(System.in);
System.out.println(" Enter 1/2/3 for SBI/HDFC/ICICI
banks”);
bank= in.nextInt();
BankFactory bf = new BankFactory();
sh= bf.getService(bank);
sh.loanPayment();
}
}
Factory Method Pattern allows the sub-classes to choose the type of objects to
create. It promotes the loose-coupling by eliminating the need to bind application-
specific classes into the code.
Abstract Factory design – block diagram
Program:
interface Shape{
void draw();
}
class FactoryProducer{
static AbsFactory getFactory(int x){
if (x==1)
return new ShapeFactory();
else if (x==2)
return new RoundedShapeFactory();
else return null;
}
}
class AbsFactDemo1{
public static void main(String[] args){
AbsFactory abf;
Shape sh;
abf = FactoryProducer.getFactory(2);
sh= abf.getShape(2);
sh.draw();
}
}
Program :
// Agrigation program – object as a instance variable (through constructor)
class Address {
String d_no;
String city;
void show_details(){
System.out.println("Door no -> "+d_no);
System.out.println("city -> "+ city);
}
}
class Employee {
String name;
String emp_no;
Address ad;
void show_details(){
ad.show_details();
System.out.println("name -> "+ name);
System.out.println("emp no -> "+emp_no);
}
}
class Aggregation1{
public static void main(String[] args){
Aggregation:
Class contains object of another class as it’s instance variable or as a local variable
so that all the members of the class can be accessed.
Advantages:
Structural patterns explain how to assemble objects and classes into larger
structures while keeping these structures flexible and efficient. These patterns help
make it easier to identify a simple way to realize relationships between entities.
SpCrikPlayer class is acting like a connector to get methods from both of the
interfaces.
Program :
interface Cricket{
void playCricket();
}
interface Hockey{
void playHockey();
}
class CricPlayer implements Cricket{
public void playCricket(){
System.out.println(" playing cricket is my passion");
}
}
class AdoptDemo1 {
public static void main(String[] args){
Cricket ck, sck;
Hockey hk;
hk= new HockPlayer();
hk.playHockey();
ck = new CricPlayer();
sck = new SpCrikPlayer();
ck.playCricket();
sck.playCricket();
}
}
interface Duck{
void kwack();
}
class AdoptDemo2 {
public static void main(String[] raga){
Parrot p1;
Duck d1;
}
}
interface Deco{
void display();
}
class BridgeDemo1{
public static void main(String[] msr){
Shape sh;
Deco dc;
sh = new Rectangle();
dc = new Deco1(sh);
dc.display();
}
}
20. Bridge design Pattern (Example-2)
Answer:
The Bridge design pattern separates an abstraction from its implementation,
allowing both to change independently. This structural pattern increases flexibility
and maintainability in complex systems.
Program:
interface Bank{
void show();
}
interface Account{
void openAcc();
}
class BridgeDemo2{
public static void main(String[] msr){
Bank bnk;
Account acc;
acc = new SavingAcc();
bnk = new Axis(acc);
bnk.show();
The Facade pattern offers the following benefits: It shields clients from subsystem
components, thereby reducing the number of objects that clients deal with and
making the subsystem easier to use. It promotes weak coupling between the
subsystem and its clients. Often the components in a subsystem are strongly
coupled.
Program:
void draw();
System.out.println(" I am a Rectangle");
System.out.println(" I am a square");
System.out.println(" I am a circle");
}
class ShapeMaker {
public ShapeMaker() {
void drawCircle(){
circle.draw();
void drawRectangle(){
rectangle.draw();
void drawSquare(){
square.draw();
}
class DemoFacadePattern1 {
shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
interface MobilePhone {
void modelNo();
void price();
}
ShopKeeper(){
iphone= new Iphone();
samsung=new Samsung();
blackberry=new Blackberry();
}
void iphoneSale(){
iphone.modelNo();
iphone.price();
}
void samsungSale(){
samsung.modelNo();
samsung.price();
}
void blackberrySale(){
blackberry.modelNo();
blackberry.price();
}
}
class DemoFacade2 {
public static void main(String args[]) {
sk.iphoneSale();
sk.samsungSale();
sk.blackberrySale();
}
}
Advantages:
Model diagram:
24. Template design pattern for “making Tea” – Example program
Program:
abstract class Drink{
abstract void boilWater();
abstract void addTeaPowder();
abstract void addSugar();
abstract void serveTea();
void addTeaPowder(){
System.out.println("add TEA powder and milk ");
}
void addSugar(){
System.out.println("add sugar as per your taste ");
}
void serveTea(){
System.out.println("Serve Tea in cups");
}
}
class TempDemo2{
public static void main(String[] args){
Drink gg;
gg= new Tea();
gg.makeTea();
}
}
hasNext() method will check whether next element is there in the list or not,
accordingly returns true if available otherwise returns false.
next() method will return the next element from the list if available.
Both these methods are made available through a interface, any class implementing
this interface can use both of these methods.
The implemented class must take care of objects of any type may be String or any
user defined type.
interface Iterator {
public boolean hasNext();
public Object next();
}
interface Iterator {
Object next();
boolean hasNext();
}
class IteratorDemo1{
public static void main(String[] msr){
NameIterator ni = new NameIterator();
while(ni.hasNext())
System.out.println((String) ni.next());
}
}
interface Iterator {
Object next();
boolean hasNext();
}
class IteratorDemo2{
public static void main(String[] msr){
NumIterator ni = new NumIterator();
while(ni.hasNext())
System.out.println((Integer) ni.next());
}
}
28. Command Design Pattern (Example program-1)
Answer:
The Command design pattern is a behavioral pattern that transforms a request into a
stand-alone object. It focuses on separating the sender of a request from the
receiver.
class WatchSon{
void bringVeg(){
System.out.println(" brought vegitables");
}
}
class WatchMan{
WatchSon ws;
WatchMan(WatchSon ws1){
ws = ws1;
}
void bringVeg(){
ws.bringVeg();
}
}
class Husband{
WatchMan wm;
Husband(WatchMan wm1){
wm = wm1;
}
void bringVeg(){
wm.bringVeg();
}
}
class CommandDemo1{
public static void main(String[] msr){
WatchSon w1 = new WatchSon();
WatchMan w2 = new WatchMan(w1);
Husband w3 = new Husband(w2);
w3.bringVeg();
}
}
class Account {
void savings(){
System.out.println(" your savings account opened");
}
void current(){
System.out.println(" your current account opened");
}
}
class BankBazar{
Bank bk;
BankBazar( Bank bk1){
bk=bk1;
}
void service(int x){
bk.openAcc(x);
}
}
class CommandDemo2{
public static void main(String[] msr){
Account acc = new Account();
SBI sb = new SBI(acc);
BankBazar bz = new BankBazar(sb);
bz.service(2);
}
}
Program-1:
interface Mobile{
void model();
void price();
}
class SalesMan{
Mobile mb;
SalesMan(Mobile mb1){
mb=mb1;
void showDetails(){
mb.model();
mb.price();
class DepInj1{
Mobile mb;
mb = new Samsung();
sm.showDetails();
Program:
interface Shape{
void area(int x, int y);
class ShapeMaker{
Shape sh;
ShapeMaker(Shape sh1){
sh = sh1;
}
void ShapeArea(int x, int y){
sh.area(x,y);
class DepInj2{
sm.ShapeArea(5,10);
Program:
import java.util.Scanner;
interface DChain{
DChain chain;
chain = dc;
if (x>1) chain.dispense(x);
}
}
DChain chain;
chain = dc;
if (x>2) chain.dispense(x);
DChain chain;
chain = dc;
class DemoChainExams{
int n;
c1.setNextChain(c2);
c2.setNextChain(c3);
n= in.nextInt();
c1.dispense(n);
import java.util.Scanner;
interface DispenseChain {
DispenseChain chain;
chain=nextChain;
} else chain.dispense(cur);
}
class Rs20Dispenser implements DispenseChain{
DispenseChain chain;
chain=nextChain;
} else chain.dispense(cur);
DispenseChain chain;
class DemoChainATM {
c1.setNextChain(c2);
c2.setNextChain(c3);
while (true) {
int amount = 0;
amount = input.nextInt();
if (amount % 10 != 0) {
return;
c1.dispense(amount);
Simple:
Maintainable:
Testable:
Readable:
1. All the resources must be placed in the respective folders for pro use and
maintenance
2. Proper Naming : all variables, constants, class names, method names,
Enum names must follow the conventions used in the industry
3. Anatomy of java program : as per the industry standards
I am going to illustrate a java program for the above concepts of clean coding,
Program:
// clean code program
// method's long parameter list reduced
// Address data class, collection of variables
class Address{
int house_no;
int road_no;
String city;
// constructor for data class
Address(int h, int r, String c){
house_no = h;
road_no = r;
city = c;
}
}
// main class
class StudentX{
// this method is getting more data from address object
void show(String name, Address ad1){
System.out.println( name );
System.out.println( ad1.house_no );
System.out.println( ad1.road_no );
System.out.println( ad1.city );
}
// driver method
public static void main(String[] args){
Address ad = new Address(100, 22, "vja");
StudentX st1 = new StudentX();
st1.show("Rahul",ad);
}
}
Bloaters: Bloaters are code, methods and classes that have increased to such
gargantuan proportions that they are hard to work with. Usually these smells do not
crop up right away, rather they accumulate over time as the program evolves (and
especially when nobody makes an effort to eradicate them). Long Method, Large
Class, Primitive Obsession, Long Parameter List and Data Clumps are famous in
this category.
Object-Orientation Abusers: All these smells are incomplete or incorrect application
of object-oriented programming principles. Switch Statements, Temporary Field,
Refused Request and Alternative Classes with Different Interface are known as
object-orientation abusers code smells.
Change Preventers: These smells mean that if you need to change something in one
place in your code, you have to make many changes in other places too. Program
development becomes much more complicated and expensive as a result. Code
smells like Divergent Change, Shotgun Surgery and Parallel Inheritance Hierarchies
are in this category.
Couplers: All the smells in this group contribute to excessive coupling between
classes or show what happens if coupling is replaced by excessive delegation. Some
examples would be Feature Envy, Inappropriate Intimacy, Message Chains, Middle
Man and Incomplete Library Class
2. Long Method: A long method contains too many lines of code. Any code
with more than 25 lines of code should make you question. It could be solved
using refactoring techniques like changing expression into sub-expression,
complex codes into a new function in order to make a function or method a
small and easy to read without changing its functionality.
3. Long Parameter List: Any function with more parameters is obviously more
complex. One of the thumb rules is to use a maximum of 3 to 4 parameters in
a function.
4. Large Classes: A class contains many methods/lines of code/fields is
considered a code smell. Refactoring techniques could be done like, extract
class, extract subclass, extract interface, duplicate observed data.
5. Duplicate Code: When a code is repeated for more than two times, merge it
into a function or a method of the class. If the same code is found in two or
more classes, using the extract method we can refactor the code smell.
6. Dead Code: The code that is not being used. A function with no calls or the
condition that never occurs. Delete unused code and unnecessary files.
Program:
// clean code program
// method's long parameter list reduced
// Address data class, collection of variables
class Address{
int house_no;
int road_no;
String city;
// main class
class StudentX{
// driver method
public static void main(String[] args){
Address ad = new Address(100, 22, "vja");
StudentX st1 = new StudentX();
st1.show("Rahul",ad);
}
}
class Parent {
String name;
String ph;
Parent(){
}
void show(){
System.out.println(" name ="+ name);
System.out.println(" phone ="+ ph);
System.out.println(" branch ="+ branch);
System.out.println(" college ="+ clg);
}
}
class DemoLiskov{
public static void main(String[] args){
Parent obj = new Derived("Rahul","99999","CSE","KLEF");
// Liskov substitution goes here...
Derived doj = new Derived("Rani","88888","CSE","KLEF");
doj.show();
doj.display();
}
}
42. Dependency Inversion – program (clean coding)
Program:
class Parent {
Parent(){
}
void show(){
System.out.println("show method parent class");
}
}
class Derived extends Parent{
void show(){
System.out.println("show method child class");
}
void display(){
System.out.println("display method of child class");
}
}
class DemoDepInversion{
public static void main(String[] args){
//Parent obj = new Parent();
Derived obj = new Derived();
obj.show();
obj.display();
}
}
void hello(){
System.out.println(" Hello from one class");
}
}
void borrow(){
System.out.println(" borrow from Two class");
}
}
class InterfaceSegre{
public static void main(String[] args){
Iface1 oo;
oo = new One();
oo.show();
oo = new Two();
oo.show();
}
}
44. Usage of Data class – program ((clean coding)
Program:
class Data {
int x;
int y;
Data (int x1 , int y1){
x = x1;
y = y1;
}
}
class Compute{
Data dt;
Compute(Data dt1){
dt = dt1;
}
int sum(){
return dt.x + dt.y;
}
int subtract(){
return dt.x - dt.y;
}
}
class DataClass1{
public static void main(String[] msr){
Data dd = new Data(20,10);
Compute cp = new Compute(dd);
System.out.println("sum ="+ cp.sum());
System.out.println("difference ="+ cp.subtract());
}
}
45. Refactoring techniques - Example program.
Answer:
• Refactoring encompasses a number of specific code hygiene practices. When
it comes to eliminating code smells, however, there are three particularly
effective techniques: one that focuses on methods, another that focuses on the
method calls and a third that focuses on classes.
-------------------------------------
Program before refactoring:
-------------------------------------
class StudentY{
void show(String name, int house_no, int road_no, String
city){
System.out.println(name);
System.out.println(house_no);
System.out.println(road_no);
System.out.println(city);
}
// main class
class StudentX{
// driver method
public static void main(String[] args){
Address ad = new Address(100, 22, "vja");
StudentX st1 = new StudentX();
st1.show("Rahul",ad);
}
}
PrintHelloMethod(String name) {
this.name = name;
}
// normal method
public void print() {
System.out.println("Hello, " + name);
}
}
class Refactor2{
public static void main(String[] args){
PrintHelloMethod phm = new PrintHelloMethod("world");
phm.printHello();
}
}
// After refactoring
interface MyDelegate {
void doSomething();
}
class MyClass {
MyDelegate delegate;
MyClass() {
this.delegate = new MyDelegate();
}
public void doSomething() {
delegate.doSomething();
}
}
50. Remove MiddleMan - java example ( Refacoring )
Program:
// Normal way...
class Boss1 {
private Worker w1;
Boss1( Worker ww){
w1 = ww;
}
class Worker{
void doSomething(){
System.out.println(" brought 1 kg chillies");
}
}
class Refactor5 {
public static void main(String[] args){
Worker w10 = new Worker();
Boss1 bb1 = new Boss1(w10);
bb1.doSomething();
}
}
// refactored way...
class Boss1 {
public void doSomething() {
System.out.println(" brought 1 kg chillies");
}
}
class Refactor51 {
public static void main(String[] args){
Boss1 bb1 = new Boss1();
bb1.doSomething();
}
}
// After refactoring
abstract class Bird {
private String type;
@Override
public String getSpeed() {
return "average";
}
}
@Override
public String getSpeed() {
return (numberOfCoconuts > 2) ? "tired" : "average";
}
}
class NorwegianBlueParrot extends Bird {
private boolean isNailed;
private int voltage;
@Override
public String getSpeed() {
return (isNailed) ? "0" : "beautiful";
}
}
// Usage example
Bird bird = new EuropeanSwallow();
System.out.println(bird.getSpeed()); // "average"
Generics does not work with primitive types (int, float, char, etc).
Syntax :
public int compareTo(Object obj): It is used to compare the current object with
the specified object. It returns
o positive integer, if the current object is greater than the specified object.
o negative integer, if the current object is less than the specified object.
o zero, if the current object is equal to the specified object.
4. HashSet – Explanation
Answer:
HashSet is commonly used if we have to access elements randomly. It is because
elements in a hash table are accessed using hash codes. The hashcode of an
element is a unique identity that helps to identify the element in a hash table.
HashSet cannot contain duplicate elements. Hence, each hash set element has a
unique hashcode.
Add(), remove(), size(), addAll(), retainAll(), removeAll(), clear() are the main
Collection framework classes are used to store and manage variety of Objects.
6. Map - Explanation
Answer:
Map interface is implemented by Hashmap, LinkedHashMap and TreeMap
A map contains values on the basis of key, i.e. key and value pair. Each key and
value pair is known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a
key.
put(), remove(), getKey(), getValue(), entrySet() are the major methods of the Map.
Public Boolean hasNext() – returns true if element/s are available otherwise false.
Public void remove() – last element returned by the iterator will be removed
LONG ANSWER QUESTIONS ( from CO-2 )
Java Generics allows us to create a single class, interface, and method that can be
used with different types of data (objects).
Generics does not work with primitive types (int, float, char, etc).
Advantages:
Type Parameters :
The type parameters naming conventions are important to learn generics thoroughly.
The common type parameters are
Program : whether the given number is Zero/Non-zero (Integer and Double types)
class Gen10{
int i;
double d;
String s;
if( (Integer)data1 == 0)
System.out.println("ZERO");
else
System.out.println("non ZERO");
if( (Double)data1 == 0)
System.out.println("ZERO");
else
System.out.println("non ZERO");
g1.<Integer>check(200);
g1.<Integer>check(0);
g1.<Double>check(12.6);
g1.<Double>check(0.0);
}
}
Program: whether the given number is even/odd (Integer and Double types)
T data1;
Gen10(T data1){
this.data1 = data1;
void check(){
int i;
double d;
String s;
if( (Integer)data1 == 0)
System.out.println("ZERO");
else
System.out.println("non ZERO");
if( (Double)data1 == 0)
System.out.println("ZERO");
else
System.out.println("non ZERO");
g1.check();
g2.check();
G3.check();
g4.check();
class Even {
<T> void checkOddEven (T number) {
if (number instanceof Integer) {
if ((Integer)number % 2 == 0)
System.out.println((Integer)number + "
is even number");
else
System.out.println((Integer)number + "
is odd number");
} else
if (number instanceof Double) {
if ((Double)number % 2 == 0)
System.out.println((Double)number + "
is even number");
else
System.out.println((Double)number + "
is odd number");
}
}
}
public class EvenDemo {
public static void main(String[] args) {
Even e = new Even();
e.<Integer>checkOddEven(11);
e.<Double> checkOddEven(13.0);
}
}
class CompDemo{
public static void main(String[] args){
Answer:
Comparable Comparator
2) Comparable affects the original class, Comparator doesn't affect the original
i.e., the actual class is modified. class, i.e., the actual class is not
modified.
6. Clonable Interface
Program:
class Student implements Cloneable {
int id;
String name;
Student(int id, String name){
this.id = id;
this.name = name;
}
@Override
Public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
class ClonableInterface{
public static void main(String[] args) {
Student s = new Student(101, "Rahul");
System.out.println(s.id + " " + s.name);
try {
Student s1 = (Student) s.clone();
System.out.println(s1.id + " " + s1.name);
}catch (Exception e) {
System.out.println(e);
}
}
}
numbers.set(3,”Malaysia” );
System.out.println("size"+ countries.size());
System.out.println(" ");
countries.remove(2);
Iterator itr= countries.iterator();
while(itr.hasNext()) {
System.out.print(itr.next());
System.out.print(" , ");
}
System.out.println("size"+ countries.size());
}
}
import java.util.Stack;
public class Stack1
{
public static void main(String[] args)
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);
result = stk.empty();
System.out.println("Is the stack empty? " + result);
System.out.println("top of the stack ="+ stk.pop());
}
}
class PriorityQueue1 {
public static void main(String[] args) {
// Create a PriorityQueue using the natural
ordering (ascending)
PriorityQueue<Integer> pq = new
PriorityQueue<>();
import java.util.*;
class Set1 {
public static void main(String[] klu){
System.out.println(list);
System.out.println(list);
a.addAll(Arrays.asList(
new Integer[] { 1, 3, 2, 4, 8, 9, 0 }));
b.addAll(Arrays.asList(
new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 }));
Set<Integer> union = new LinkedHashSet<>(a);
union.addAll(b);
System.out.print("Union of the two Set");
System.out.println(union);
Map in Java is an interface available in java. util package and it stores the data in
key and value pairs. It does not allow duplicate keys.
TreeMap, HashMap and LinkedHashMap are the classes that are implementing
Map interface.
The map() operation in Java 8 streams transforms the elements of a collection based
on a specified function. It takes a Function<T, R> as input, where T is the type of
the input element and R is the type of the output element.
Changing Element:
hm1.put(new Integer(2), "For");
Removing Elements:
hm1.remove(new Integer(4));
// removing an element
mp.remove("four");
// load elements
mp.put(5,"India");
mp.put(2,"Srilanka");
mp.put(3,"USA");
mp.put(4,"Russia");
mp.put(1,"China");
System.out.println(" No of element in the map (before) :"+mp.size());
// removing an element
mp.remove(4);
interface Eatable{
void eat();
}
class FuncInterface1 {
public static void main(String[] args){
Eatable eb = new Eatable(){
public void eat(){
System.out.println(" eating .. fruits");
System.out.println(" eating .. sweets");
}
};
eb.eat();
}
}
class Lamba2 {
public static void main(String[] args){
Eatable eb =(String a, String b)->{
System.out.println(" eating .. "+a);
System.out.println(" eating .. "+b);
};
eb.eat("fruits","sweets");
}
}
20. Nested classes
a) Inner class : The purpose of nested classes is to group classes that belong
together, which makes your code more readable and maintainable.
class Outer
{
int outer_x=100;
void test()
{
Inner inner = new Inner();
inner.display();
inner.showy();
}
class Inner
{
int y=10;
void display()
{
System.out.println("dispaly: outer_x =" + outer_x);
}
void showy()
{
System.out.println(y);
}
}
}
class InnerClass
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}
b) Local class : A class i.e., created inside a method, is called local inner class in java. Local
Inner Classes are the inner classes that are defined inside a block. Generally, this block is a
method body.
Program 1:
class JLInner1{
private int data=30;
void display(){
class Local{
void msg(){
System.out.println(data);
}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
JLInner1 obj=new JLInner1();
obj.display();
}
}
Program 2:
class JLInner2{
private int data=30;//instance variable
void display(){
int value=50;
class Local{
void msg(){
System.out.println("local variable: "+value);
System.out.println("instance variable: "+data);
}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
JLInner2 obj=new JLInner2();
obj.display();
}
}
c) Anonymous class : a class that has no name is known as an anonymous inner class in Java.
It should be used if you have to override a method of class or interface.
Program 1:
abstract class Person{
abstract void eat();
}
class JAInner1{
public static void main(String args[]){
Person p=new Person(){
void eat(){
System.out.println("nice fruits");
}
};
p.eat();
}
}
Program 2:
interface Eatable{
void eat();
}
class JAInner2{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){
System.out.println("nice fruits");
}
};
e.eat();
}
}
CO – 3
SHORT ANSWER QUESTIONS ( from CO-3 )
Process-based Thread-based
Multitasking Multitasking
Address space Each process have its own Threads share the same
address in memory i.e. address space.
each process allocates
separate memory area.
2. Implements Runnable
Class Thr2 implements Runnable{
Public void run(){
}
}
Run() is the main method of java thread program, thread behavior declared in this
method. After creating the thread object,
Thread o1 = new Thread();
o1.start(); Would call the run() method.
The sleep() method of Thread class is used to sleep a thread for the specified
amount of time.
Eg:
public static void sleep(long miliseconds) throws InterruptedException
Each thread have a priority. Priorities are represented by a number between 1 and
10. In most cases, thread schedular schedules the threads according to their priority
(known as preemptive scheduling). But it is not guaranteed because it depends on
JVM specification that which scheduling it chooses.
Eg:
Thread t1 = new Thread();
t1.setPriority(6);
Int g = t1.getPriority();
the above two methods available.
Eg. synchronized(this){
}
11. Differentiate synchronized block and method
Answer:
t1.start();
t2.start();
}
}
4. Java program- thread1 is derived from Thread class which should produce
numbers from 1 to 10, thread2 is drawn from Runnable interface to
produce numbers from 10 to 1. Demo class to output both threads created.
Answer:
classs MyThr1 extends Thread {
public void run(){
try{
for(int I = 1; i<=10; i++)
Thread.sleep();
System.out.println(i);
} catch(Exception e){
System.out.println(e);
}
}
}
Class MyThr2 implements Runnable {
public void run(){
try{
for(int i = 10; i>=1; i--)
Thread.sleep();
System.out.println(i);
} catch(Exception e){
System.out.println(e);
}
}
}
Class Demo {
public static void main(String[] args){
MyThr1 t1 = new MyThr1();
MyThr2 m2 = new MyThr2();
Thread t2 = new Thread(m2);
t1.start();
t2.start();
}
}
void evenOdd(){
int[] ar = {10,23,45,20,24,99};
for(int i=0; i<ar.length; i++){
if ((ar[i] % 2) == 0)
System.out.println(ar[i]+ " "+ " is Even number");
else
System.out.println(ar[i]+ " "+ " is ODD number");
}
}
}
t1.start();
t2.start();
System.out.println(" t1 is existing? "+ t1.isAlive());
System.out.println(" t2 is existing? "+ t1.isAlive());
try{
t1.join();
t2.join();
}catch(Exception e){
System.out.println(e);
}
6. Develop a java program, your program should have two threads with two
different purposes to demonstrate start(), run(), sleep(), getPriority(),
setPriority() methods.
( Count of even/odd numbers and count of zeroes/Non-zeroes are possible in this
program )
Answer:
class Thr1 extends Thread {
String str;
Thr1( String str){
this.str =str;
}
t1.start();
t2.start();
t3.start();
t1.setPriority(9);
t3.setPriority(2);
System.out.println(t1.getName() + " priority : " +
t1.getPriority());
System.out.println(t3.getName() + " priority : " +
t3.getPriority());
try{
t1.join();
t2.join();
t3.java();
}catch(Exception er){
System.out.println(er);
}
System.out.println(" AFTER calling join() method");
System.out.println(t1.getName() + " is exists? " +
t1.isAlive());
System.out.println(t2.getName() + " is exists? " +
t2.isAlive());
System.out.println(t3.getName() + " is exists? " +
t3.isAlive());
}
}
7. Describe synchronization in java threads, write a java program that
included a synchronized block in a particular method for a genuine reason.
Answer:
Synchronization in Java is the capability to control the access of multiple threads to
any shared resource.
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. It can be achieved by using the following three ways:
Program:
class Bangee{
void doit(String str){
// synchronized block
synchronized(this){
try{
System.out.print("[ "+str);
Thread.sleep(1000);
}
catch(Exception e){
System.out.println(e);
}
System.out.println("]");
}
}
}
class TsyncDemo1{
public static void main(String[] args){
Bangee bg1 = new Bangee();
Thr1 tt1 = new Thr1(bg1,"raja");
Thr1 tt2 = new Thr1(bg1,"Kaja");
Thread t1 = new Thread(tt1);
Thread t2 = new Thread(tt2);
t1.start();
t2.start();
}
}
8. A java program to implement synchronized method
Answer:
class Bangee{
// synchronized method…
synchronized void doit(String str){
try{
System.out.print("[ "+str);
Thread.sleep(1000);
}
catch(Exception e){
System.out.println(e);
}
System.out.println("]");
}
}
class TableX{
Lock qLock = new ReentrantLock();
void printX(int n){
qLock.lock();
try{
for (int i= 1; i<=10; i++){
System.out.println( n +" X "+ i +" = "+n*i);
Thread.sleep(1000);
}
}catch(Exception e){
System.out.println(e);
}
qLock.unlock();
}
}
class Thr12Lock1{
public static void main(String[] args){
TableX tx = new TableX();
ThrTable t1 = new ThrTable(tx, 5);
ThrTable t2 = new ThrTable(tx, 10);
t1.start();
t2.start();
}
}
Program 2:
// Lock and ReentrantLock - synchronization program...
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class StrX{
Lock qLock = new ReentrantLock();
void printX(String str){
qLock.lock();
try{
System.out.print("[ "+ str);
Thread.sleep(500);
System.out.println(" ]");
}catch(Exception e){
System.out.println(e);
}finally{
qLock.unlock();
}
}
}
class ThrStr extends Thread{
StrX sx;
String s;
ThrStr( StrX sx1, String s1){
sx = sx1;
s = s1;
}
class Thr13Lock2{
public static void main(String[] args){
class Thr14Semaphore1{
public static void main(String[] args){
TableX tx = new TableX();
ThrTable t1 = new ThrTable(tx, 5);
ThrTable t2 = new ThrTable(tx, 10);
t1.start();
t2.start();
}
}
Program 2:
import java.util.concurrent.*;
// Thread coodination - with semaphore
class StrX{
Semaphore sem = new Semaphore(1);
void printX(String str){
try{
sem.acquire();
System.out.print("[ "+ str);
Thread.sleep(500);
System.out.println(" ]");
}catch(Exception e){
System.out.println(e);
}
sem.release();
}
}
class Thr15Semaphore2{
public static void main(String[] args){
Wait() - The wait() method causes the current thread to wait indefinitely until
another thread either invokes notify() for this object .
Notify() - For all threads waiting on this object’s monitor (by using any one of
the wait() methods), the method notify() notifies any one of them to wake up
arbitrarily.
Program:
// wait() and notify() demo program...
class Data {
boolean sig = false;
synchronized void part1() {
System.out.println("Welcome to KLEF");
sig = true;
notify();
}
synchronized void part2() {
try {
if (!sig)
wait();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Join in any one Tech
club");
}
}
class Thr16WtNtf1{
public static void main(String[] args) {
Data dt = new Data();
}
}
Program 2:
class Bank{
boolean sig = false;
class Thr17WtNtf2{
public static void main(String[] args){
Bank bkk = new Bank();
Thr1 t1 = new Thr1(bkk);
Thr2 t2 = new Thr2(bkk);
t2.start();
t1.start();
}
}
12. Deadlock program (situation how deadlock occurs)
Program:
class BookTkt extends Thread {
Object train, comp;
BookTkt(Object t1, Object c1){
train = t1;
comp=c1;
}
class Thr19DeadLock{
public static void main(String[] args){
Object train = new Object();
Object compartment = new Object();
BookTkt obj1 = new BookTkt(train, compartment);
CancelTkt obj2 = new CancelTkt(train, compartment);
class Thr20DeadLockAvoid{
public static void main(String[] args){
Object train = new Object();
Object compartment = new Object();
BookTkt obj1 = new BookTkt(train, compartment);
CancelTkt obj2 = new CancelTkt(train, compartment);
n=n1;
System.out.println("put= "+n);
sig=true;
notify();
}
class Thr18ProdConsumer {
public static void main(String args[]) {
Data dt= new Data();
Producer p1 = new Producer(dt);
Consumer c1 = new Consumer(dt);
p1.start();
c1.start();
}
}
CO – 4
SHORT ANSWER QUESTIONS ( from CO-4 )
From the above architecture, JDBC Driver manager and JDBC Driver plays a
major role in making JDBC application programs.
Driver: This interface handles the communications with the database server. You
will interact directly with Driver objects very rarely. Instead, you use
DriverManager objects, which manages objects of this type. It also abstracts the
details associated with working with Driver objects.
5. Explain JDBC ResultSet?
Answer :
ResultSet: These objects hold data retrieved from a database after you execute an
SQL query using Statement objects. It acts as an iterator to allow you to move
through its data.
Eg.
ResultSet rs=stmt.executeQuery("select PCOST, PNAME from product");
Where stmt is the Statement class object.
Answer:
Six steps of JDBC application development with Oacle/any database
Import the packages: Requires that you include the packages containing the
JDBC classes needed for database programming. Most often, using import
java.sql.* will suffice.
Register the JDBC driver: Requires that you initialize a driver so you can
open a communication channel with the database.
7. Explain HTTP ?
Answer:
The Hyper Text Transfer Protocol (HTTP) is the foundation of the World
Wide Web, and is used to load webpages using hypertext links. HTTP is an
application layer protocol designed to transfer information between
networked devices and runs on top of other layers of the network protocol
stack.
Multiple users can access the same version of an application. Users don't
need to install the app. Users can access the app through various platforms
such as a desktop, laptop or mobile. Users can access the app through
multiple browsers.
9. Give any two examples of web client?
Answer:
Apache Tomcat
Microsoft IIS
Oracle IPlanet
are the few web servers examples.
11.Define Servlet ?
Answer:
a servlet is a Java programming language class that extends the capabilities
of web server applications. Servlets can respond to any type of request, and
are commonly used to design and deploy dynamic web pages.
HTML is statically typed and is parsed at browser i.e. client side and hence
would be evaluated at client side which exposes your page and would allow
client to do several manipulations. But JSPs are server side and hence are
more secure and safe as client can only access html in last.
13.List the phases in Lifecycle of a JSP Page.
Answer:
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}
Answer:
JDBC driver implementations vary because of the wide variety of operating systems
and hardware platforms in which Java operates. Sun has divided the implementation
types into four categories, Types 1, 2, 3, and 4, which is explained below −
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each
client machine. Using ODBC, requires configuring on your system a Data Source
Name (DSN) that represents the target database.
When Java first came out, this was a useful driver because most databases only
supported ODBC access but now this type of driver is recommended only for
experimental use or when no other alternative is available.
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind
of driver.
Type 2: JDBC-Native API
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls,
which are unique to the database. These drivers are typically provided by the
database vendors and used in the same manner as the JDBC-ODBC Bridge. The
vendor-specific driver must be installed on each client machine.
This kind of driver is extremely flexible, since it requires no code installed on the
client and a single driver can actually provide access to multiple databases.
You can think of the application server as a JDBC "proxy," meaning that it makes
calls for the client application. As a result, you need some knowledge of the
application server's configuration in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the
database, understanding the nuances will prove helpful.
Type 4: 100% Pure Java
This kind of driver is extremely flexible, you don't need to install special software
on the client or server. Further, these drivers can be downloaded dynamically.
Program :
import java.sql.*;
class DBCRUD_PRODUCT{
public static void main(String args[])throws
Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost
:1521:xe","system","admin");
// code segment to verify Connection is
successfully established or not
if( con != null )
System.out.println("connected");
else
System.out.println("not connected");
int n = stmt.executeUpdate(s1);
System.out.println("Records effected:" + n);
con.commit();
// use of reultset to get all rows from
the product table
ResultSet rs=stmt.executeQuery("select
* from product");
// use of reultset to get all rows from the
product table with a condition
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost
:1521:xe","system","admin");
// code segment to verify Connection is
successfully established or not
if( con != null )
System.out.println("connected");
else
System.out.println("not connected");
// Statement object code segment in this
program
Statement stmt = con.createStatement();
// depends on the question use the following strings
appropriately
// String s1="INSERT into EMPLOYEE
values(1118,'sundar’,33333.98)";
//String s1 = "DELETE FROM EMPLOYEE WHERE EID=
115";
String s1 = "UPDATE product SET ESAL =
44444.90 WHERE EID=1110";
int n = stmt.executeUpdate(s1);
System.out.println("Records effected:" + n);
con.commit();
// use of reultset to get all rows from
the product table
ResultSet rs=stmt.executeQuery("select
* from EMPLOYEE");
// use of reultset to get all rows from the
product table with a condition
}
}
6. Program to update the third record and delete the fourth record and finally
display available records using ResultSet object that uses SELECT sql
statement.
Answer :
PRODUCT table description:
PID – number(3) field
PNAME – varchar2(30) field
PCOST – number(5,2) field
Assuming there are 5 record available in the table with PIDs are 101, 102, 103, 104
and 105 sequentially .
Program :
import java.sql.*;
class DBCRUD_PRODUCT{
public static void main(String args[])throws
Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost
:1521:xe","system","admin");
// code segment to verify Connection is
successfully established or not
if( con != null )
System.out.println("connected");
else
System.out.println("not connected");
int n1 = stmt.executeUpdate(s1);
System.out.println("Records effected:" + n1);
con.commit();
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@local
host:1521:xe","system","admin");
Statement st =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@local
host:1521:xe","system","admin");
int i=pstmt.executeUpdate();
System.out.println(i+" records inserted");
}
}
Answer:
1. Life Cycle of a Servlet
1. Servlet class is loaded
2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked
The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:
Servlet Architecture
Execution of Servlets :
Properties of Servlets :
There are many differences between the Get and Post request. Let's see these
differences:
GET POST
1) In case of Get request, only limited amount of data can be In case of post request, large amount of data can
sent because data is sent in header. be sent because data is sent in body.
2) Get request is not secured because data is exposed in URL Post request is secured because data is not exposed
bar. in URL bar.
4) Get request is idempotent . It means second request will Post request is non-idempotent.
be ignored until response of first request is delivered
5) Get request is more efficient and used more than Post. Post request is less efficient and used less than
get.
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b> Hello servlet world </b>");
out.print("</body></html>");
}
public void destroy(){System.out.println("servlet is
destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-
1010";}
15. Web technology deals with many types of methodologies and technologies,
Java server pages is one among them. JSP adopts a particular process to make
the web page dynamic. Explain JSP processing with a neat diagram.
Answer:
JSP Architecture
JSP Processing
The following steps explain how the web server creates the Webpage using JSP −
As with a normal page, your browser sends an HTTP request to the web
server.
The web server recognizes that the HTTP request is for a JSP page and
forwards it to a JSP engine. This is done by using the URL or JSP page
which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet
content. This conversion is very simple in which all template text is
converted to println( ) statements and all JSP elements are converted to Java
code. This code implements the corresponding dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the
original request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML
format. The output is furthur passed on to the web server by the servlet
engine inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of
static HTML content.
Finally, the web browser handles the dynamically-generated HTML page
inside the HTTP response exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram −
Typically, the JSP engine checks to see whether a servlet for a JSP file already
exists and whether the modification date on the JSP is older than the servlet. If the
JSP is older than its generated servlet, the JSP container assumes that the JSP hasn't
changed and that the generated servlet still matches the JSP's contents. This makes
the process more efficient than with the other scripting languages (such as PHP) and
therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having
to be a Java programming wiz. Except for the translation phase, a JSP page is
handled exactly like a regular servlet.
The Scriptlet
<body>
Hello World!<br/>
<%
out.println("Your IP address is " +
request.getRemoteAddr());
%>
</body>
</html>
JSP Declarations
A declaration declares one or more variables or methods that you can use in Java
code later in the JSP file. You must declare the variable or method before you use it
in the JSP file.
JSP Expression
Eg.
<html>
<head><title>A Comment Test</title></head>
<body>
<p>Today's date: <%= (new
java.util.Date()).toLocaleString()%></p>
</body>
</html>
JSP Comments
JSP comment marks text or statements that the JSP container should ignore. A JSP
comment is useful when you want to hide or "comment out", a part of your JSP
page.
<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page
source --%>
</body>
</html>
JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the
following form −
Eg.
Program:
<html>
<body>
<%@ page import ="java.sql.*" %>
<%@ page import ="javax.sql.*" %>
<%
String id;
int iid;
double dcost;
id=request.getParameter("pid");
String name=request.getParameter("pname");
String cost=request.getParameter("pcost");
iid=Integer.parseInt(id);
dcost=Double.parseDouble(cost);
try{
<%--comment – for Registering the driver --%>
Class.forName("oracle.jdbc.driver.OracleDriver");
PreparedStatement pstmt=con.prepareStatement("insert
into product values(?,?,?)");
pstmt.setInt(1,iid);
pstmt.setString(2,name);
pstmt.setDouble(3,dcost);
int i=pstmt.executeUpdate();
17. Develop a JSP application that accepting two numbers from the client
.html program and sending to a .jsp file in the server that responding to the
input arrived on request object and computing the sum of the two numbers
sending the output back to the client over response object.
Answer:
This question requires two programs 1. HTML program to initiate the process from
browser 2. JSP program in the server to accept the request from HTML program.
Programs:
sum.html program
<html>
<body>
<h2>Compute the sum of two numbers</h2>
<form name="testForm" method="GET"
action="computesum.jsp">
</body>
</html>
Computesum.jsp
<html>
<head>
<title>sum of two numbers with jsp</title>
</head>
<body>
<%
String value1, value2;
double n1, n2, sum;
value1=request.getParameter("num1");
value2=request.getParameter("num2");
n1=Double.parseDouble(value1);
n2=Double.parseDouble(value2);
sum=n1+n2;
</body>
</html>
18. A JSP program to connect to Oracle database and to get data from the
PRODUCT table and publish the record sets in a HTML table in the browser.
Programs:
First program : Product.html
<html>
<body>
<form action="prod.jsp" method="post">
<input type="submit" value="dispaly products" />
</form>
</body>
</html>
<HTML>
<HEAD>
<TITLE>Selecting products From a
Database</TITLE>
</HEAD>
<BODY>
<H1>Showing Products From a product table</H1>
<%
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost
:1521:xe","system","admin");
Statement stat = con.createStatement() ;
ResultSet resultset =
stat.executeQuery("select * from Product") ;
%>
<TABLE BORDER="1">
<TR>
<TH>ID</TH>
<TH>NAME</TH>
<TH>COST</TH>
</TR>
<% while(resultset.next()){ %>
<TR>
<TD> <%= resultset.getInt(1) %></td>
<TD> <%= resultset.getString(2) %></TD>
<TD> <%= resultset.getDouble(3) %></TD>
</TR>
<% } %>
</TABLE>
</BODY>
</HTML>
Team AOOP wishes you