You are on page 1of 141

Advanced Object Oriented Programming

( AOOP - Regular )

Lecture Notes

( This notes is for quick preparation, NOT covering all syllabus )

Prepared by

Dr. M.S.R.PRASAD
CO - 1
SHORT ANSWER QUESTIONS ( from CO-1 )

1. Types of inheritance
Answer:
a) multilevel b) multiple c) Hierarchical d) hybrid inheritance

2. Multi level inheritance?


Answer:
class A , class B extends A , class C extends B is multilevel inheritance

3. Advantages of inheritance in java?


Answer:
1. Reusability 2. Better organization of the code 3. Clean coding technique 4.
Method overriding are the advantages.

4. Multiple inheritance in Java, what is the problem?


Answer:
Java supports single parent class to derive the child class, but multi inheritance
needs more than one super classes. To overcome this problem, the child class can
be derived from one class and one interface.

Eg: class Book extends Paper implements from Ink


Where
Paper is the super class
Ink is the interface.
5. Example of an abstract class
Answer:
abstract class AbsEmp {
abstract void show();
}

6. Example of abstract method in Java.


Answer:
abstract class AbsEmp {
abstract void show();
}
In this above program abstract method show() has no definition, it’s definition
must be overridden in the child class of the abstract class AbsEmp .

7. "implements" keyword in java


Answer:
“implements” keyword is used for interface .
Eg.
interface Iface {
void callMe();
}
Class Employee implements Iface {
Public void callMe() {
System.out.println(“ hello dude”);
}
}
8. “extends” keyword - in interfaces ?
Answer:
interfaces can be extended with keyword “extends”
Eg.
interface Iface1 {
void callMe();
}
interface Iface2 extends Iface1 {
void callMeToo();
}

9. Testing in software development - Explanation


Answer:
coding and testing are the important steps of software engineering. As per the
requirements project can be designed and developed (coded), after the coding part is
completed code should be tested for correctness of the results ie validation and
verification purposes.

10. Design patterns


Answer:
Design patterns represent the best practices used by experienced object-oriented
software developers. Design patterns are solutions to general problems that software
developers faced during software development. These solutions were obtained by
trial and error by numerous software developers over quite a substantial period of
time. Finally Design Patterns are a software engineering concept describing
recurring solutions to common problems in software design.
11. Uses of design patterns
Answer:
During the design phase of the software development design patterns are used. They
are programming language-independent strategies for solving a common problem.
That means a design pattern represents an idea, not a particular implementation. By
using design patterns, you can make your code more flexible, reusable, and
maintainable.

12. Uses of Singleton pattern.


Answer:
The Singleton pattern also supports lazy loaded and static initialization, helps in the
hiding of dependencies, and provides a single access point to a particular example.

13. List of creational design patterns?


Answer:
Singleton, Factory and abstract Factory design patterns

14. Uses of Structural Design patterns .


Answer:
In software engineering, structural design patterns are design patterns that ease the
design by identifying a simple way to realize relationships among entities.
Examples of Structural Patterns include: Adapter pattern: 'adapts' one interface for a
class into one that a client expects. Structural design patterns are blueprints for
combining objects and classes into larger structures to achieve multiple goals. They
simplify the structure by identifying relationships, such as how classes inherit from
each other and how they are composed from other classes.
LONG ANSWER QUESTIONS ( from CO-1 )

1. Inheritance - Example program


Program:
class Animal {
void eat(){
System.out.println("Animals eat food");
}
void sleep(){
System.out.println("Animals sleep at night");
}
}

class Monkey extends Animal{


void jump(){
System.out.println("Monkeys easily jumps on trees");
}
void eat(){
System.out.println("Monkeys eat vegitarian food");
}
}
class Human extends Monkey{
void study(){
System.out.println("Humans study in great
universities");
}
void eat(){
System.out.println("Human eat cooked food and junk
food");
}
}

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

2. Inheritance – Example program -2 (method overriding)


(What is method overriding in java, Explain how runtime polymorphism is
achieved in java? Use at least two classes inheritance is the relationship between
them. Child class must override at least one method from the parent class.)

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

class Human extends Monkey{


@override from parent class
void eat(){
System.out.println("Human eat cooked food and junk
food");
}
void study(){
System.out.println("Humans study in great
universities");
}
}
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();
}
}

3.Abstract class – Example program -1


(Java program to create abstract class Car, with abstract methods steering() and
braking(). Create a subclass Maruthi to implements abstract methods in it.)

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

4.Abstract class – Example program -2


(Java program with an abstract class Brazo in which callMe() method is an abstract
method. Write another java class that should implement callMe() method of Brazo
class, so that callMe() method can be called.)

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

5. Interface –abstract class - Example program -1


(Java program interface Animal having atleast two methods in it, write a Monkey
class as abstract class, atleast one abstract method in it, Write Human class with
one method in it, test how the methods of Animal and Monkey are executed?)

Program:
interface Animal {
void eat();
void sleep();
}

abstract class Monkey implements Animal{


abstract void jump();
public void eat(){
System.out.println("Monkeys eat vegitarian food");
}
public void sleep(){
System.out.println("Monkeys sleep on trees");
}
}
class Human extends Monkey{
void study(){
System.out.println("Humans study in great
universities");
}
void eat(){
System.out.println("Human eat cooked food and junk
food");
}
}

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

class IntImpl implements One {


public void callMe(){
System.out.println("callme: output");
}

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

8. Multiple inheritance - Example program


Answer:
Java does not support multiple inheritance ie child class having two parent classes,
but it can be achieved through one parent as class and another as interface. The
following program demonstrates this feature.

Program :
interface One{
void callMe();
}

class Hello{
void greet(){
System.out.println("Hello world");
}
}

class HelloOne extends Hello implements One {


public void callMe(){
System.out.println("callme: output");
}
void show(){
System.out.println("today is wednes day");
}
}

class DemoIntf5{
public static void main(String[] args){
HelloOne ho1 = new HelloOne();
ho1.callMe();
ho1.greet();
ho1.show();
}
}

9. Differentiate interface with abstract class in java

Abstract class Interface

1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

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

10. Singleton design pattern – Example program


Answer;
SINGLETON Design Pattern :
This pattern involves a single class which is responsible to create an object while
making sure that only single object gets created. This class provides a way to access
its only object which can be accessed directly without need to instantiate the object
of the class.

Important points:
1. Private default constructor
2. Static object
3. Static method to return the object to the caller.
Program :
class Hello{
private Hello(){
}

static Hello obj = new Hello();


static Hello getObject(){
return obj;
}

void show(){
System.out.println("Hello World");
}
}

class DemoSing1 {
public static void main(String[] args){

Hello h1 = Hello.getObject();
h1.show();
}
}

11. Block diagram for Factory design pattern


Answer:
Components used in this design pattern block diagram:
1. Interface Shape
2. Class Circle
3. Class Rectangle
4. Class Square
5. Class ShapeaFctory
6. Class FactoryPatternDemo(Client program)
All the above seven components are organized as sown in the diagram to
implement Factory design pattern.

Factory design pattern – bock diagram

12. Factory design pattern – Example program – 1


Program:
import java.util.Scanner;
interface Shape{
void draw();
}

class Circle implements Shape{


public void draw(){
System.out.println(" circle has no sides");
}
}
class Square implements Shape{
public void draw(){
System.out.println(" square has all equal sides");
}
}

class Rectangle implements Shape{


public void draw(){
System.out.println(" rectangle has two sides equal");
}
}

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

13. Factory design pattern - Example program – 2


Program:
import java.util.Scanner;
interface Service{
void loanPayment();
}

class SBI implements Service{


public void loanPayment() {
System.out.println(" Loan paid in SBI with roi 7.5%");
}
}

class HDFC implements Service{


public void loanPayment() {
System.out.println(" Loan paid in HDFC bank with roi
7.9%");
}
}

class ICICI implements Service{


public void loanPayment(){
System.out.println(" Loan paid in ICICI bank with roi
7.8%");
}
}

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

14. Block diagram - Abstract Factory design pattern


Answer:
Components used in this diagram

1. interface Shape
2. class Rectangle
3. class Square
4. class RoundedRectangle
5. class RoundedSquare
6. abstract class AbsFactory
7. class ShapeFactory
8. class RoundedSquare
9. class FactoryProducer
10.class AbstractFactoryPatternDemo (client program)
All the above 10 components are organized as shown in the below diagram to
implement abstract factory design pattern

Abstract Factory design – block diagram

15. Abstract Factory design pattern - Example program


Program:
interface Shape{
void draw();
}

class Rectangle implements Shape{


public void draw(){
System.out.println(" I am a Rectangle");
}
}
class Square implements Shape{
public void draw(){
System.out.println(" I am a Square");
}
}

class RoundedRectangle implements Shape{


public void draw(){
System.out.println(" I am a rounded Rectangle");
}
}

class RoundedSquare implements Shape{


public void draw(){
System.out.println(" I am a rounded Square");
}
}

abstract class AbsFactory {


abstract Shape getShape(int x);
}

class ShapeFactory extends AbsFactory {


Shape getShape(int x){
if (x==1)
return new Rectangle();
else if(x==2)
return new Square();
else return null;
}
}

class RoundedShapeFactory extends AbsFactory {


Shape getShape(int x){
if (x==1)
return new RoundedRectangle();
else if(x==2)
return new RoundedSquare();
else return null;
}
}

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

16. Aggregation - Example program


Answer:
Aggregation is HAS-A type relation among java objects.
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.

Program :
// Agrigation program – object as a instance variable (through constructor)

class Address {
String d_no;
String city;

Address( String d, String c){


d_no=d;
city=c;
}
void show_details(){
System.out.println("Door no -> "+d_no);
System.out.println("city -> "+ city);
}
}

class Employee {
String name;
String emp_no;
Address ad;

Employee( String n, String e, Address a){


name=n;
emp_no=e;
ad=a;
}

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

Address aa= new Address("100", "Delhi");


Employee ee=new Employee("Rahul G", "CSE-255",aa);
ee.show_details();
}
}

17. Adopter design pattern - Aggregation – Example program


Answer:
The following program demonstrates two incompatible interfaces, where CricPlayer
class and HockPlayer class are good to access their own methods. But

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 HockPlayer implements Hockey{


public void playHockey(){
System.out.println(" playing hockey is my passion");
}
}

class SpCrikPlayer implements Cricket{


public void playCricket(){
Hockey hh = new HockPlayer();
hh.playHockey();
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();
}
}

18. Block diagram - Decorator design pattern


Answer:
Components used in the diagram

1. interface Shape
2. class Circle
3. class Rectangle
4. class ShapeDecorator
5. class RedShapeDecorator
6. class DecoratorDemoPattern (client program)

All the above 6 components are organized as shown in the below diagram to
implement Decorator design pattern ..
Decorator design pattern - block diagram

19. Decorator design pattern – Example program


Program:
interface Shape{
void draw();
}

class Circle implements Shape{


public void draw(){
System.out.println(" I am a circle");
}
}
class Rectangle implements Shape{
public void draw(){
System.out.println(" I am a rectangle");
}
}

class ShapeDecorator implements Shape{


Shape sh;
ShapeDecorator(Shape s){
sh=s;
}
public void draw(){
sh.draw();
System.out.println(" i have silver lining");
}
}

class RedShapeDecorator implements Shape{


Shape sh;
RedShapeDecorator(Shape s){
sh=s;
}
public void draw(){
sh.draw();
setRedBorder();
}
void setRedBorder(){
System.out.println(" i have red border");
}
}
class DecoDemo1{
public static void main(String[] args){
Shape s = new Circle();
Shape s1 = new ShapeDecorator(s);
RedShapeDecorator s2 = new RedShapeDecorator(s1);
s2.draw();

Shape s3 = new Rectangle();


Shape s4 = new ShapeDecorator(s3);
s4.draw();

}
}

20. Structural Design Patterns - Explanation


Answer:
There are many structural design patterns available, most popular among them are

1. Adopter design pattern


One class can adopt the features of other class without changing the
original class content
2. Decorator design pattern
One class get the features of other class/ classes without changing it’s
implementation.

Both of them use aggregation concept of oop.


Aggregation:

Aggregation is HAS-A type relation among java objects.

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.

The purpose of design patterns is simple - to provide structure. By giving you a


basic framework for problem-solving, they can speed up the development process.
Generally speaking, using design patterns will make your code more flexible,
reusable, and maintainable.

They are reusable in multiple projects.


They provide the solutions that help to define the system architecture.
They capture the software engineering experiences.
They provide transparency to the design of an application.

21. Template Pattern - Explanation


Answer:
Template pattern, This pattern comes under behavior pattern category. An abstract
class exposes defined way(s)/template(s) to execute its methods. Its subclasses can
override the method implementation as per need but the invocation is to be in the
same way as defined by an abstract class.

The Template Method design pattern allows subclasses to change the steps of an
algorithm without modifying its structure. This leads to more reusable and flexible
code. It's particularly beneficial when a part of an algorithm can vary, but the
structure of the algorithm is to be preserved.

Advantages:

1. Encourages Code Reusability: The Template Design Pattern promotes code


reuse by providing a common template or algorithm structure in the abstract
class.
2. Defines a Consistent Algorithm Structure: The pattern enforces a consistent
algorithm structure across multiple subclasses.
3. Easy to Use.
4. Time and Cost-efficient.
5. Proven through testing.

Model diagram:
22. Template design pattern for “making Tea” – Example program
Program:
abstract class Drink{
abstract void boilWater();
abstract void addTeaPowder();
abstract void addSugar();
abstract void serveTea();

final void makeTea(){


boilWater();
addTeaPowder();
addSugar();
serveTea();
}
}

class Tea extends Drink{


void boilWater(){
System.out.println(" boil water until we get fumes");
}

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

23. Iterator design pattern - Explanation


Answer:
The most important two methods are

1. public boolean hasNext();


2. public Object next();

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.
Example program can be written..

interface Iterator {
public boolean hasNext();
public Object next();
}

24. Iterator design pattern for “String objects” – Example program


Program:
interface Iterator {
public boolean hasNext();
public Object next();
}

interface Container {
public Iterator getIterator();
}

class Names implements Container {


String list [] =
{"Ram","Lakshman","Bharath","Satrughn","seetha"};

public Iterator getIterator() {


return new NameIterator();
}
}

class NameIterator implements Iterator {


int index=0;
Names nr=new Names();

public boolean hasNext() {

if(index < nr.list.length){


return true;
}
return false;
}

public Object next() {

if(hasNext()){
return nr.list[index++];
}
return null;
}
}

class IteratorPattern1 {
public static void main(String[] args) {
Names namesList = new Names();

Iterator iter = namesList.getIterator();


while(iter.hasNext()==true){
String name = (String)iter.next();
System.out.println("Name : " + name);
}
}
}
CO - 2
SHORT ANSWER QUESTIONS ( from CO-2 )

1. Phases of Test driven development


Answer:
1. Red Phase : planning and design stage i.e before coding
2. Green Phase : coding stage
3. Refactoring : code change

2. Refactoring of code
Answer:
To get the efficiency of the code, refactoring is required. In Refactoring the
behavior of the code is unchanged ie. Inputs is same and output is same. What
happens is the code is reorganized by changing data structures or input modes or
adding more functions or class hierarchical arrangements.

3. Characteristics of clean code


Answer:
The code that is easily readable, modifiable, testable, maintainable and is less prone
to errors is referred as "Clean Code".

4. Comments in clean coding


Answer:
Commenting is also considered as one of the best practises to make the code easily
understandable. In Java, two kinds of comments are allowed:

Documentation comments - The target audience is the users of codebase


Implementation comments - The target audience is the developers that work on the
codebase.

5. Variable - As per clean coding - Explanation


Answer:
A variable is considered as an identifier in programming languages,

Variables are used to represent data items in program. Variables are declared with
data types.

Eg . int marks;

boolean flag;

characters to declare a variable

a) length
b) begin with small letter or underscore
c) special characters used

6. Dead code / Lazy code


Answer:
Dead code is a code available in the program but has no significance, found no
references in the usage.

When there is no significance of a particular code segment, it is called dead code or


lazy code.

7. Relate a method call?


Answer:
In java methods are declared as class methods and instance methods.

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

8. Uses of Generics in Java?


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

Code reusability is an advantage

9. Comparable interface - Explanation


Answer:
Java Comparable interface is used to order the objects of the user-defined class.
This interface is found in java.lang package and contains only one method named
compareTo(Object).
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.

10. comparable and comparator interfaces - Differences.


Answer:
Comparable interface :
available in java.lang package
it’s method is compareTo( Object o1)
Comparator interface
available in java.util package
it’s method is compare( Object o1, Object o2)

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

methods of the Hashset.

12. collection framework - Explanation


Answer:
Collection framework has three major interfaces List, Queue and Set

List has been implemented by arrayList, LinkedList and Vector classes

Queue is implemented by PriorityQueue class

Set is implemented by HashSet, LinkedHashSet and TreeSet

Collection framework classes are used to store and manage variety of Objects.

13. 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.
14. iterator interface - Explanation
Answer:
Iterator interface provides the facility of iterating the elements in a forward
direction only, it is used along with many collection framework classes.

There are 3 methods in an iterator interface only.

Public Boolean hasNext() – returns true if element/s are available otherwise false.

Public Object next() – returns object if available

Public void remove() – last element returned by the iterator will be removed
LONG ANSWER QUESTIONS ( from CO-2 )

1. Techniques / Characteristics of clean code.


Answer:
The code that is easily readable, modifiable, scalable(in some cases), maintainable
and is less prone to errors is referred as "Clean Code". Less prone to errors means
that there will be very less chances of getting bugs in that code.

Characteristics of Clean Code:

 Simple:

 Maintainable:

 Testable:

 Readable:

 Techniques of clean code:

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

4. White spaces and Indentation:


To increase the readability include white spaces wherever they are
appropriate. Indentation must be followed to understand the block of
statements ie group of logically related statements.
5. Method parameters : avoid too many parameters or arguments to be
passed in a method call, to achieve this think of data classes.
6. Hard coding : Data may be needed in different ways when project is
executed in real time, so while developing program use appropriate source
but always not from the key board.
7. Code comments : comments are required for every code component to
express its relevance in the project useful in the maintenance phase.
8. Log file : It is important to understand the execution of the code
9. SOLID properties : Simple , open/closed principle, Liskov substitution
principle, Interface segregation principle, Dependency inversion principle.
10. keep it simple and stupid whether it is design or code.

2. Clean coding techniques – Example program


Answer:
One important point in clean coding technique is to build a method with minimum
number of arguments.

a) Method parameters : avoid too many parameters or arguments to be passed in


a method call, to achieve this think of data classes.
b) Naming conventions
c) Comments :

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);
}
}
3. code smells - Explanation
Answer:
There are many known code smells that have been categorized as follows:

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.

Dispensable: A dispensable is something pointless and unneeded whose absence


would make the code cleaner, more efficient and easier to understand like
Comments, Duplicate Code, Lazy Class, Data Class, Dead Code and Speculative
Generality.

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
4. code smells within classes - Explanation
Answer:
Code Smells Within Classes
1. Comments: Yes, Comments are code smells too. It is like deodorant to the
code. If comments explain a few lines of complex code or a complex
expression, it should be made as a complete another function/ sub-expression
respectively.

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.
5. code smells with in classes – Example Program
Answer:
One of the code smells within the class is
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.
I am going present a program to avoid above code smell.

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

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

public static void main(String[] args){


StudentY st1 = new StudentY();
st1.show("Rahul",100, 22, "vja");
}
}
----------------------------
Program after Refactoring:
----------------------------
// 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);
}
}
7. Demonstrate a code segment to represent duplicate.
Answer:
In the following code segment method1() and method2() methods are exactly the
same. This is an example of duplicate code.

public class MyClass {


public void method1() {
int a = 1;
int b = 2;
int c = a + b;
System.out.println(c);
}

public void method2() {


int a = 1;
int b = 2;
int c = a + b;
System.out.println(c);
}
}

8. Build a java program to remove duplicate code in Q.7


Answer :
By removing the duplicate code ie method2 from the above program, I am giving
the fully implemented program as follows.

class MyClass {
public void method1() {
int a = 1;
int b = 2;
int c = a + b;
System.out.println(c);
}

public static void main(String[] args){


MyClass mc1 = new MyClass();
Mc1.method1();
}
}

9. Generics / Generic method - Example program - 1


Answer:

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:

1) Type-safety: We can hold only a single type of objects in generics. It doesn’t


allow to store other objects.
2) 2) Type casting is not required: There is no need to typecast the object.
3) 3) Compile-Time Checking: It is checked at compile time so problem will not
occur at runtime.
4) Code Reusability

Type Parameters :

The type parameters naming conventions are important to learn generics thoroughly.
The common type parameters are
1. T – Type 2. E – Element 3. K – Key 4. N – Number 5. V – Value

Program : whether the given number is Zero/Non-zero (Integer and Double types)

class Gen10{

<T> void check(T data1){

int i;

double d;

String s;

if(data1 instanceof Integer){

if( (Integer)data1 == 0)

System.out.println("ZERO");

else

System.out.println("non ZERO");

else if(data1 instanceof Double){

if( (Double)data1 == 0)

System.out.println("ZERO");

else

System.out.println("non ZERO");

public static void main(String[] args){

Gen10 g1 = new Gen10();


g1.<Integer>check(200);

g1.<Integer>check(0);

g1.<Double>check(12.6);

g1.<Double>check(0.0);

10. Generics class - Example program

Program: whether the given number is even/odd (Integer and Double types)

class Gen10 <T>{

T data1;

Gen10(T data1){

this.data1 = data1;

void check(){

int i;

double d;

String s;

if(data1 instanceof Integer){

if( (Integer)data1 == 0)

System.out.println("ZERO");
else

System.out.println("non ZERO");

else if(data1 instanceof Double){

if( (Double)data1 == 0)

System.out.println("ZERO");

else

System.out.println("non ZERO");

public static void main(String[] args){

Gen10<Integer> g1 = new Gen10<>(200);

g1.check();

Gen10<Integer> g2 = new Gen10<>(0);

g2.check();

Gen10<Double> g3 = new Gen10<>(200.99);

G3.check();

Gen10<Double> g4 = new Gen10<>(0.0);

g4.check();

}
11. Generic method - Example program- 2
Program: whether the given number is even/odd (Integer and Double types)

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

12. Comparable interface – Example program.


Program: ( Find out the best object depends on cgpa of the student )
class Student implements Comparable<Student>{
String name;
int rank;
double cgpa;
double salarypak;

Student(String n, int r, double cg, double sp){


name=n;
rank=r;
cgpa=cg;
salarypak=sp;
}

public int compareTo(Student s){


if(cgpa > s.cgpa)
return 1;
else if(cgpa < s.cgpa)
return -1;
else return 0;
}
}
class CompDemo{
public static void main(String[] args){

Student s1 = new Student("Raman",100,9.9,12.5);


Student s2 = new Student("Kishore",40000,7.9,25.9);

int i = s1.compareTo(s2);
if(i==1)
System.out.println("Raman is best");
else if(i==-1)
System.out.println("Kishore is best");
else
System.out.println("Both are best");
}
}

13. comparable and comparator interfaces – Differences


Answer:

Comparable Comparator

1) Comparable provides compareTo() Comparator provides compare()


method to sort elements method to sort elements.

2) Comparable affects the original class, i.e., Comparator doesn't affect the original
the actual class is modified. class, i.e., the actual class is not
modified.

3). Comparable is present A Comparator is present in


in java.lang package. the java.util package.
4) Comparable provides a single sorting The Comparator provides multiple
sequence. sorting sequences.

5) We can sort the list elements of Comparable We can sort the list elements of
type by Collections.sort(List) method. Comparator type
by Collections.sort(List,
Comparator) method.

14. Block diagram of collection Framework


Answer:
15. ArrayList / LinkedList - Example Program-1 ( Integer objects )
Program:
import java.util.*;
class List1 {
public static void main(String[] args){
// create ArrayList or LinkedList as per the question
//LinkedList<Integer> numbers = new LinkedList<>();
ArrayList<Integer> numbers = new ArrayList<>();
// Add elements to ArrayList
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);
System.out.println("ArrayList: " + numbers);
numbers.set(3,35);
System.out.println("size"+ numbers.size());
System.out.println(" ");
numbers.remove(3);
Iterator itr= numbers.iterator();
while(itr.hasNext()) {
System.out.print(itr.next());
System.out.print(" , ");
}
System.out.println("size"+ numbers.size());
}
}
16. ArrayList / LinkedList - Example Program-1 ( String objects )
Program:
import java.util.*;
class List2 {
public static void main(String[] args){

// create ArrayList or LinkedList as per the


question
//LinkedList<String> countries = new LinkedList<String>();
ArrayList< String > countries = new ArrayList< String >();
// Add elements to List
countries.add(“India”);
countries.add(“Australia”);
countries.add(“USA”);
countries.add(“Nepal”);
countries.add(“Russia”);
System.out.println("ArrayList: " + countries);

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

17. HashSet / LinkedHashSet / TreeSet program with ( Integer Objects )


( Any four methods on Set )
Program:

import java.util.*;
class Set1 {
public static void main(String[] klu){

// declare set as per the question from the


following
// HashSet <Integer> list = new
HashSet<Integer>();
// LinkedHashSet <Integer> list = new
LinkedHashSet<Integer>();
TreeSet <Integer> list = new
TreeSet<Integer>();

// add() method ...


list.add(40);
list.add(20);
list.add(30);
list.add(70);
list.add(50);

System.out.println(list);

// contains() method ...


boolean x = list.contains(20);
System.out.println(x);
System.out.println(list.size());

// remove() method ...


list.remove(4);
System.out.println(list);
System.out.println(list.size());

// iterator() method ...


Iterator itr = list.iterator();
while(itr.hasNext()){
int i = (Integer) itr.next();
System.out.println(i);
}
}
}

18. HashSet / LinkedHashSet / TreeSet program with ( String Objects )


( Any four methods on Set )
Program:
import java.util.*;
class Set2 {
public static void main(String[] klu){

// declare set as per the question from the


following
TreeSet <String> list = new TreeSet<String>();
//LinkedHashSet <String> list = new LinkedHashSet<>();
//HashSet <String> list = new HashSet<String>();

// add() method ...


list.add("India");
list.add("canada");
list.add("Egypt");
list.add("Malaysia");
list.add("singapore");
System.out.println(list);

// contains() method ...


boolean x = list.contains("malaysia");
System.out.println(x);
System.out.println(list.size());

// remove() method ...


list.remove("Egypt");
System.out.println(list);
System.out.println(list.size());

// iterator() method ...


Iterator itr = list.iterator();
while(itr.hasNext()){
String i = (String) itr.next();
System.out.println(i);
}
}
}

19. HashSet / LinkedHashSet / TreeSet program ( Operations on Sets)


Answer:
Major Operations on Sets are performed with the following methods

1. Union - addAll() method


2. Intersection - retainAll() method
3. Difference - removeAll() method
Program:
import java.util.*;
class SetExample {
public static void main(String args[])
{
// declare set as per the question from the following
Set <Integer> list = new LinkedHashSet <>();

a.addAll(Arrays.asList(
new Integer[] { 1, 3, 2, 4, 8, 9, 0 }));

Set<Integer> b = new LinkedHashSet<Integer>();

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

Set<Integer> intersection = new HashSet<>(a);


intersection.retainAll(b);
System.out.print("Intersection of the two Set");
System.out.println(intersection);
Set<Integer> difference = new TreeSet<>(a);
difference.removeAll(b);
System.out.print("Difference of the two Set");
System.out.println(difference);
}
}

20. Block diagram of Map interface and Explanation


Answer:

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.

SortedMap is another interface extending Map.

TreeMap class implements both SortedMap and Map interfaces


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.

Operations using Map Interface and HashMap/ LinkedHashMap /TreeMap

Adding Elements :
hm1.put(1, "Geeks");
hm2.put(new Integer(1), "Geeks");

Changing Element:
hm1.put(new Integer(2), "For");

Removing Elements:
hm1.remove(new Integer(4));

Iterating through the Map:


for (Map.Entry<String, Integer> e : map.entrySet())
System.out.println(e.getKey() + " "+
e.getValue());

By using the for-each loop, we get an entrySet() which provides an automated


“view” of the data in the map, in the form of key-value pairs. Each entrySet
contains a key and corresponding values.
21. HashMap/TreeMap/LinkedHashMap program with ( Integer Objects )
( Any Five methods of Map)
Program:
import java.util.*;
class MapDemo11{
public static void main(String[] args){

// use the following map declaration as per the question


//Map<String,Integer> mp = new HashMap<>();
//Map<String,Integer> mp = new LinkedHashMap<>();
Map<String,Integer> mp = new TreeMap<>();
// load elements
mp.put("one", 181);
mp.put("two", 275 );
mp.put("three",356);
mp.put("four", 499);
mp.put("five", 598);
System.out.println(" No of element in the map (before) :"+mp.size());

// removing an element
mp.remove("four");

// getting element from map


int str =(Integer) mp.get("five");
System.out.println(str);
// checking the size of the map
System.out.println(" No of element in the map (after) :"+mp.size());

// traversing through map (entrySet() method)

for(Map.Entry<String,Integer> myMap: mp.entrySet())


{
System.out.print(myMap.getKey()+" : ");
System.out.println(myMap.getValue());
}
}
}

22. HashMap/ LinkedHashMap /TreeMap program with ( String Objects )


( Any Five methods of Map )
Program:
import java.util.*;
class MapDemo1{
public static void main(String[] args){
// use the following map declaration as per the question

//Map<Integer,String> mp = new HashMap<>();


//Map<Integer,String> mp = new LinkedHashMap<>();
Map<Integer,String> mp = new TreeMap<>();
// 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);

// getting element from map


String str =(String) mp.get(5);
System.out.println(str);

// checking the size of the map


System.out.println(" No of element in the map (after) :"+mp.size());
// traversing through map (entrySet() method)
for(Map.Entry<Integer,String> myMap: mp.entrySet())
{
System.out.print(myMap.getKey()+" : ");
System.out.println(myMap.getValue());
}
}
}
CO – 3
SHORT ANSWER QUESTIONS ( from CO-3 )

1. What is parallel programming?


Answer:
Parallel programming can also be called as Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use


multitasking to utilize the CPU. Multitasking can be achieved by two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

2. Identify the differences between Multithreading and Multitasking


Answer:

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.

weight Process is heavyweight. Thread is lightweight.

Cost of communication Cost of communication Cost of communication


between the process is between the thread is low.
high.
3. Threads and Thread states?
Answer:

Thread is basically a lightweight sub-process, a smallest unit of processing.


Multiprocessing and multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common
memory area.
The life cycle of the thread with thread states are as follows:
1. New : The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
2. Runnable : The thread is in runnable state after invocation of start() method,
but the thread scheduler has not selected it to be the running thread.
3. Running: The thread is in running state if the thread scheduler has selected it.
4. Non-Runnable (Blocked): This is the state when the thread is still alive, but is
currently not eligible to run.
5. Terminated: A thread is in terminated or dead state when its run() method
exits.
4. List the ways, threads can be declared in Java?
Answer:
Threads in Java can be declared in two ways.
1. Extends Thread

Class Thr1 extends Thread{


Public void run(){
}
}

2. Implements Runnable
Class Thr2 implements Runnable{
Public void run(){
}
}

5.Illustrate Thread class with fully written constructor.


Answer:

Class MyThread extends Thread {


String str;
MyThread(String s){
Str=s;
}
}
6.Discuss the importance of run() method?
Answer:
public void run() is used to perform action for a thread.

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.

7.Explain sleep() method in threads.


Answer:

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

8. What is the purpose of join()?


Answer:
The join() method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task.

9.Judge the relevance of priority in threads?


Answer:

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.

10.Types of Synchronization in java.


Answer:
It is to maintain the critical section among threads.
Key word: synchronized
1. Synchronized method()
Eg. synchronized void add(){

2. Synchronized block - from any method

Eg. synchronized(this){
}
LONG ANSWER QUESTIONS ( from CO-3 )

1. Java Thread program for displaying “HelloWorld”.


Answer:
Classs MyThr implements Runnable {
public void run(){
System.out.println(“Hello World”);
}
public static void main(String[] args){
MyThr m1 = new MyThr();
Thread t1 = newThread(m1);
t1.start();
}
}

2. Java thread to print 1 to 10 numbers…


Answer:
Classs MyThr implements Runnable {
public void run(){
for(int I = 1; i<=10; i++)
System.out.println(i);
}
public static void main(String[] args){
MyThr m1 = new MyThr();
Thread t1 = newThread(m1);
t1.start();
} }
3. Sleep() method -extended from Thread .
Answer:
classs MyThr 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);
}
}
public static void main(String[] args){
MyThr t1 = new MyThr();
MyThr t2 = new MyThr();

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

5. Java thread program –Runnable interface - to print Fibonacci sequence


numbers / even odd numbers
Note: This program is good for any three/five thread methods of thread ( sleep(),
start(), isAlive(), join() and run() methods )
Answer:
class FiboSeq{
void fibo(){
int a,b,f;
a=0;
b=1;
System.out.println(a);
System.out.println(b);
try{
for(int i=0; i< 8; i++){
f=a+b;
System.out.println(f);
Thread.sleep(500);
a=b;
b=f;
}
}
catch(Exception e){
System.out.println(e);
}
}

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

class ThrN implements Runnable{


FiboSeq fs;
ThrN(FiboSeq f1){
fs=f1;
}
public void run(){
fs.fibo();
}
}

class ThrM implements Runnable{


FiboSeq fs;
ThrM(FiboSeq f1){
fs=f1;
}

public void run(){


fs.evenOdd();
}
}
class ThrFibo1 {
public static void main(String[] args){
FiboSeq ff = new FiboSeq();

ThrN tt = new ThrN(ff);


Thread t1 = new Thread(tt);

ThrM tk = new ThrM(ff);


Thread t2 = new Thread(tk);

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

System.out.println(" t1 is existing? "+ t1.isAlive());


System.out.println(" t2 is existing? "+ t1.isAlive());
}
}

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

public void run(){


int ectr=0;
int octr=0;

int ar[] = {12,97,87,54,78,32,9,91,53,75};


for(int i=0; i<ar.length; i++){
if((ar[i] % 2) == 0) {
System.out.println(str +": "+ ar[i] + " is an EVEN
number");
ectr++;
}
else {
System.out.println(str + " : "+ar[i] + " is an ODD
number");
octr++;
}
}
System.out.println(str +": count of EVEN numbers =
"+ectr);
System.out.println(str +": count of ODD numbers =
"+octr);
}
}

class Thr2 implements Runnable {


String str;
Thr2( String str){
this.str =str;
}
public void run(){
int zctr=0;
int nzctr=0;
try{
int ar[] = {12,0,87,54,0,32,9,91,53,0};
for(int i=0; i<ar.length; i++){
if(ar[i] == 0) {
System.out.println(str +": "+ ar[i] + " is a ZERO");
zctr++;
}
else {
System.out.println(str + ": "+ar[i] + " is NON ZERO");
nzctr++;
}
Thread.sleep(500);
}
} catch(Exception e){
System.out.println(e);
}
System.out.println(str +" count of ZERO numbers =
"+zctr);
System.out.println(str +" count of NonZero numbers =
"+nzctr);
}
}
class ThrDemo5 {
public static void main(String[] args){
String s1 = "FIRST";
String s2 = "SECOND";

Thr1 t1 = new Thr1(s1);


Thr1 t3 = new Thr1(s1);

Thr2 gg = new Thr2(s2);


Thread t2 = new Thread(gg,s2);

t1.start();
t2.start();
t3.start();

System.out.println(" Name of Thread1 ="+ t1.getName());


System.out.println(" Name of Thread2 ="+ t2.getName());

t1.setPriority(9);
t3.setPriority(2);
System.out.println(t1.getName() + " priority : " +
t1.getPriority());
System.out.println(t3.getName() + " priority : " +
t3.getPriority());

System.out.println(" BEFORE 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());

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:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization

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 Thr1 implements Runnable {


Bangee bg;
String str;
Thr1(Bangee bb, String str1){
bg=bb;
str = str1;
}
public void run(){
bg.doit(str);
}
}

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 Thr1 implements Runnable {


Bangee bg;
String str;
Thr1(Bangee bb, String str1){
bg=bb;
str = str1;
}
public void run(){
bg.doit(str);
} }
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();
}
}

9. Examine the process of inter-thread communication (communication


between threads) with a neat diagram, explain wait() and notify() methods
in this context.
Answer:

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:
class Thrd extends Thread{
boolean flag=false;

void susp(){
System.out.println( "Thread is suspended");
flag = true;
}

void resm(){
System.out.println( "Thread is notified and resumed");
flag=false;
synchronized(this){
notify();
}
}
public void run(){
try{
for( int i =1; i<=10; i++){
System.out.println("printing .... "+i);
Thread.sleep(200);
synchronized(this){
while(flag){
wait();
}
}
}
}catch(Exception e){
System.out.println(e);
}
}
}

class WtNfDemo{
public static void main(String[] args){
Thrd t1= new Thrd();
t1.start();
try{

t1.susp();
Thread.sleep(10000);
t1.resm();

} catch(Exception e){
System.out.println(e);
}
}
}
10.Differentiate synchronized block and method
Answer:

Synchronized method Synchronized block


Lock Object/class level Only object level
scope Entire method Limited to few statements
Performance low high
Waiting time high low
Null pointer no yes
exception

11. A classical Producer and Consumer java threads to demonstrate inter


thread communication.
Program :
class Data {
int n;
boolean sig=false;
synchronized void put(int n1) {
try {
if(sig)
wait();
}catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}

n=n1;
sig=true;
System.out.println("put= "+n);
notify();
}

synchronized int get() {


try {
if(!sig)
wait();
}catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got= "+n);
sig=false;
notify();
return n;
}

class Producer implements Runnable {


Data dt;
Producer(Data dt1){
dt=dt1;
}

public void run() {


int j=0;
for(int i=0;i<10;i++){
dt.put(j++);
}
}
}

class Consumer implements Runnable {


Data dt;
Consumer(Data dt1) {
dt=dt1;
}
public void run() {
for(int i=0;i<10;i++) {
dt.get();
}
}
}
class ThrProdCons {
public static void main(String args[]) {
Data dt= new Data();
Producer pp = new Producer(dt);
Thread p1 = new Thread(pp);
Consumer cc = new Consumer(dt);
Thread c1 = new Thread(cc);
p1.start();
c1.start();
}
}
CO – 4
SHORT ANSWER QUESTIONS ( from CO-4 )

1. List DML commands in SQL?


Answer:

DML – stands for Data Manipulation Language commands,


they are usually called CRUD operations.
C – Create ie INSERT SQL
R – Read ie SELECT SQL
U – Update ie UPDATE SQL
D – Delete ie DELETE SQL

2. which java package must be imported for jdbc?


Answer :
Java.sql.* pkg must be imported to work with JDBC operations in Java, it
contains classes like

Connection, Statement, PreparedStatement, CallableStatement, ResultSet,


DatabaseMetaData, ResultSetMetaData etc..

These classes are useful for JDBC applications development.

3. Which SQL command is used for querying a table?


Answer :
SELECT SQL command is used for the querying a table.
Eg.
SELECT * from PRODUCT;
SELECT PID, PNAME from PRODUCT;
SELECT PID, PNAME from PRODUCT where PID>115;
4. Express the role of a driver and Driver Manager in JDBC?
Answer :

From the above architecture, JDBC Driver manager and JDBC Driver plays a
major role in making JDBC application programs.

DriverManager: This class manages a list of database drivers. Matches connection


requests from the java application with the proper database driver using
communication sub protocol. The first driver that recognizes a certain subprotocol
under JDBC will be used to establish a database Connection.

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.

6. Database is the heart of any programming application, in this context


how java programs are designed to connect to any commercial
databases available in the market? Write the procedure that you know
to connect java program to a Oracle database.

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.

 Open a connection: Requires using the DriverManager.getConnection()


method to create a Connection object, which represents a physical connection
with the database.

 Execute a query /Execute update: Requires using an object of type


Statement for building and submitting an SQL statement to the database.
 Extract data from result set: Requires that you use the appropriate
ResultSet.getXXX() method to retrieve the data from the result set.

 Clean up the environment: Requires explicitly closing all database


resources versus relying on the JVM's garbage collection.

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.

8. Explain the benefits of web programming


Answer:

Web programming is the process of creating web pages, developing web


pages to creating intricate web applications.

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:

web browsers like


Google chrome
Mozilla Firefox
Microsoft Internet Explorer are the few examples of web clients.

10. Give example of web server?


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.

12.Difference between HTML and JSP programs


Answer:

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:

14.List the Advantages of JSP over Servlets.


Answer:

1. Easy maintenance: JSP is easy to maintain since separating business


logic with presentation logic is simple.
2. Servlet extension: Being the extension of Servlet technology, it can use
all the features of Servlet.
3. Require less coding: It allows custom tags that reduces the code and
makes coding flexible.
LONG ANSWER QUESTIONS ( from CO-4 )

1. JDBC Drivers Types


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 −

Type 1: JDBC-ODBC Bridge Driver

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.

If we change the Database, we have to change the native API, as it is specific to a


database and they are mostly obsolete now, but you may realize some speed
increase with a Type 2 driver, because it eliminates ODBC's overhead.

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.


Type 3: JDBC-Net pure Java

In a Type 3 driver, a three-tier approach is used to access databases. The JDBC


clients use standard network sockets to communicate with a middleware application
server. The socket information is then translated by the middleware application
server into the call format required by the DBMS, and forwarded to the database
server.

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

In a Type 4 driver, a pure Java-based driver communicates directly with the


vendor's database through socket connection. This is the highest performance driver
available for the database and is usually provided by the vendor itself.

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.

2. Identify difference between INSERT and UPDATE SQL statements in


JDBC?
Answer:
INSERT SQL UPDATE SQL
1 New record is added to table NO new record is added
2 Row count will be increased Row count remains same
3 Applied on a single row Multiple rows can be affected
4 Clauses can not be used Clauses can be used
3. Program on CRUD operations for PRODUCT table..
Answer:
PRODUCT table description:
PID – number(3) field
PNAME – varchar2(30) field
PCOST – number(5,2) field

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

Statement stmt = con.createStatement();


// depends on the question use the following strings
appropriately
// String s1="INSERT into product
values(118,'pen drive',97.98)";
//String s1 = "DELETE FROM PRODUCT WHERE PID= 115";
String s1 = "UPDATE product SET PCOST =
48.90 WHERE PID=110";

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

ResultSet rs=stmt.executeQuery("select * from product


where PID > 115");
// use any one of the above statements depending on the
question
while(rs.next())
{
//
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getDouble(3));
}
con.close();
stmt.close();
}
}
4. Program on CRUD operations for EMPLOYEE table..
Answer:
EMPLOYEE table description:
EID – number(4) field
ENAME – varchar2(20) field
ESAL – number(8,2) field
Program:
import java.sql.*;
class DBCRUD_EMPLOYEE{
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");
// 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

ResultSet rs=stmt.executeQuery("select * from EMPLOYEE


where EID > 1115");
// use any one of the above statements depending on the
question
while(rs.next())
{
//
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getDouble(3));
}
con.close();
stmt.close();

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

Statement stmt = con.createStatement();


// depends on the question use the following strings
appropriately

// updating Third record where its PID = 103


String s1 = "UPDATE product SET PCOST =
48.90 WHERE PID=103";

int n1 = stmt.executeUpdate(s1);
System.out.println("Records effected:" + n1);
con.commit();

// Deleting fourth record where its PID = 104


String s2 = "DELETE FROM PRODUCT WHERE PID= 104";
int n2 = stmt.executeUpdate(s1);
System.out.println("Records effected:" + n2);

// printing all the records after performing above two


tasks.
ResultSet rs=stmt.executeQuery("select
* from product");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getDouble(3));
}
con.close();
stmt.close();
} }
6. Program on scrollable result set.
Answer:
import java.sql.*;

public class ScrollableResultSet1 {

public static void main(String[] args) throws


Exception {

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

ResultSet rs = st.executeQuery("select * from


product");
System.out.println("RECORDS IN THE TABLE...");
while (rs.next()) {
System.out.println(rs.getInt(1) + " -> " +
rs.getString(2)+" -> "+rs.getDouble(3));
}
rs.first();
System.out.println("FIRST RECORD...");
System.out.println(rs.getInt(1) + " -> " +
rs.getString(2)+" -> "+rs.getDouble(3));
rs.absolute(3);
System.out.println("THIRD RECORD...");
System.out.println(rs.getInt(1) + " -> " +
rs.getString(2)+" -> "+rs.getDouble(3));
rs.last();
System.out.println("LAST RECORD...");
System.out.println(rs.getInt(1) + " -> " +
rs.getString(2)+" -> "+rs.getDouble(3));
System.out.println("LAST BUT ONE RECORD...");
rs.previous();
System.out.println(rs.getInt(1) + " -> " +
rs.getString(2)+" -> "+rs.getDouble(3));
rs.relative(-2);
System.out.println(rs.getInt(1) + " -> " +
rs.getString(2)+" -> "+rs.getDouble(3));

//System.out.println(rs.getInt(1) + " -> " +


rs.getString(2)+" -> "+rs.getDouble(3));
con.close();
}
}
7. Write a java code segment to use PreparedStatement object to insert a
record into product table.
Program :
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@local
host:1521:xe","system","admin");

Statement stmt = con.createStatement();


PreparedStatement pstmt=con.prepareStatement("insert
into product values(?,?,?)");

pstmt.setInt(1,115);//1 specifies the first parameter in


the query
pstmt.setString(2,"MARKER");
pstmt.setDouble(3,19.00);

int i=pstmt.executeUpdate();
System.out.println(i+" records inserted");

ResultSet rs=stmt.executeQuery("select * from product");


while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getDouble(3));
//
System.out.println(rs.getInt("PID")+"
"+rs.getString("PNAME")+" "+rs.getDouble("PCOST"));
}
con.commit();
con.close();

}catch(Exception e){ System.out.println(e);}

}
}

8. Differentiate Statement and PreparedStatement objects


Statement PreparedStatement
1 createStatement() method is used prepareStatement() method is used
2 SQL command contains absolute SQL command will have ‘?’ marks
data
3 Do not have setXXX() methods This has setXXX() methods
4 Useful only at compile time Useful at both compile time and
database operations runtime database operations
Notes On servlets:
9. Life Cycle of a Servlet (Servlet Life Cycle)

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:

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.
As displayed in the above diagram, there are three states of a servlet: new, ready
and end. The servlet is in new state if servlet instance is created. After invoking the
init() method, Servlet comes in the ready state. In the ready state, servlet performs
all the tasks. When the web container invokes the destroy() method, it shifts to the
end state.
10. Architecture of Servlet ?
Answer:

Servlet Architecture

Execution of Servlets :

Execution of Servlets involves the six basic steps:


1. The clients send the request to the web server.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generate the response in the form of
output.
5. The servlet send the response back to the web server.
6. The web server sends the response back to the client and the client browser
displays it on the screen.
11. Why servlets are important ?
Answer:
Today we all are aware of the need of creating dynamic web pages i.e the ones
which have the capability to change the site contents according to the time or are
able to generate the contents according to the request received by the client. If you
like coding in Java, then you will be happy to know that using Java there also exists
a way to generate dynamic web pages and that way is Java Servlet, the need for
server-side extensions.
Servlets are the Java programs that runs on the Java-enabled web server or
application server. They are used to handle the request obtained from the web
server, process the request, produce the response, then send response back to the
web server.

Properties of Servlets :

 Servlets work on the server-side.


 Servlets capable of handling complex request obtained from web server.

12. Differences between GET and POST methods


Answer:
Get vs. Post

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.

3) Get request can be bookmarked. Post request cannot be bookmarked.

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.

13. Servlet program to display “ Hello servlet world “ in the browser.


Program:
import java.io.*;
import javax.servlet.*;

public class First implements Servlet{


ServletConfig config=null;

public void init(ServletConfig config){


this.config=config;
System.out.println("servlet is initialized");
}

public void service(ServletRequest req,ServletResponse


res)
throws IOException,ServletException{
res.setContentType("text/html");

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

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

15. Explain JSP elements like JSP scriplet, declaration, expression,


comment, directive to develop a dynamic web page.
Answer:

Elements of JSP
The elements of JSP have been described below −
The Scriptlet

A scriptlet can contain any number of JAVA language statements, variable or


method declarations, or expressions that are valid in the page scripting language.

Following is the syntax of Scriptlet −

<% code fragment %>


Eg.
<html>
<head><title>Hello World</title></head>

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

Following is the syntax for JSP Declarations −

<%! declaration; [ declaration; ]+ ... %>

Eg.
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
JSP Expression

A JSP expression element contains a scripting language expression that is


evaluated, converted to a String, and inserted where the expression appears in the
JSP file.

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.

Following is the syntax of the JSP comments −

<%-- This is JSP comment --%>

Following example shows the JSP Comments −

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

<%@ directive attribute="value" %>

Eg.

<%@ page ... %>

16. Program on JSP elements ?


Answer:
The following program illustrates some of the JSP Elements to insert a row into
the product table of Oracle database.

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

<%--comment – getting the Connection object --%>


Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localho
st:1521:xe","system","admin");

PreparedStatement pstmt=con.prepareStatement("insert
into product values(?,?,?)");

pstmt.setInt(1,iid);
pstmt.setString(2,name);
pstmt.setDouble(3,dcost);

int i=pstmt.executeUpdate();

out.print(i+ "Insertion Successful");


}catch(Exception e)
{
System.out.println(e);
}
%>
</body>
</html>
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">

Enter num1: <input type="text" name="num1" /><br>


Enter num2: <input type="text" name="num2" /><br><br>

<input type="submit" value="SumJSP" name="Compute"/>


</form>

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

out.println("The sum is:" + sum);


%>

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

Second program : prod.jsp

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

***** END OF NOTES *****

Department of CSE wishes you All the best…

You might also like