SlideShare a Scribd company logo
1 of 83
Download to read offline
1 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Java - Collections Framework
Java - Collections Framework
A collection allows a group of objects to be treated as a single unit. Arbitrary
objects can be stored, retrieved, and manipulated as elements of collection.
This framework is provided in the java.util package.
2 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Classes & Interfaces
Collection Interface
List Interface
• It extends collection interface.
3 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
• The elements in a list are ordered. Each element, therefore, has a position in the
list.
• It can contain duplicates.
• A zero-based index can be used to access the element at the position designated
by the index value. The position of an element can change as elements are
inserted or deleted from the list.
Constructor
LinkedList( )
LinkedList Class
• The LinkedList implements the List interface.
• It provides a linked-list data structure.
• The elements in a linked list are ordered.
• It can contain duplicates.
Constructor
LinkedList()
import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
LinkedList ll = new LinkedList();
ll.add("F");
ll.add("B");
ll.add("D");
System.out.println(ll);
}
}
4 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// remove elements from the linked list
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: " + ll);
// remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: " + ll);
// get and set a value
Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}
This would produce following result:
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
5 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
ArrayList Class
• The ArrayList class implements the List interface.
• ArrayList supports dynamic arrays that can grow as needed.
• The elements in a Array list are ordered.
• It can contain duplicates.
• ArrayList gives better performance as it is non-synchronized.
ArrayList is non-synchronized which means multiple threads can work on
arrayList at the same time
ArrayList gives better performance as it is non-synchronized
Constructor
ArrayList()
import java.util.*;
class ArrayListDemo
{
public static void main(String args[])
{
ArrayList al = new ArrayList();
al.add("F");
al.add("B");
al.add("D");
System.out.println(al);
}
}
ArrayList LinkedList
1) ArrayList internally uses dynamic array to
tore the elements.
LinkedList internally uses doubly linked
list to store the elements.
2) Manipulation with ArrayList is slow
because it internally uses array. If any element
is removed from the array, all the bits are
shifted in memory.
Manipulation with LinkedList is faster
than ArrayList because it uses doubly
linked list so no bit shifting is required in
memory.
3) ArrayList is better for storing and
accessing data.
LinkedList is better for manipulating
data.
6 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
4) ArrayList al = new ArrayList();
LinkedList al = new LinedList();
Vector class
• The class can be used to create a generic dynamic array known as vector that can
hold objects of any type and any number.(Object don’t have to be homogenous)
• The Vector class implements the List interface.
• The elements in a Vector are ordered.
• It can contain duplicates.
• Vector is synchronized. This means if one thread is working on Vector, no other
thread can get a hold of it.
• Vector operations gives poor performance as they are thread-safe
Constructor
Vector( )
import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
Vector v = new Vector();
v.add("F");
v.add("B");
v.add("D");
System.out.println(v);
}
}
Iterator
Iterator is an interface available in Collection framework in java.util package. It is a Java
Cursor used to iterate a collection of objects.
Iterator is interface enables you to cycle through a collection, obtaining or removing
elements.
7 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
The Methods Declared by Iterator:
SN Methods with Description
1
boolean hasNext( )
Returns true if there is next elements. Otherwise, returns false.
2
Object next( )
Returns the next element.
3
Void remove( )
Removes the current element.
import java.util.*;
class IteratorDemo
{
public static void main(String args[])
{
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
System.out.print(“Display element using iterator” );
Iterator itr = al.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element );
}
}
}
ListIterator
ListIteratoris interface that extends Iterator to allow bidirectional traversal of a list,
and the modification of elements.
The Methods Declared by ListIterator:
SN Methods with Description
1
Void add(Object obj)
It add object
8 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
2
boolean hasNext( )
Returns true if there is a next element. Otherwise, returns false.
3
boolean hasPrevious( )
Returns true if there is a previous element. Otherwise, returns false.
4
Object next( )
Returns the next element. A NoSuchElementException is thrown if there is not a
next element.
5
int nextIndex( )
Returns the index of the next element. If there is not a next element, returns the size
of the list.
6
Object previous( )
Returns the previous element. A NoSuchElementException is thrown if there is not a
previous element.
7
int previousIndex( )
Returns the index of the previous element. If there is not a previous element, returns
-1.
8
Void remove( )
Removes the current element from the list.
9
Void set(Object obj)
Set obj to the current element.
import java.util.*;
class ListIteratorDemo
{
public static void main(String args[])
{
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
System.out.print(“Display next element using listiterator” );
ListIterator itr = al.iterator();
while(itr.hasNext())
{
9 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Object element = itr.next();
System.out.print(element );
}
System.out.print(“Display previous element using listiterator” );
while(itr.hasPrevious())
{
Object element = itr.previous();
System.out.print(element + " ");
}
}
}
ListIterator Iterator
ListIterator is interface
that extends Iterator to
allow bidirectional
traversal of a list, and the
modification of elements
Iterator is interface
enables you to cycle
through a collection,
obtaining or
removing elements
It can traverse in both the
directions (forward and
Backward).
It can traverse in
only forward
direction using
Iterator
It can use ListIterator to
traverse List only.
Iterator is used for
traversing List and
Set both.
It can add element during
traversing a list using
ListIterator.
It can not add
element during
traversing a list
using Iterator.
It can obtain indexes at
any point of time while
traversing a list using
ListIterator
It cannot obtain
indexes while using
Iterator.
Methods of ListIterator:
• add(obj)
• hasNext()
• hasPrevious()
• next()
• nextIndex()
• previous()
• previousIndex()
• remove()
• set(obj)
Methods of Iterator:
• hasNext()
• next()
• remove()
10 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Enumeration Interface
The Enumeration interface defines the methods by which you can enumerate (obtain one
at a time) the elements in a collection of objects.
import java.util.*;
class Enumeration
{
public static void main(String args[])
{
Enumeration d;
Vector v = new Vector();
v.add("C");
v.add("A");
v.add("E");
d=v.elements();
while (d.hasMoreElements())
{
System.out.println(d.nextElement());
}
}
}
Set Interface
• It extends collection interface
• It does not contain duplicate
SortedSet Interface
The SortedSet interface extends Set and declares the behavior of a set sorted in
ascending order.
TreeSet Class
• It implements SortedSet interface that uses a tree for storage.
• Objects are stored in sorted, ascending order.
• Access and retrieval times are quite fast, which makes TreeSet an excellent choice
when storing large amounts of sorted information that must be found quickly.
11 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Constructor
TreeSet( )
TreeSet(Comparator comp)
import java.util.*;
class TreeSetDemo {
public static void main(String args[]) {
// Create a tree set
TreeSet ts = new TreeSet();
// Add elements to the tree set
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.println(ts);
}
}
This would produce following result:
[A, B, C, D, E, F]
Java Comparator interface
• It is used to order the objects of user-defined class.
• This interface contains 2 methods compare(Object obj1,Object obj2) or
equals(Object element).
int compare(Object obj1, Object obj2)
obj1 and obj2 are the objects to be compared. This method returns zero if the
objects are equal. It returns a positive value if obj1 is greater than obj2.
Otherwise, a negative value is returned.
• It provides multiple sorting sequence i.e. you can sort the elements on the basis of
any data member, for example rollno, name, age or anything else.
12 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
import java.util.*;
class Tree implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
return s2.compareTo(s1);
}
public static void main(String args[])
{
// Create a tree set
TreeSet ts = new TreeSet(new Tree());
// Add elements to the tree set
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.println(ts);
}
}
o/p
F E D C B A
HashSet Class
• HashSet implemets the Set interface.
• It creates a collection that uses a hash table for storage
• It does not have duplicate
• It displaying object at any order.
Constructor
HashSet( )
import java.util.*;
class HashSetDemo {
public static void main(String args[])
13 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
{
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
o/p
[A, F, E, D, C, B]
LinkedHashSet Class
• LinkedHashSet class implemets the Set interface.
• It used linked list & hash table for storage
• It does not have duplicate
• It displaying insertion order.
Constructor
LinkedHashSet( )
import java.util.*;
class Lh
{
public static void main(String args[])
{
// create a hash set
LinkedHashSet hs = new LinkedHashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}
o/p
14 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
[B,A,D,E,C,F]
Map Interface
• A Map interface defines mappings from keys to values. The <key, value> pair is
called an entry in a Map.
• A Map does not allow duplicate keys, in other words, the keys are unique.
Methods
• Object put(Object key, Object value)
15 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
• Object get(Object key)
• Object remove(Object key)
• void putAll(Map t)
• boolean containsKey(Object key)
• boolean containsValue(Object value)
• int size()
• boolean isEmpty()
• void clear()
TreeMap Class
• The TreeMap class implements the Map interface by using a tree.
• A TreeMap provides an efficient means of storing key/value pairs in sorted order,
and allows rapid retrieval.
• Its elements will be sorted in ascending key order.
• It contains only unique key.
Constructor
TreeMap()
import java.util.*;
class TreeMapDemo
{
public static void main(String args[])
{
TreeMap tm = new TreeMap();
tm.put("Amol", new Float(55.55));
tm.put("Punit", new Float(66.33));
System.out.println(tm);
}
}
16 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
HashMap Class
• The HashMap class uses a hash table to implement the Map interface.
• It display object any order.
• It contains only unique key.
Constructor
HashMap( )
import java.util.*;
class HashMapDemo
{
public static void main(String args[])
{
HashMap tm = new HashMap();
tm.put("Amol", new Float(55.55));
tm.put("Punit", new Float(66.33));
System.out.println(tm);
}
}
LinkedHashMap Class
1.This class implement the Map interface.
2.It display object insertion order.
3.It contains only unique key.
Constructor
LinkedHashMap( )
import java.util.*;
class Hd
{
public static void main(String args[])
{
17 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
LinkedHashMap tm = new LinkedHashMap();
tm.put("Amol", new Float(55.55));
tm.put("Punit", new Float(66.33));
System.out.println(tm);
}
}
Hashtable
• Hashtable contains values based on the key. It implements the Map interface.
• It contains only unique key.
• It is synchronized.
Constructor
Hashtable()
import java.util.*;
class HashDemo
{
public static void main(String args[])
{
Hashtable tm = new Hashtable();
tm.put("Amol", new Float(55.55));
tm.put("Punit", new Float(66.33));
System.out.println(tm);
}
}
18 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
MultiThreading
MuliProcessing
• This allows many processes to run simultaneously.
• Process is a running instance of the program. i.e. an operating system
process.
CPU time is shared between different processes.
• OS provides context switching mechanism, which enables to switch
between the processes.
• Program’s entire contents (e.g. variables, global variables, functions) are
stored separately in their own context.
Example:- MS-Word and MS-Excel applications running simultaneously. (or
any two applications for that matter)
MultiThreading
• It allows many tasks within a program (process) to run simultaneously.
• Each such task is called as a Thread.
• Each Thread runs in a separate context.
• Each Thread has a beginning , a body,& an end
• Example:- Lets take a typical application like MS-Word. There are various
independent tasks going on, like displaying GUI, auto-saving the file, typing in
text, spell-checking, printing the file contents etc…
Thread
• Thread is an independent sequential path of execution within a program. i.e.
separate call stack.
19 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
• Many threads run concurrently within a program.
• At runtime, threads in a program exist in a common memory space and can share
both data and code.
Start Start Start
Switching switching
How To Thread Created?
Threads can be achieved in one of the two ways –
1 Extending java.lang.Thread class.
2 Implementing java.lang.Runnable interface
1.Using Extending java.lang.Thread class.
To Define a class that extends Thread class & override its run() with code
required by thread.
Steps as Follows
1.Declare the class as extending the Thread class
Class A extends Thread
{
-----------
}
Where A is name of thread.
2.Implement the run() method.i.e Responsible for executing of code the thread will
execute.
public void run()
{
-------
Main
Thread
Threads
A
Threads
B
Threads
C
20 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
-----
}
3.Create a thread object & call the start() method to initiate the thread execution.
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("n From Thread A:i="+i);
}
System.out.println("n Exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("n From Thread B:j="+j);
}
System.out.println("n Exit from B");
}
}
class ThreadTest
{
public static void main(String args[])
{
A t1=new A();
//new A().start();
t1.start();//invoke run method
21 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
B t2=new B();
t2.start();//invoke run method
}
}
2.Implementing java.lang.Runnable interface
Steps as follows
1.Declare the class as implementing the runnable interface.
2.Implement the run() method.
3.It create a thread which is pass a parameter as a thread class object which
implemetns “runnable” interface
4.Call the thread’s start() method to run the thread.
class A implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("tThread A :"+i);
}
System.out.println("End of thread A");
}
}
class RunnableTest
{
public static void main(String args[])
{
A r=new A();
Thread tx=new Thread(r);
tx.start();
System.out.println("End of main thread");
}
}
22 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Life Cycle of thread
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
1 Newborn state
It create a thread object, the thread is born & is said to be newborn state.
2. Runnable state
It means thread is ready for execution & is waiting for the availability of processor.
The processor of assigning time to threads is known as timing-slicing.
yield
……
Runnable thread
newborn
Running
Runnable
Blocked
Dead
stop
stop
stop
Resume
Notify
Suspend
Sleep
wait
start
yield
Active
Thread
New
Thread
Idle
Thread
23 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
If a thread to leave control to another thread of equal priority before its turn
comes,it can done by using yield() method
3.Running state
It means that the processor has given its time to the thread for its execution.
The thread runs until it leaves control on its own or it is preempted by higher priority
thread.A running thread my leaves its control in one of the following
1.suspend():
It has been suspended using suspend() method. A suspended thread can be received by
using resume() method.
Resume()
Running Runable Suspended
2.sleep()
It can put thread to sleep for a specified time period using sleep(t) method.(t is time
milliseconds).
Sleep(t)
After t
Running Runable Sleeping
3.wait()
It has been hold to wait until some event occurs. This is done using wait() method. The
thread can be scheduled to run again using notify() method.
Wait Notify()
Running Runable waiting
4.Blocked state
24 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
A thread is said to be blocked when it is prevented from entering into runnable state &
subsequently the running state. This happens when the thread is suspended,sleeping or
waiting.
A blocked thread is considered “not runnable” but not dead .
5.Dead state
Every Thread has a life cycle. A running threads ends its life when it has completed
executing its run() method.
Display the main Thread.
public static Thread currentThread()
Returns a reference to the currently executing thread object.
class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t.getName());
try
{
for(int n = 6; n > 0; n--)
{
System.out.println(n);
}
}
catch (Exception e)
{
}
25 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
}
}
Threads priority
Each thread is assigned a priority, which affects the order it is scheduled for running.
i.e Threads are assigned priorities that the thread scheduler can use to determine how the
threads will be scheduled.
The following static final integer constants are defined in the Thread class:
• MIN_PRIORITY =0( Lowest Priority)
• NORM_PRIORITY =5 (Default Priority)
• MAX_PRIORITY =10 (Highest Priority)
setPriority():It can modify a thread’s priority at any time after its creation using the
setPriority() method.
Threadname.setPriority(int number)
Where number is priority number.
getPriority(): It retrieve the thread priority value
class A extends Thread
{ public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("n From Thread A:i="+i);
}
System.out.println("n Exit from A");
}
}
class B extends Thread
{ public void run()
{
for(int j=1;j<=5;j++)
{ System.out.println("n From Thread B:j="+j);
}
System.out.println("n Exit from B");
}
}
26 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
class C extends Thread
{ public void run()
{
for(int k=1;k<=5;k++)
{ System.out.println("n From Thread C:k="+k);
}
System.out.println("n Exit from C");
}
}
public class ThreadPriority
{ public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t3.setPriority(Thread.MAX_PRIORITY);
t1.setPriority(Thread.MIN_PRIORITY);
t3.start();
t1.start();
t2.start();
}
}
Threads Method
1. isAlive() method:
Returns true if the thread is alive, otherwise false.
public final boolean isAlive()
2.join() method:
The join() method waits for a thread to die.(A thread to wait until the completion
of another thread before continue.
public void join()
class A extends Thread
{
public void run()
{
System.out.println("A Thread");
27 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
}
}
class B extends Thread
{
public void run()
{
System.out.println("B Thread");
}
}
class ThreadTest
{
public static void main(String args[])
{
try
{
A t1=new A();
t1.start();//invoke run method
B t2=new B();
t2.start();//invoke run method
t1.join();
t2.join();
System.out.println("Main parent thread");
System.out.println("A thread "+t1.isAlive());
System.out.println("B thread "+t2.isAlive());
}
catch(Exception e)
{
System.out.println("error"+e);
}
}
}
28 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
What is mean by Synchronization?
When two or more threads need access to a shared resource, they need to ensure that
the resource will be used by only one thread at a time.
This process by which this is achieved is called Synchronization.
This is the general form of the synchronized statement:
synchronized method1 ()
{
// statements to be synchronized
}
When it declare a method synchronized, Java creates a “Monitor” & hands it over
to the thread that calls the method first time. As long as the thread holds the monitor, no
other thread can enter the synchronized section of code.
When thread has completed its work of using synchronized method(or block of
code),it will hand over the monitor to the next thread that is ready to use same resource.
Using synchronized
class Callme
{
synchronized void call(String msg)
{
System.out.print("[" + msg);
System.out.println("]");
}
}
class Caller implements Runnable
{
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
29 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
t = new Thread(this);
t.start();
}
public void run()
{
target.call(msg);
}
}
public class Synch
{
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
}
}
Java - Interthread Communication
When multiple threads are running in an application, it become necessary for the threads
to communicate(talk) with each other such communication called as interthread
communication.
The thread can communicate by either sharing data or indicating when a specific activity
has completed.
Methods for interthread communication
wait( ): Causes the current thread to wait until another thread invokes the notify().
Notify( ): Wakes up a single thread that is waiting on this object's monitor.
notifyAll( ): Wakes up all the threads that called wait( ) on the same object.
Join():The join() method waits for a thread to die.(A thread to wait until the completion
of another thread before continue.
Thread Method & Description
static Thread currentThread()
This method returns a reference to the currently
executing thread object.
String getName()
30 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
This method returns this thread's name.
int getPriority()
This method Returns this thread's priority.
boolean isAlive()
This method tests if this thread is alive.
void join()
Waits for this thread to die.
void run()
If this thread was constructed using a separate
Runnable run object, then that Runnable object's
run method is called; otherwise, this method does
nothing and returns
void setName(String name)
This method changes the name of this thread to be
equal to the argument name.
void setPriority(int newPriority)
This method changes the priority of this thread.
static void sleep(long millis)
This method causes the currently executing thread
to sleep (temporarily cease execution) for the
specified number of milliseconds, subject to the
precision and accuracy of system timers and
schedulers.
void start()
This method causes this thread to begin execution;
the Java Virtual Machine calls the run method of
this thread.
static void yield()
This method causes the currently executing thread
object to temporarily pause and allow other
threads to execute.
31 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
DATABASE PROGRAMING
What is JDBC?
• It is Java Database Connectivity technology.
• This technology is an API(Application Programming Interface) for the java
programming language that define how a client may access a database.
• It provides methods for querying and updating data in database.
What are JDBC Drivers?
It is a software component enabling a java application to interact with a database.
JDBC Architecture
JDBC Driver Types
JDBC drivers are divided into four types or levels. The different types of jdbc drivers
are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)
Type 1 JDBC Driver
JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the
ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended
only for experimental use or when no other alternative is available.
32 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Type 1: JDBC-ODBC Bridge
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database's
ODBC drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not
portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC
driver, then to the database, and this applies even in the reverse process. They are
the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
Type 2 JDBC Driver
Native-API/partly Java driver
The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC
calls into database-specific calls i.e. this driver is specific to a particular database. Some
33 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will
have oracle native api.
Type 2: Native api/ Partly Java Driver
Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better
performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less
than that of Type 1 and also it uses Native api which is Database specific.
Disadvantage
1. Native API must be installed in the Client System and hence type 2 drivers cannot
be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability
issue.
3. If we change the Database we have to change the native api as it is specific to a
database.
4. Usually not thread safe.
Type 3 JDBC Driver
All Java/Net-protocol driver
34 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Type 3 database requests are passed through the network to the middle-tier server. The
middle-tier then translates the request to the database. If the middle-tier server can in turn
use Type1, Type 2 or Type 4 drivers.
Type 3: All Java/ Net-Protocol Driver
Advantage
1. This driver is server-based, so there is no need for any vendor database library to
be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and
scalability.
4. The net protocol can be designed to make the client JDBC driver very small
and fast to load.
5. The type 3 driver typically provides support for features such as caching
(connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.
Disadvantage
It requires another server application to install and maintain. Traversing the recordset
may take longer, since the data comes through the backend server.
35 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Type 4 JDBC Driver
Native-protocol/all-Java driver
The Type 4 uses java networking libraries to communicate directly with the database
server.
Type 4: Native-protocol/all-Java driver
Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are completely
written in Java to achieve platform independence and eliminate deployment
administration issues. It is most suitable for the web.
2. . Number of translation layers is very less i.e. type 4 JDBC drivers don't have to
translate database requests to ODBC or a native connectivity interface or to pass
the request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these
drivers can be downloaded dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database.
JDBC Versions
1). The JDBC 1.0 API.
2). The JDBC 1.2 API.
36 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
3). The JDBC 2.0 Optional Package API.
4). The JDBC 2.1 core API.
5) The JDBC 3.0 API.
6) The JDBC 4.0 API.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database
access.
1. Two-tier
In such an architecture, the Java application communicates directly with the data source
(or database). The database may reside on the same machine or may be on another
machine to which the clinet machine needs to be connected through a network
2. Three-tier
In such an architecture, the client machine will send the database access statements to the
middleware, which will then send the statements to the database residing on the third tier
37 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
of the architecture, which is normally referred to as the back end. The statements will be
processed there and the result be returned back to the client through the middle tier. This
approach will have all the advantages associated with the 3-tier architecture, such as
better maintainability, easier deployment, scalability, etc.
JDBC CLASSES AND INTERFACE
The java.sql package contains several classes and interface which are used to
communicate with the
database
38 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
BASIC JDBC STEPS
1.Load the driver
Loading Database driver is very first step towards making JDBC connectivity with the
database. It is necessary to load the JDBC drivers before attempting to connect to the
database.
39 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Syntax
Class.forName(drivername).
e.g Class.forName("org.postgresql.Driver");
2.Establishing Connection
After loading driver, now Establishing Connection with the database with user name and
password.
Syntax
con = DriverManager.getConnection(url+db, user, pass);
con=DriverManager.getConnection("jdbc:postgresql://localhost:5432
/ty");
3.Create a statement object:
There are three basic types of SQL statements used in the JDBC API:
1.Statement:A Statement is interface.It represents a general SQL statement without
parameters. The method createStatement() creates a Statement object.
Eg
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from student ");
2.Prepared Statement: A PreparedStatement is a interface.It represents a precompiled
SQL statement, with or without parameters. It is used for SQL commands that need
to be executed repeatedly.
Eg 1
PreparedStatement ps = con.prepareStatement(“select * from student where
rollno=?”);
ps.setString(1,1);
ResultSet rs = stmt.executeQuery();
Eg2
PreparedStatement ps = con.prepareStatement(“insert into student values(?,?,?)”);
ps.setInt(1,1);
ps.setString(2,’amol’);
40 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
ps.setFloat(3,66.55f);
ResultSet rs = ps.executeUpdate();
3.CallableStatement - CallableStatement is interface. It is used to execute SQL stored
procedures
Eg
CallableStatement cstmt=con.prepareCall(“call student”);
4.Execute a query
An SQL statement can either be a query that return result or operation that manipulates
the database
1.ResultSet executeQuery(String sql):
It is used for statements that return an output result(for only select query)
2.int executeUpdate(String sql): Returns an integer representing the number of rows
affected by the SQL statement. (For only INSERT, DELETE, or UPDATE SQL
statements).
5.Process a query:
ResultSet provides access to a table of data generated by executing a Statement. The table
rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row
of data. The next() method is used to successively step through the rows of the tabular
results.
To access these values, there are getXXX() methods where XXX is a type for example,
getString(), getInt(),getFloat etc.
There are two forms of the getXXX methods:
i. Using columnName: getXXX(String columnName)
ii. Using columnNumber: getXXX(int columnNumber)
Example
rs.getString(“sname”));
rs.getString(1);
41 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
6.Close the connections
After all work is done, it is important to close the connection. But before the connection
is closed , close the ResultSet and the statement objects.
e.g
rs.close();
stmt.close();
con.close();
ResultSet Scroll Types
The scroll type indicates how the cursor moves in the ResultSet. The concurrency type
affects concurrent access to the resultset. The types are given in the table below.
Scroll Type
TYPE_FORWARD_ONLY :
The result set is not scrollable.
TYPE_SCROLL_INSENSITIVE:
The result set is scrollable but not sensitive to database changes.
TYPE_SCROLL_SENSITIVE:
The result set is scrollble and sensitive to database changes.
Concurrency Type
CONCUR_READ_ONLY The result set cannot be used to update the
database.
CONCUR_UPDATABLE The result set can be used to update the
database.
42 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Note: store postgres.jar file into following path /usr/lib/jvm/java/jre/lib/ext
1.USING SELECT STATEMENT
import java.sql.*;
public class Post
{
43 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
public static void main(String args[])
{
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c=DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat
");
Statement stmt = c.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
{
System.out.println("Rollno"+rs.getInt(1));
System.out.println("Name"+rs.getString(2));
System.out.println("Per"+rs.getFloat(3));
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
2.USING INSERT STATEMENT
import java.sql.*;
import java.io.*;
public class Post
{
public static void main(String args[])
{
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c =
DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat");
Statement stmt = c.createStatement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Roll no: ");
int rno=Integer.parseInt(br.readLine());
System.out.println("Enter Name: ");
String name=br.readLine();
44 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
System.out.println("Enter percentage: ");
float per=Float.parseFloat(br.readLine());
String sql="insert into student values("+rno+",'"+name+"',"+per+")";
int k=stmt.executeUpdate(sql);
if(k>0)
System.out.println("Insert "+k);
else
System.out.println("Insert "+k);
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
{
System.out.println("rollno"+rs.getInt(1));
System.out.println("name"+rs.getString(2));
System.out.println("Percentage"+rs.getFloat(3));
}
rs.close();
stmt.close();
c.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
3.USING UPDATE STATEMENT
import java.sql.*;
import java.io.*;
public class Post
{
public static void main(String args[])
{
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c =
DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat");
Statement stmt = c.createStatement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Roll no: ");
int rno=Integer.parseInt(br.readLine());
45 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
System.out.println("Enter Name: ");
String name=br.readLine();
System.out.println("Enter percentage: ");
float per=Float.parseFloat(br.readLine());
String sql="update student set name='"+name+"'"+","+"per="+per+" "+"where
rollno="+rno;
int k=stmt.executeUpdate(sql);
if(k>0)
System.out.println("Insert "+k);
else
System.out.println("Insert "+k);
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
{
System.out.println("rollno"+rs.getInt(1));
System.out.println("name"+rs.getString(2));
System.out.println("Percentage"+rs.getDouble(3));
}
rs.close();
stmt.close();
c.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
4. USING DELETE STATEMENT
import java.sql.*;
import java.io.*;
public class Post
{
public static void main(String args[])
{
Connection c = null;
try {
46 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Class.forName("org.postgresql.Driver");
c =
DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat");
Statement stmt = c.createStatement();
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter Roll no: ");
int rno=Integer.parseInt(br.readLine());
String sql="delete from student where rollno="+rno;
int k=stmt.executeUpdate(sql);
if(k>0)
System.out.println("Delete "+k);
else
System.out.println("Delete "+k);
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
{
System.out.println("rollno"+rs.getInt(1));
System.out.println("name"+rs.getString(2));
System.out.println("Percentage"+rs.getFloat(3));
}
rs.close();
stmt.close();
c.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Navigate the Database
import java.sql.*;
class stud3
{
public static void main( String args[])
{
try
{
Connection c=null;
Class.forName("org.postgresql.Driver");
47 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
C=DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","
redhat");
//Statement stmt=c.createStatement();
Statement stmt = c.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from student";
ResultSet rs= stmt.executeQuery(sql);
System.out.println("Display record next");
while( rs.next())
{
System.out.println( rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getDouble(3));
}
System.out.println("Display record previous");
while( rs.previous())
{
System.out.println( rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getDouble(3));
}
System.out.println("Display first record ");
rs.first();
System.out.println( rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getDouble(3));
System.out.println("Display last record ");
rs.last();
System.out.println( rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getDouble(3));
rs.close();
stmt.close();
c.close();
}
catch(Exception e)
{
System.out.println("error"+e);
}
}
}
METADATA
48 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Metadata means information about data. Some application need to discover information
about the tables, result set structure or underlying database dynamically. JDBC can
provide additional information about the structure of a database and its tables.
DatabaseMetadata Interface
MetaData interface provides methods to get meta data of a database such as database
product name, database product version, driver name, name of total number of tables,
name of total number of views etc.
How to get the object of DatabaseMetaData:
The getMetaData() method of Connection interface returns the object of
DatabaseMetaData. Syntax:
public DatabaseMetaData getMetaData()throws SQLException
Methods:
o public String getDriverName()throws SQLException: it returns the name of
the JDBC driver.
o public String getDriverVersion()throws SQLException: it returns the version
number of the JDBC driver.
o public String getUserName()throws SQLException: it returns the username of
the database.
o public String getDatabaseProductName()throws SQLException: it returns the
product name of the database.
o public String getDatabaseProductVersion()throws SQLException: it returns
the product version of the database.
o public ResultSet getTables(String catalog, String schemaPattern, String
tableNamePattern, String[] types)throws SQLException: it returns the
description of the tables of the specified catalog. The table type can be TABLE,
VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
Example1:
DatabaseMetaData dbmd=con.getMetaData();
System.out.println("Driver Name: "+dbmd.getDriverName());
System.out.println("Driver Version: "+dbmd.getDriverVersion());
System.out.println("UserName: "+dbmd.getUserName());
System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());
49 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Example 2:
To print no. of tables
DatabaseMetaData dbmd=con.getMetaData();
String table[]={"TABLE"};
ResultSet rs=dbmd.getTables(null,null,null,table);
while(rs.next()){
System.out.println(rs.getString(3));
ResultSetMetaData
ResultSetMetaData interface
The ResultSetMetaData interface provides information about the structure of a particular
ResultSet
How to get the object of ResultSetMetaData:
The getMetaData() method of ResultSet interface returns the object of
ResultSetMetaData. Syntax:
public ResultSetMetaData getMetaData()throws SQLException
Method Description
public int getColumnCount()throws
SQLException
it returns the total number of
columns in the ResultSet object.
public String getColumnName(int
index)throws SQLException
it returns the column name of the
specified column index.
public String getColumnTypeName(int
index)throws SQLException
it returns the column type name
for the specified index.
public String getTableName(int index)throws
SQLException
it returns the table name for the
specified column index.
Example:
PreparedStatement ps=con.prepareStatement("select * from stud");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1)
);
50 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Transaction
Method Description
void setAutoCommit(boolean
status)
It is true bydefault means each transaction is
committed bydefault.
void commit() commits the transaction.
void rollback() cancels the transaction.
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
con.commit();
Savepoints
The save point is a logical position in a transaction up to which we can rollback the
transaction. When the save point is placed in the middle of the transaction, the logics
placed before the save point will be committed and the logics placed after the save point
will be rolled back.
Statement st = con.createStatement ();
con.setAutoCommit (false);
st.executeUpdate ("insert into college values (‘am’, ‘mumbai’, 1009)");
Savepoint svpt = con.setSavepoint ("mysp");
st.executeUpdate ("update college set cname= ‘sm’ where code=1001");
st.executeUpdate ("insert into college values (‘mit’, ‘Bhubaneswar’, 1008)");
con.rollback (svpt);
con.commit ();
51 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
NETWORKING
Networking Basics
Protocol
A protocol is a set of rules and standards for communication.
1. IP (Internet Protocol): is a network layer protocol that breaks data into small packets
and routes them using IP addresses.
2. TCP (Transmission Control Protocol): This protocol is used for connection-oriented
communication between two applications on two different machines. It is most reliable
and implements a connection as a stream of bytes from source to destination.
3.UDP (User Datagram Protocol): It is a connection less protocol
and used typically for request and reply services. It is less reliable but faster than TCP.
Addressing
1. MAC Address: Each machine is uniquely identified by a physical address, address of
the network interface card. It is 48-bit address represented as 12 hexadecimal characters:
For Example: 00:09:5B:EC:EE:F2
2.IP Address: It is used to uniquely identify a network and a machine in the network.
Itis referred as global addressing scheme. Also called as logical address. Currently used
type of IP addresses is: Ipv4 – 32-bit address and Ipv6 – 128-bit address.
For Example:
Ipv4 – 192.168.16.1
Ipv6 – 0001:0BA0:01E0:D001:0000:0000:D0F0:0010
3.Port Address: It is the address used in the network to identify the application on the
network.
Domain Name Service (DNS)
It is very difficult to remember the IP addresses of machines in a network. Instead, we
can identify a machine using a “domain name” which is character based naming
mechanism. Example: www.google.com. The mapping between the domain name and the
IP address is done by a service called DNS.
URL
A URL (Uniform Resource Locator) is a unique identifier for any resource located on the
Internet. The syntax for URL is given as:
<protocol>://<hostname>[:<port>][/<pathname>][/<filename>[#<section>]]
52 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Sockets
Def:A socket represents the end-point of the network communication.
It provides a simple read/write interface and hides the implementation details network
and transport layer protocols. It is used to indicate one of the two end-points of a
communication link between two processes. When client wishes to make connection to a
server, it will create a socket at its end of the communication link.
The socket concept was developed in the first networked version of UNIX developed at
the University of California at Berkeley. So sockets are also known as Berkeley Sockets.
Ports
A port number identifies a specific application running in the machine.
A port number is a number in the range 1-65535.
Reserved Ports: TCP/IP protocol reserves port number
in the range 1-1023 for the use of
specified standard services, often referred to as “well-known” services.
e.g
FTP :21
HTTP:80
SNMP:161
SMTP:25
The java.net Package
The java.net package provides classes and interfaces for implementing network
applications such as sockets, network addresses, Uniform Resource Locators (URLs) etc.
some important interfaces, classes and exceptions as follows :
InetAddress Class
Java InetAddress class represents an IP address. The java.net.InetAddress class provides
methods to get the IP of any host name for example www.google.com,
www.facebook.com etc.
Method Description
public static InetAddress getByName(String
host) throws UnknownHostException
it returns the instance of InetAddress
containing LocalHost IP and name.
public static InetAddress getLocalHost() throws
UnknownHostException
it returns the instance of InetAdddress
containing local host name and address.
public String getHostName() it returns the host name of the IP
address.
public String getHostAddress() it returns the IP address in string format.
URL Class
The Java URL class represents an URL. URL is an acronym for Uniform Resource
Locator. It points to a resource on the World Wide Web.
The class has the following constructors:
53 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
1. URL(String url_str): Creates a URL object based on the string parameter. If the
URL cannot be correctly parsed, a MalformedURLException will be thrown.
2. URL(String protocol, String host, String path): Creates a URL object with the
specified protocol, host and path.
3. URL(String protocol, String host, int port, String path): Creates a URL object
with the specified protocol, host, port and file path.
4. URL(URL urlObj, String urlSpecifier): Allows you to use an existing URL as a
reference context and then create a new URL from that context.
Methods
Method Description
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the Port Number of the URL.
public String getFile() it returns the file name of the URL.
public URLConnection
openConnection()
it returns the instance of URLConnection i.e.
associated with this URL.
URLConnection Class
The Java URLConnection class represents a communication link between the URL and
the application. This class can be used to read and write data to the specified resource
referred by the URL.
public class URLConnectionExample
{
public static void main(String[] args)
{
try
{
URL url=new URL("http://www.visionacademe.com/java-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1)
{
System.out.print((char)i);
}
}catch(Exception e)
54 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
{
System.out.println(e);
}
}
}
Connection Oriented Communication
Using Socket Java performs the network communication. Sockets enables to transfer data
through certain port. Socket class of Java makes it easy to write the socket program
Sockets are broken into two types:
1. Datagram sockets (UDP Socket)
1.A Datagram socket uses user datagram protocol (UDP) to send datagrams (self
contained units of information) in a connectionless manner.
2.This method does not guarantee delivery of the datagram.
3.The advantage is the datagram sockets require relatively few resources and so
communication is faster.
4.Typically request-reply types of application use datagram socket.
5.Java uses java.net.DatagramSocket class to create datagram socket. The
java.net.DatagramPacket represents a datagram.
2. Stream Socket (TCP Socket)
1.A stream socket is a “connected” socket through which data is transferred continuously.
2. It use TCP to create a connection between the client and server. TCP/IP sockets are
used to implement reliable, bidirectional, persistent, point to point, stream-based
connection between hosts on the internet.
3. The benefit of using a stream socket is the communication is reliable. because once
connected ,the communication link is available till it is disconnected. So data
transmission is done in real-time and data arrives reliably in the same order that it was
sent. however this requires more resource. Application like file transfer require a reliable
communication. For such application stream sockets are better.
4. Java uses java.net.Socket class to create stream socket for client and
java.net.ServerSocket for server.
55 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Difference between Datagram and Stream socket
1.DatagramSocket is for sending UDP datagram
Stream socket is used for sending TCP packets.
2. DatagramSocket is a packet based socket.
Stream socket is a byte oriented socket.
3. DatagramSocket are unreliable. They may be dropped ,duplicate and delivered out of
order.
Stream socket is reliable ,if datas are lost on the way, TCP automatically re-sends.
4. DatagramSocket have less overheads and so faster.
Stream sockets require more overhead and are slower.
5.Application which use datagram sockets are request-reply type of application such as
DNS lookups,PING and SMTP.
Stream sockets are used for application like file transfer which require reliability.
ServerSocket Class
This class is used to create a server that listens for incoming connections from clients. It
is possible for client to connect with the server when server socket binds itself to a
specific port. The various constructors of the ServerSocket class are:
1. ServerSocket(int port): binds the server socket to the specified port number. If 0 is
passed, any free port will be used. However, clients will be unable to access the
service unless notified the port number.
2. ServerSocket(int port, int numberOfClients): Binds the server socket to the
specified port number and allocates sufficient space to the queue to support the
specified number of client sockets.
3. ServerSocket(int port, int numberOfClients, InetAddress address): Binds the
server socket to the specified port number and allocates sufficient space to the queue
to support the specified number of client sockets and the IP address to which this
socket binds
The various methods of this class are:
56 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Method Description
Socket Class
This class is used to represents a TCP client socket, which connects to a server socket and
initiate protocol exchanges. The various constructors of this class are:
1. Socket(InetAddress address, int port): creates a socket connected to the specified
IP address and port. Can throw an IOException.
2. Socket(String host, int port): creates a socket connected to the specified host and
port. Can throw an UnknownHostException or an IOException.
57 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
How to create a server socket
1. Create a ServerSocket object which listen to a specific port.
2. Call the accept() method which accepts client request. This method return the
client socket object.
3. Use the socket object to communication with the client
import java.net.*;
import java.io.*;
public class Server
{
public static void main(String[] ar)
{
try
{
int port = 6666;
ServerSocket ss = new ServerSocket(port);
System.out.println("Waiting for a client...");
Socket socket = ss.accept();
InputStream sin = socket.getInputStream();
DataInputStream in = new DataInputStream(sin);
58 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
String line = null;
while(true)
{
line = in.readUTF();
System.out.println(“Receving line from client : " + line);
System.out.println();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
How to create a client socket
1.Create an object of the socket class using the server names and port as parameter.
2.Communication with the server.
3.Close the socket
//Client
import java.net.*;
import java.io.*;
public class Client
{
public static void main(String[] ar)
{
try
{
int serverPort = 6666;
String address = "127.0.0.1";
InetAddress ipAddress = InetAddress.getByName(address);
Socket socket = new Socket(ipAddress, serverPort);
OutputStream sout = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(sout);
59 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while(true)
{
line = keyboard.readLine();
System.out.println("Sending this line to the server...");
out.writeUTF(line); // send the above line to the server.
out.flush();
System.out.println();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
60 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Servlet
What Web server?
➢ Apache is a very popular server
➢ 66% of the web sites on the Internet use Apache
Apache is:
• Full-featured and extensible
• Efficient
• Robust
• Secure (at least, more secure than other servers)
• Up to date with current standards
• Open source
• Free
What is Tomcat?
Tomcat is the Servlet Engine that handles servlet requests for Apache.
➢Tomcat is a “helper application” for Apache
➢It’s best to think of Tomcat as a “servlet container”
What is servlet?
A servlet is a web component,managed by a container, that generates dynamic
content.
➢ Client sends a request to server
➢ Server starts a servlet
➢ Servlet computes a result for server and does not quit
➢ Server returns response to client
➢ Another client sends a request
➢ Server calls the servlet again
61 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
The Life Cycle of a Servlet
The Servlet API
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when
the first request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet instance.
The init method is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException
4) service method is invoked
The service() method of the Servlet is invoked to inform the Servlet about the client
requests.
This method uses ServletRequest object to collect the data requested by the client.
This method uses ServletResponse object to generate the output content.
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
62 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
5) destroy method is invoked
When a servlet is unloaded by the servlet container, its destroy() method is called.
This step is only executed once, since a servlet is only unloaded once.
public void destroy()
Servlet Package
It includeTwo packages:
▪ javax.servlet
▪ javax.servlet.http
1.The javax.servlet Package
The javax.servlet package contains a number of interfaces and classes that establish
the framework in which servlets operate.
Interface Description
Servlet Declares life cycle methods for a servlet.
ServletConfig Allows servlets to get initialization
parameters.
ServletContext Enables servlets to log events and access
Information about their environment.
ServletRequest Used to read data from a client request.
ServletResponse Used to write data to a client response.
Class Description
GenericServlet Implements the Servlet and ServletConfig
interfaces.
ServletInputStream Provides an input stream for reading
requests from a client.
ServletOutputStream Provides an output stream for writing responses to
a client.
2.javax.servlet.http Package
Interface Description
63 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
HttpServletRequest Enables servlets to read data from an HTTP
request.
HttpServletResponse Enables servlets to write data to an HTTP
response.
HttpSession Allows session data to be read and written.
Class Description
Cookie Allows state information to be stored on a client
machine.
HttpServlet Provides methods to handle HTTP requests and
responses.
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
This method services a GET request
Input is from the HttpServletRequest parameter
Output is via the HttpServletResponse object, which we have named
response
64 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
This method services post request
Input is from the HttpServletRequest parameter
Output is via the HttpServletResponse object, which we have named
response
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B> Hi Vision Academy!");
pw.close();
}
}
How To retrieve value from the component
Using doGet method
<html>
<body>
<center>
<form name="Form1"
method="get"
action="http://localhost:8080/examples/servlets/servlet/GetServlet">
Enter name
<input type=text name=”t”>
<br>
<input type=submit value="Submit">
</body>
</html>
import java.io.*;
65 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String s = request.getParameter("t");
pw.println(s);
pw.close();
}
}
Using doPost method
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlets/servlet/PostServlet">
Enter name
<input type=text name=”t”>
<br>
<input type=submit value="Submit">
</body>
</html>
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PostServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
66 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
String s = request.getParameter("t");
pw.println(s);
pw.close();
}
}
2
<html>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/examples/servlets/servlet/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
HTML-SERVLET COMMUNICATION
1.getParameter():Return the value of named parameter
67 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
2.getParameterValues():Return array of values of named parameter
3.getPArameterNames():Gives the name of parameter
What is a Cookie?
A "cookie" is a small piece of information sent by a web server to store on a web browser
so it can later be read back from that browser. A cookie’s value identify user
Constructor of Cokkie class
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name and value.
Method of Cookie class
Method Description
public void setMaxAge(int
expiry)
Sets the maximum age of the cookie in seconds.
public String getName()
Returns the name of the cookie. The name cannot be
changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String
name)
changes the name of the cookie.
public void setValue(String
value)
changes the value of the cookie.
Interface Method Description
Public void addCookie(Cookie ck) method of HttpServletResponse interface is
used to add cookie in response object.
Public Cookie[] getCookies() method of HttpServletRequest interface is
used to return all the cookies from the
browser.
Add cookie’s value
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlets/servlets/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=”text” name="t1" >
68 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
<input type=submit value="Submit">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
SOFTWARE DEVELOPMENT
USING JAVA
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
// Get parameter from HTTP request.
String data = request.getParameter("t1");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
// Add cookie to HTTP response.
//cookie.setMaxAge( 60 * 60 * 24 );//24 hours
response.addCookie(cookie);
// Write output to browser.
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}
Accessing cookie’s value
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
69 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
for(int i = 0; i < cookies.length; i++)
{
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name +"; value = " + value);
}
pw.close();
}
}
Session Tracking
HTTP is a stateless protocol. i.e Each request is independent of the previous one.
In some applications, it is necessary to save state information so that
information can be collected from several interactions between a browser and a
server. Sessions provide such a mechanism.
There are several ways through which it can provide unique identifier in request and
response.
1. User Authentication – This is the very common way where we user can provide
authentication from the login page and then we can pass the authentication
information between server and client to maintain the session. This is not very
effective method because it wont work if the same user is logged in from different
browsers.
2. HTML Hidden Field – We can create a unique hidden field in the HTML and
when user starts navigating, we can set its value unique to the user and keep track
of the session. This method can’t be used with links because it needs the form to
be submitted every time request is made from client to server with the hidden
field. Also it’s not secure because we can get the hidden field value from the
HTML source and use it to hack the session.
3. URL Rewriting – We can append a session identifier parameter with every
request and response to keep track of the session. This is very tedious because we
need to keep track of this parameter in every response and make sure it’s not
clashing with other parameters.
4. Cookies: A "cookie" is a small piece of information sent by a web server to store
on a web browser so it can later be read back from that browser. It can maintain a
session with cookies but if the client disables the cookies, then it won’t work.
5. Session Management API:The servlet API provide methods and classes
specifically designed to handle session.The HttpSession class provide various
session tracking methods
public void setAttribute( String name, Object value )
public Object getAttribute( String name )
70 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
public Object removeAttribute( String name )
USING JAA
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException
{
// Get the HttpSession object.
HttpSession hs = request.getSession(true);
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String s = (String)hs.getAttribute("course");
if(s!= null)
{
hs.setAttribute("course", “bcs”);
}
else
pw.println("data is: " + s);
}
}
JDBC USING SERVLET
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello1 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
PrintWriter out=null;
try
{
Connection c = null;
res.setContentType("text/html");
71 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
out = res.getWriter();
Class.forName("org.postgresql.Driver");
c=DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat
");
// Create a Statement object
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while(rs.next())
{
out.println("rollno is" +rs.getString(1) );
out.println("name is" +rs.getString(2) );
out.println("per is" +rs.getString(3));
}
rs.close();
stmt.close();
c.close();
}
catch(Exception e)
{
out.println("error"+e);
}
}
}
72 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
JSP(Java Server Page)
Feature
• JSP is a server side program.
• JSP tags to enable dynamic content creation (Combination of HTML & JSP tag).
• JSP provide excellent server side scripting support for creating database driven web
applications
• JSP enable the developers to directly insert java code into jsp file, this makes the
development process very simple and its maintenance also becomes very easy.
• JSP pages are efficient, it loads into the web servers memory on receiving the
request very first time and the subsequent calls are served within a very short
period of time.
Life cycle of JSP
There are 3 methods in JSP(Life cycle of JSP)
A JSP page undergoes 3 phases during life cycle.
1.Translation phase:In this phase,JSP pages get translated into servlet code.
2.Compilation phase:In this phase, the servlet code compiled. The compilation is done
only if the page is requested the first time or it is modified.
3.Excution phase:This is final phase where jsp servlet methods are executed.These are
jspInit(),_jspService(),jspDestroy()
1.jspInt()
• This method is identical to the init() method in Java servlet.
73 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
• This method is called first when the JSP is requested and is used to initialize objects
& variables that are used throughout the life of the JSP.
public void jspInit()
{
// Initialization code...
}
2.jspDestroy()
• This method is identical to the destroy() method in Java servlet.
• This method is automatically called when JSP terminates normally.
• This method is used for cleanup where resources used during execution of JSP are
released.
public void jspDestroy() {
// Your cleanup code goes here.
}
3._jspService()
• This method is identical to the service() method in Java servlet.
• This method is automatically processing request& sending response.
void _jspService(HttpServletRequest request, HttpServletResponse response) {
// Service handling code...
}
74 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
JSP Architecture
JSP Processing:
The following steps explain how the web server creates the web page 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.
75 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
• 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,
which the servlet engine passes to the web server inside an HTTP response.
• The web server forwards the HTTP response to your browser in terms of static
HTML content.
JSP Tags
1.Comment Tags:
It is denoted by
<%--
--%>
e.g
<%-- This comment will not be visible in the page source --%>
2.Declaration statement tags: This tag is used for defining the functions and variables to
be used in the JSP.
It is denoted by
<%!
%>
Eg
<%! int age=25;%>
3.Scriptlet tags: It is used for Java control statements & loop.
It is denoted by
<%
Eg. %>
<% for(int i=0;i<=3;i++)
{
---
---
}
%>
76 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
4.Expression tags: The expression is evaluated and the result is inserted into the HTML
page
It is denoted by
<%= expression %>
Eg.
<%=age%>
5.Directive tags:
The jsp directives are messages that tells the web container how to translate a JSP page
into the corresponding servlet.
There are three types of directives:
o page directive
o include directive
o taglib directive
1.page directive
The page directive defines attributes that apply to an entire JSP page.
It is denoted by
<%@ directive attribute="" %>
Attribute as follows
1.language: It defines the programming language (underlying language) being used in
the page.
Syntax of language:
<%@ page language="value" %>
e.g
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
2.Extends: This attribute is used to extend (inherit) the class like JAVA does
Syntax of extends:
<%@ page extends="value" %>
e.g
77 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
<%@ page extends="demotest.DemoClass" %>
3.Import: It is used to import Java package into the JSP program.
Syntax of import:
<%@ page import="value" %>
e.g
<%@page import=” java.sql.*” %
4.contentType:
• It defines the character encoding scheme i.e. it is used to set the content type and
the character set of the response
• The default type of contentType is "text/html; charset=ISO-8859-1".
Syntax of the contentType:
<%@ page contentType="value" %>
e.g
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
5.Session
Specifies whether or not the JSP page participates in HTTP sessionsSyntax of session
Syntax
<%@ page session="true/false"%>
e.g
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
session="false"%>
6.errorPage:
This attribute is used to set the error page for the JSP page if JSP throws an exception and
then it redirects to the exception page.
Syntax of errorPage:
78 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
<%@ page errorPage="value" %>
e.g
<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1"
errorPage="errorHandler.jsp"%>
7. PageEncoding:
The "pageEncoding" attribute defines the character encoding for JSP page.The default is
specified as "ISO-8859-1" if any other is not specified.
Syntax
<%@ page pageEncoding="vaue" %>
Here value specifies the charset value for JSP
Example:
<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1"
isErrorPage="true"%>
2.include directive:
• include directive is used to include one file to the another file
• This included file can be HTML, JSP, text files, etc.
<%@ include file="/header.jsp" %>
e.g
a.jsp
<%="HELLO bcs"%>
p.jsp
<%@ include file="p.jsp" %>
<%="HELLO mcs"%>
3.taglib directive:
JSP taglib directive is used to define the tag library with "taglib" as the prefix, which we
can use in JSP. (custom tags allows us to defined our own tags).
79 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
Syntax of taglib directive:
<%@ taglib uri="uri" prefix="value"%>
Here "uri" attribute is a unique identifier in tag library descriptor and "prefix" attribute is
a tag name.
e.g
<%@ taglib prefix="vtag" uri="http://java.sun.com/jsp/jstl/core" %>
How To run JSP?
<html>
<head>
<title>
Sachin Sir 9823037693
</title>
</head> JSP CODE
<body>
<%="HELLO Sachin Sir"%>
<body>
</html>
Using Function
<html>
<head>
<title>
Sachin Sir 9823037693 Sum of first n numbers
</title>
</head>
<body>
<%! int sumoffirst(int n)
int sum=0;
for(int i=1;i<=n;i++)
sum=sum+i;
return(sum);
}
%>
80 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
JSP CODE
<p>Sum of first n number:
</p>
<body>
</html>
JSP provides several predefined variables(implicit object)
Implicit object:These objects are created automatically by JSP container. It can directly
use these object.JSP Implicit Objects are also called pre-defined variables
No. Object & Description
1
request
This is the HttpServletRequest object associated
with the request.
2
response
This is the HttpServletResponse object associated
with the response to the client.
3
out
This is the PrintWriter object used to send output to
the client.
4
session
This is the HttpSession object associated with the
request.
5
application
This is the ServletContext object associated with the
application context.
6
config
This is the ServletConfig object associated with the
page.
<%=sumoffirst(5)%>
81 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
7
pageContext
This encapsulates use of server-specific features like
higher performance JspWriters.
8
page
This is simply a synonym for this, and is used to call
the methods defined by the translated servlet class.
9
Exception
The Exception object allows the exception data to be
accessed by designated JSP.
1.Display html & jsp page separate
l.html
<html>
<head>
<title>Login</title>
</head>
<body>
<form method="post" action="http://localhost:8080/examples/jsp/login.jsp">
Username:<input type="text" name="t1">
<br>
Password:<input type="password"name="t2">
<br>
<input type="submit" value="Login">
<input type="reset" value="Clear">
</body>
</html>
Login.jsp
<%
String s1=request.getParameter("t1");
String s2=request.getParameter("t2");
if(s1.equals("sachin")&&s2.equals("sachin"))
out.println("Login Sucessfully");
else
out.println("Login incorrect");
82 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
%>
Database connection using jsp
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<html>
<body>
<%
try
{
Class.forName("("org.postgresql.Driver"");
con =
DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat");
Statement sta = con.createStatement();
ResultSet rs=sta.executeQuery("select * from student");
while(rs.next())
{
out.println("rollno"+rs.getInt(1));
out.println("name"+rs.getString(2));
out.println("Percentage"+rs.getFloat(3));
}
rs.close();
sta.close();
con.close();
}
catch(Exception e)
{
}
%>
</body>
</html>
JSP Benefits
• Easy to combine static templates,including HTML or XML.
• JSP pages compile dynamically into servlets.
• JSP makes it easier to author pages "by hand"
• JSP tags for invoking JavaBeansTM components
Compare servlet &jsp
83 Vision Academy
(9823037693/9822506209, http://www.visionacademe.com)
(SACHIN SIR MCS,SET)
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
JAVA II
JSP Servlets
JSP is a webpage scripting language that can
generate dynamic content.
Servlets are Java programs that are
already compiled which also creates
dynamic web content.
JSP run slower compared to Servlet as it takes
compilation time to convert into Java Servlets.
Servlets run faster compared to JSP.
It’s easier to code in JSP than in Java Servlets. Its little much code to write here.
In MVC, jsp act as a view. In MVC, servlet act as a controller.
JSP are generally preferred when there is not
much processing of data required.
servlets are best for use when there is
more processing and manipulation
involved.
The advantage of JSP programming over
servlets is that we can build custom tags which
can directly call Java beans.
There is no such custom tag facility in
servlets.
We can achieve functionality of JSP at client
side by running JavaScript at client side.
There are no such methods for servlets.
Vision Academy Since 2005
Prof. Sachin Sir(MCS,SET)
9822506209/9823037693
www.visionacademe.com
Branch1:Nr Sm Joshi College,Abv Laxmi
zerox,Ajikayatara Build,Malwadi
Rd,Hadapsar
Branch2:Nr AM College,Aditya Gold
Society,Nr Allahabad Bank ,Mahadevnager

More Related Content

Similar to adjava_23_bcs_vision_academy_sachinsir.pdf

Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxeyemitra1
 
NJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docx
NJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docxNJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docx
NJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docxcurwenmichaela
 
11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.pptNaitikChatterjee
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfarpitaeron555
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptxSoniaKapoor56
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & setsRatnaJava
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)SURBHI SAROHA
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40bhawna sharma
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanZeeshan Khan
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorialinfo_zybotech
 
More topics on Java
More topics on JavaMore topics on Java
More topics on JavaAhmed Misbah
 

Similar to adjava_23_bcs_vision_academy_sachinsir.pdf (20)

Advanced core java
Advanced core javaAdvanced core java
Advanced core java
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
2 b queues
2 b queues2 b queues
2 b queues
 
NJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docx
NJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docxNJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docx
NJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docx
 
11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdf
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
Collections
CollectionsCollections
Collections
 
Java collections
Java collectionsJava collections
Java collections
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
 

Recently uploaded

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 

Recently uploaded (20)

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 

adjava_23_bcs_vision_academy_sachinsir.pdf

  • 1. 1 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Java - Collections Framework Java - Collections Framework A collection allows a group of objects to be treated as a single unit. Arbitrary objects can be stored, retrieved, and manipulated as elements of collection. This framework is provided in the java.util package.
  • 2. 2 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Classes & Interfaces Collection Interface List Interface • It extends collection interface.
  • 3. 3 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II • The elements in a list are ordered. Each element, therefore, has a position in the list. • It can contain duplicates. • A zero-based index can be used to access the element at the position designated by the index value. The position of an element can change as elements are inserted or deleted from the list. Constructor LinkedList( ) LinkedList Class • The LinkedList implements the List interface. • It provides a linked-list data structure. • The elements in a linked list are ordered. • It can contain duplicates. Constructor LinkedList() import java.util.*; class LinkedListDemo { public static void main(String args[]) { LinkedList ll = new LinkedList(); ll.add("F"); ll.add("B"); ll.add("D"); System.out.println(ll); } }
  • 4. 4 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II import java.util.*; class LinkedListDemo { public static void main(String args[]) { // create a linked list LinkedList ll = new LinkedList(); // add elements to the linked list ll.add("F"); ll.add("B"); ll.add("D"); ll.add("E"); ll.add("C"); ll.addLast("Z"); ll.addFirst("A"); ll.add(1, "A2"); System.out.println("Original contents of ll: " + ll); // remove elements from the linked list ll.remove("F"); ll.remove(2); System.out.println("Contents of ll after deletion: " + ll); // remove first and last elements ll.removeFirst(); ll.removeLast(); System.out.println("ll after deleting first and last: " + ll); // get and set a value Object val = ll.get(2); ll.set(2, (String) val + " Changed"); System.out.println("ll after change: " + ll); } } This would produce following result: Original contents of ll: [A, A2, F, B, D, E, C, Z] Contents of ll after deletion: [A, A2, D, E, C, Z] ll after deleting first and last: [A2, D, E, C] ll after change: [A2, D, E Changed, C]
  • 5. 5 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II ArrayList Class • The ArrayList class implements the List interface. • ArrayList supports dynamic arrays that can grow as needed. • The elements in a Array list are ordered. • It can contain duplicates. • ArrayList gives better performance as it is non-synchronized. ArrayList is non-synchronized which means multiple threads can work on arrayList at the same time ArrayList gives better performance as it is non-synchronized Constructor ArrayList() import java.util.*; class ArrayListDemo { public static void main(String args[]) { ArrayList al = new ArrayList(); al.add("F"); al.add("B"); al.add("D"); System.out.println(al); } } ArrayList LinkedList 1) ArrayList internally uses dynamic array to tore the elements. LinkedList internally uses doubly linked list to store the elements. 2) Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory. Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory. 3) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.
  • 6. 6 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II 4) ArrayList al = new ArrayList(); LinkedList al = new LinedList(); Vector class • The class can be used to create a generic dynamic array known as vector that can hold objects of any type and any number.(Object don’t have to be homogenous) • The Vector class implements the List interface. • The elements in a Vector are ordered. • It can contain duplicates. • Vector is synchronized. This means if one thread is working on Vector, no other thread can get a hold of it. • Vector operations gives poor performance as they are thread-safe Constructor Vector( ) import java.util.*; class VectorDemo { public static void main(String args[]) { Vector v = new Vector(); v.add("F"); v.add("B"); v.add("D"); System.out.println(v); } } Iterator Iterator is an interface available in Collection framework in java.util package. It is a Java Cursor used to iterate a collection of objects. Iterator is interface enables you to cycle through a collection, obtaining or removing elements.
  • 7. 7 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II The Methods Declared by Iterator: SN Methods with Description 1 boolean hasNext( ) Returns true if there is next elements. Otherwise, returns false. 2 Object next( ) Returns the next element. 3 Void remove( ) Removes the current element. import java.util.*; class IteratorDemo { public static void main(String args[]) { ArrayList al = new ArrayList(); al.add("C"); al.add("A"); al.add("E"); System.out.print(“Display element using iterator” ); Iterator itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element ); } } } ListIterator ListIteratoris interface that extends Iterator to allow bidirectional traversal of a list, and the modification of elements. The Methods Declared by ListIterator: SN Methods with Description 1 Void add(Object obj) It add object
  • 8. 8 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II 2 boolean hasNext( ) Returns true if there is a next element. Otherwise, returns false. 3 boolean hasPrevious( ) Returns true if there is a previous element. Otherwise, returns false. 4 Object next( ) Returns the next element. A NoSuchElementException is thrown if there is not a next element. 5 int nextIndex( ) Returns the index of the next element. If there is not a next element, returns the size of the list. 6 Object previous( ) Returns the previous element. A NoSuchElementException is thrown if there is not a previous element. 7 int previousIndex( ) Returns the index of the previous element. If there is not a previous element, returns -1. 8 Void remove( ) Removes the current element from the list. 9 Void set(Object obj) Set obj to the current element. import java.util.*; class ListIteratorDemo { public static void main(String args[]) { ArrayList al = new ArrayList(); al.add("C"); al.add("A"); al.add("E"); System.out.print(“Display next element using listiterator” ); ListIterator itr = al.iterator(); while(itr.hasNext()) {
  • 9. 9 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Object element = itr.next(); System.out.print(element ); } System.out.print(“Display previous element using listiterator” ); while(itr.hasPrevious()) { Object element = itr.previous(); System.out.print(element + " "); } } } ListIterator Iterator ListIterator is interface that extends Iterator to allow bidirectional traversal of a list, and the modification of elements Iterator is interface enables you to cycle through a collection, obtaining or removing elements It can traverse in both the directions (forward and Backward). It can traverse in only forward direction using Iterator It can use ListIterator to traverse List only. Iterator is used for traversing List and Set both. It can add element during traversing a list using ListIterator. It can not add element during traversing a list using Iterator. It can obtain indexes at any point of time while traversing a list using ListIterator It cannot obtain indexes while using Iterator. Methods of ListIterator: • add(obj) • hasNext() • hasPrevious() • next() • nextIndex() • previous() • previousIndex() • remove() • set(obj) Methods of Iterator: • hasNext() • next() • remove()
  • 10. 10 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Enumeration Interface The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. import java.util.*; class Enumeration { public static void main(String args[]) { Enumeration d; Vector v = new Vector(); v.add("C"); v.add("A"); v.add("E"); d=v.elements(); while (d.hasMoreElements()) { System.out.println(d.nextElement()); } } } Set Interface • It extends collection interface • It does not contain duplicate SortedSet Interface The SortedSet interface extends Set and declares the behavior of a set sorted in ascending order. TreeSet Class • It implements SortedSet interface that uses a tree for storage. • Objects are stored in sorted, ascending order. • Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.
  • 11. 11 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Constructor TreeSet( ) TreeSet(Comparator comp) import java.util.*; class TreeSetDemo { public static void main(String args[]) { // Create a tree set TreeSet ts = new TreeSet(); // Add elements to the tree set ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); System.out.println(ts); } } This would produce following result: [A, B, C, D, E, F] Java Comparator interface • It is used to order the objects of user-defined class. • This interface contains 2 methods compare(Object obj1,Object obj2) or equals(Object element). int compare(Object obj1, Object obj2) obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned. • It provides multiple sorting sequence i.e. you can sort the elements on the basis of any data member, for example rollno, name, age or anything else.
  • 12. 12 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II import java.util.*; class Tree implements Comparator { public int compare(Object o1,Object o2) { String s1=(String)o1; String s2=(String)o2; return s2.compareTo(s1); } public static void main(String args[]) { // Create a tree set TreeSet ts = new TreeSet(new Tree()); // Add elements to the tree set ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); System.out.println(ts); } } o/p F E D C B A HashSet Class • HashSet implemets the Set interface. • It creates a collection that uses a hash table for storage • It does not have duplicate • It displaying object at any order. Constructor HashSet( ) import java.util.*; class HashSetDemo { public static void main(String args[])
  • 13. 13 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II { // create a hash set HashSet hs = new HashSet(); // add elements to the hash set hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); System.out.println(hs); } } o/p [A, F, E, D, C, B] LinkedHashSet Class • LinkedHashSet class implemets the Set interface. • It used linked list & hash table for storage • It does not have duplicate • It displaying insertion order. Constructor LinkedHashSet( ) import java.util.*; class Lh { public static void main(String args[]) { // create a hash set LinkedHashSet hs = new LinkedHashSet(); // add elements to the hash set hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); System.out.println(hs); } } o/p
  • 14. 14 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II [B,A,D,E,C,F] Map Interface • A Map interface defines mappings from keys to values. The <key, value> pair is called an entry in a Map. • A Map does not allow duplicate keys, in other words, the keys are unique. Methods • Object put(Object key, Object value)
  • 15. 15 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II • Object get(Object key) • Object remove(Object key) • void putAll(Map t) • boolean containsKey(Object key) • boolean containsValue(Object value) • int size() • boolean isEmpty() • void clear() TreeMap Class • The TreeMap class implements the Map interface by using a tree. • A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. • Its elements will be sorted in ascending key order. • It contains only unique key. Constructor TreeMap() import java.util.*; class TreeMapDemo { public static void main(String args[]) { TreeMap tm = new TreeMap(); tm.put("Amol", new Float(55.55)); tm.put("Punit", new Float(66.33)); System.out.println(tm); } }
  • 16. 16 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II HashMap Class • The HashMap class uses a hash table to implement the Map interface. • It display object any order. • It contains only unique key. Constructor HashMap( ) import java.util.*; class HashMapDemo { public static void main(String args[]) { HashMap tm = new HashMap(); tm.put("Amol", new Float(55.55)); tm.put("Punit", new Float(66.33)); System.out.println(tm); } } LinkedHashMap Class 1.This class implement the Map interface. 2.It display object insertion order. 3.It contains only unique key. Constructor LinkedHashMap( ) import java.util.*; class Hd { public static void main(String args[]) {
  • 17. 17 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II LinkedHashMap tm = new LinkedHashMap(); tm.put("Amol", new Float(55.55)); tm.put("Punit", new Float(66.33)); System.out.println(tm); } } Hashtable • Hashtable contains values based on the key. It implements the Map interface. • It contains only unique key. • It is synchronized. Constructor Hashtable() import java.util.*; class HashDemo { public static void main(String args[]) { Hashtable tm = new Hashtable(); tm.put("Amol", new Float(55.55)); tm.put("Punit", new Float(66.33)); System.out.println(tm); } }
  • 18. 18 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II MultiThreading MuliProcessing • This allows many processes to run simultaneously. • Process is a running instance of the program. i.e. an operating system process. CPU time is shared between different processes. • OS provides context switching mechanism, which enables to switch between the processes. • Program’s entire contents (e.g. variables, global variables, functions) are stored separately in their own context. Example:- MS-Word and MS-Excel applications running simultaneously. (or any two applications for that matter) MultiThreading • It allows many tasks within a program (process) to run simultaneously. • Each such task is called as a Thread. • Each Thread runs in a separate context. • Each Thread has a beginning , a body,& an end • Example:- Lets take a typical application like MS-Word. There are various independent tasks going on, like displaying GUI, auto-saving the file, typing in text, spell-checking, printing the file contents etc… Thread • Thread is an independent sequential path of execution within a program. i.e. separate call stack.
  • 19. 19 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II • Many threads run concurrently within a program. • At runtime, threads in a program exist in a common memory space and can share both data and code. Start Start Start Switching switching How To Thread Created? Threads can be achieved in one of the two ways – 1 Extending java.lang.Thread class. 2 Implementing java.lang.Runnable interface 1.Using Extending java.lang.Thread class. To Define a class that extends Thread class & override its run() with code required by thread. Steps as Follows 1.Declare the class as extending the Thread class Class A extends Thread { ----------- } Where A is name of thread. 2.Implement the run() method.i.e Responsible for executing of code the thread will execute. public void run() { ------- Main Thread Threads A Threads B Threads C
  • 20. 20 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II ----- } 3.Create a thread object & call the start() method to initiate the thread execution. class A extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("n From Thread A:i="+i); } System.out.println("n Exit from A"); } } class B extends Thread { public void run() { for(int j=1;j<=5;j++) { System.out.println("n From Thread B:j="+j); } System.out.println("n Exit from B"); } } class ThreadTest { public static void main(String args[]) { A t1=new A(); //new A().start(); t1.start();//invoke run method
  • 21. 21 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II B t2=new B(); t2.start();//invoke run method } } 2.Implementing java.lang.Runnable interface Steps as follows 1.Declare the class as implementing the runnable interface. 2.Implement the run() method. 3.It create a thread which is pass a parameter as a thread class object which implemetns “runnable” interface 4.Call the thread’s start() method to run the thread. class A implements Runnable { public void run() { for(int i=1;i<=5;i++) { System.out.println("tThread A :"+i); } System.out.println("End of thread A"); } } class RunnableTest { public static void main(String args[]) { A r=new A(); Thread tx=new Thread(r); tx.start(); System.out.println("End of main thread"); } }
  • 22. 22 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Life Cycle of thread 1. Newborn state 2. Runnable state 3. Running state 4. Blocked state 5. Dead state 1 Newborn state It create a thread object, the thread is born & is said to be newborn state. 2. Runnable state It means thread is ready for execution & is waiting for the availability of processor. The processor of assigning time to threads is known as timing-slicing. yield …… Runnable thread newborn Running Runnable Blocked Dead stop stop stop Resume Notify Suspend Sleep wait start yield Active Thread New Thread Idle Thread
  • 23. 23 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II If a thread to leave control to another thread of equal priority before its turn comes,it can done by using yield() method 3.Running state It means that the processor has given its time to the thread for its execution. The thread runs until it leaves control on its own or it is preempted by higher priority thread.A running thread my leaves its control in one of the following 1.suspend(): It has been suspended using suspend() method. A suspended thread can be received by using resume() method. Resume() Running Runable Suspended 2.sleep() It can put thread to sleep for a specified time period using sleep(t) method.(t is time milliseconds). Sleep(t) After t Running Runable Sleeping 3.wait() It has been hold to wait until some event occurs. This is done using wait() method. The thread can be scheduled to run again using notify() method. Wait Notify() Running Runable waiting 4.Blocked state
  • 24. 24 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II A thread is said to be blocked when it is prevented from entering into runnable state & subsequently the running state. This happens when the thread is suspended,sleeping or waiting. A blocked thread is considered “not runnable” but not dead . 5.Dead state Every Thread has a life cycle. A running threads ends its life when it has completed executing its run() method. Display the main Thread. public static Thread currentThread() Returns a reference to the currently executing thread object. class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t); // change the name of the thread t.setName("My Thread"); System.out.println("After name change: " + t.getName()); try { for(int n = 6; n > 0; n--) { System.out.println(n); } } catch (Exception e) { }
  • 25. 25 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II } } Threads priority Each thread is assigned a priority, which affects the order it is scheduled for running. i.e Threads are assigned priorities that the thread scheduler can use to determine how the threads will be scheduled. The following static final integer constants are defined in the Thread class: • MIN_PRIORITY =0( Lowest Priority) • NORM_PRIORITY =5 (Default Priority) • MAX_PRIORITY =10 (Highest Priority) setPriority():It can modify a thread’s priority at any time after its creation using the setPriority() method. Threadname.setPriority(int number) Where number is priority number. getPriority(): It retrieve the thread priority value class A extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("n From Thread A:i="+i); } System.out.println("n Exit from A"); } } class B extends Thread { public void run() { for(int j=1;j<=5;j++) { System.out.println("n From Thread B:j="+j); } System.out.println("n Exit from B"); } }
  • 26. 26 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II class C extends Thread { public void run() { for(int k=1;k<=5;k++) { System.out.println("n From Thread C:k="+k); } System.out.println("n Exit from C"); } } public class ThreadPriority { public static void main(String args[]) { A t1=new A(); B t2=new B(); C t3=new C(); t3.setPriority(Thread.MAX_PRIORITY); t1.setPriority(Thread.MIN_PRIORITY); t3.start(); t1.start(); t2.start(); } } Threads Method 1. isAlive() method: Returns true if the thread is alive, otherwise false. public final boolean isAlive() 2.join() method: The join() method waits for a thread to die.(A thread to wait until the completion of another thread before continue. public void join() class A extends Thread { public void run() { System.out.println("A Thread");
  • 27. 27 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II } } class B extends Thread { public void run() { System.out.println("B Thread"); } } class ThreadTest { public static void main(String args[]) { try { A t1=new A(); t1.start();//invoke run method B t2=new B(); t2.start();//invoke run method t1.join(); t2.join(); System.out.println("Main parent thread"); System.out.println("A thread "+t1.isAlive()); System.out.println("B thread "+t2.isAlive()); } catch(Exception e) { System.out.println("error"+e); } } }
  • 28. 28 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II What is mean by Synchronization? When two or more threads need access to a shared resource, they need to ensure that the resource will be used by only one thread at a time. This process by which this is achieved is called Synchronization. This is the general form of the synchronized statement: synchronized method1 () { // statements to be synchronized } When it declare a method synchronized, Java creates a “Monitor” & hands it over to the thread that calls the method first time. As long as the thread holds the monitor, no other thread can enter the synchronized section of code. When thread has completed its work of using synchronized method(or block of code),it will hand over the monitor to the next thread that is ready to use same resource. Using synchronized class Callme { synchronized void call(String msg) { System.out.print("[" + msg); System.out.println("]"); } } class Caller implements Runnable { String msg; Callme target; Thread t; public Caller(Callme targ, String s) { target = targ; msg = s;
  • 29. 29 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II t = new Thread(this); t.start(); } public void run() { target.call(msg); } } public class Synch { public static void main(String args[]) { Callme target = new Callme(); Caller ob1 = new Caller(target, "Hello"); Caller ob2 = new Caller(target, "Synchronized"); Caller ob3 = new Caller(target, "World"); } } Java - Interthread Communication When multiple threads are running in an application, it become necessary for the threads to communicate(talk) with each other such communication called as interthread communication. The thread can communicate by either sharing data or indicating when a specific activity has completed. Methods for interthread communication wait( ): Causes the current thread to wait until another thread invokes the notify(). Notify( ): Wakes up a single thread that is waiting on this object's monitor. notifyAll( ): Wakes up all the threads that called wait( ) on the same object. Join():The join() method waits for a thread to die.(A thread to wait until the completion of another thread before continue. Thread Method & Description static Thread currentThread() This method returns a reference to the currently executing thread object. String getName()
  • 30. 30 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II This method returns this thread's name. int getPriority() This method Returns this thread's priority. boolean isAlive() This method tests if this thread is alive. void join() Waits for this thread to die. void run() If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns void setName(String name) This method changes the name of this thread to be equal to the argument name. void setPriority(int newPriority) This method changes the priority of this thread. static void sleep(long millis) This method causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. void start() This method causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. static void yield() This method causes the currently executing thread object to temporarily pause and allow other threads to execute.
  • 31. 31 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II DATABASE PROGRAMING What is JDBC? • It is Java Database Connectivity technology. • This technology is an API(Application Programming Interface) for the java programming language that define how a client may access a database. • It provides methods for querying and updating data in database. What are JDBC Drivers? It is a software component enabling a java application to interact with a database. JDBC Architecture JDBC Driver Types JDBC drivers are divided into four types or levels. The different types of jdbc drivers are: Type 1: JDBC-ODBC Bridge driver (Bridge) Type 2: Native-API/partly Java driver (Native) Type 3: AllJava/Net-protocol driver (Middleware) Type 4: All Java/Native-protocol driver (Pure) Type 1 JDBC Driver JDBC-ODBC Bridge driver The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.
  • 32. 32 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Type 1: JDBC-ODBC Bridge Advantage The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available. Disadvantages 1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable. 2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types. 3. The client system requires the ODBC Installation to use the driver. 4. Not good for the Web. Type 2 JDBC Driver Native-API/partly Java driver The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i.e. this driver is specific to a particular database. Some
  • 33. 33 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native api. Type 2: Native api/ Partly Java Driver Advantage The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type 1 and also it uses Native api which is Database specific. Disadvantage 1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet. 2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue. 3. If we change the Database we have to change the native api as it is specific to a database. 4. Usually not thread safe. Type 3 JDBC Driver All Java/Net-protocol driver
  • 34. 34 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers. Type 3: All Java/ Net-Protocol Driver Advantage 1. This driver is server-based, so there is no need for any vendor database library to be present on client machines. 2. This driver is fully written in Java and hence Portable. It is suitable for the web. 3. There are many opportunities to optimize portability, performance, and scalability. 4. The net protocol can be designed to make the client JDBC driver very small and fast to load. 5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced system administration such as logging and auditing. 6. This driver is very flexible allows access to multiple databases using one driver. 7. They are the most efficient amongst all driver types. Disadvantage It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server.
  • 35. 35 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Type 4 JDBC Driver Native-protocol/all-Java driver The Type 4 uses java networking libraries to communicate directly with the database server. Type 4: Native-protocol/all-Java driver Advantage 1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web. 2. . Number of translation layers is very less i.e. type 4 JDBC drivers don't have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good. 3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically. Disadvantage With type 4 drivers, the user needs a different driver for each database. JDBC Versions 1). The JDBC 1.0 API. 2). The JDBC 1.2 API.
  • 36. 36 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II 3). The JDBC 2.0 Optional Package API. 4). The JDBC 2.1 core API. 5) The JDBC 3.0 API. 6) The JDBC 4.0 API. JDBC Architecture The JDBC API supports both two-tier and three-tier processing models for database access. 1. Two-tier In such an architecture, the Java application communicates directly with the data source (or database). The database may reside on the same machine or may be on another machine to which the clinet machine needs to be connected through a network 2. Three-tier In such an architecture, the client machine will send the database access statements to the middleware, which will then send the statements to the database residing on the third tier
  • 37. 37 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II of the architecture, which is normally referred to as the back end. The statements will be processed there and the result be returned back to the client through the middle tier. This approach will have all the advantages associated with the 3-tier architecture, such as better maintainability, easier deployment, scalability, etc. JDBC CLASSES AND INTERFACE The java.sql package contains several classes and interface which are used to communicate with the database
  • 38. 38 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II BASIC JDBC STEPS 1.Load the driver Loading Database driver is very first step towards making JDBC connectivity with the database. It is necessary to load the JDBC drivers before attempting to connect to the database.
  • 39. 39 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Syntax Class.forName(drivername). e.g Class.forName("org.postgresql.Driver"); 2.Establishing Connection After loading driver, now Establishing Connection with the database with user name and password. Syntax con = DriverManager.getConnection(url+db, user, pass); con=DriverManager.getConnection("jdbc:postgresql://localhost:5432 /ty"); 3.Create a statement object: There are three basic types of SQL statements used in the JDBC API: 1.Statement:A Statement is interface.It represents a general SQL statement without parameters. The method createStatement() creates a Statement object. Eg Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from student "); 2.Prepared Statement: A PreparedStatement is a interface.It represents a precompiled SQL statement, with or without parameters. It is used for SQL commands that need to be executed repeatedly. Eg 1 PreparedStatement ps = con.prepareStatement(“select * from student where rollno=?”); ps.setString(1,1); ResultSet rs = stmt.executeQuery(); Eg2 PreparedStatement ps = con.prepareStatement(“insert into student values(?,?,?)”); ps.setInt(1,1); ps.setString(2,’amol’);
  • 40. 40 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II ps.setFloat(3,66.55f); ResultSet rs = ps.executeUpdate(); 3.CallableStatement - CallableStatement is interface. It is used to execute SQL stored procedures Eg CallableStatement cstmt=con.prepareCall(“call student”); 4.Execute a query An SQL statement can either be a query that return result or operation that manipulates the database 1.ResultSet executeQuery(String sql): It is used for statements that return an output result(for only select query) 2.int executeUpdate(String sql): Returns an integer representing the number of rows affected by the SQL statement. (For only INSERT, DELETE, or UPDATE SQL statements). 5.Process a query: ResultSet provides access to a table of data generated by executing a Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results. To access these values, there are getXXX() methods where XXX is a type for example, getString(), getInt(),getFloat etc. There are two forms of the getXXX methods: i. Using columnName: getXXX(String columnName) ii. Using columnNumber: getXXX(int columnNumber) Example rs.getString(“sname”)); rs.getString(1);
  • 41. 41 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II 6.Close the connections After all work is done, it is important to close the connection. But before the connection is closed , close the ResultSet and the statement objects. e.g rs.close(); stmt.close(); con.close(); ResultSet Scroll Types The scroll type indicates how the cursor moves in the ResultSet. The concurrency type affects concurrent access to the resultset. The types are given in the table below. Scroll Type TYPE_FORWARD_ONLY : The result set is not scrollable. TYPE_SCROLL_INSENSITIVE: The result set is scrollable but not sensitive to database changes. TYPE_SCROLL_SENSITIVE: The result set is scrollble and sensitive to database changes. Concurrency Type CONCUR_READ_ONLY The result set cannot be used to update the database. CONCUR_UPDATABLE The result set can be used to update the database.
  • 42. 42 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Note: store postgres.jar file into following path /usr/lib/jvm/java/jre/lib/ext 1.USING SELECT STATEMENT import java.sql.*; public class Post {
  • 43. 43 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II public static void main(String args[]) { Connection c = null; try { Class.forName("org.postgresql.Driver"); c=DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat "); Statement stmt = c.createStatement(); ResultSet rs=stmt.executeQuery("select * from student"); while(rs.next()) { System.out.println("Rollno"+rs.getInt(1)); System.out.println("Name"+rs.getString(2)); System.out.println("Per"+rs.getFloat(3)); } } catch (Exception e) { System.out.println(e); } } } 2.USING INSERT STATEMENT import java.sql.*; import java.io.*; public class Post { public static void main(String args[]) { Connection c = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat"); Statement stmt = c.createStatement(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Roll no: "); int rno=Integer.parseInt(br.readLine()); System.out.println("Enter Name: "); String name=br.readLine();
  • 44. 44 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II System.out.println("Enter percentage: "); float per=Float.parseFloat(br.readLine()); String sql="insert into student values("+rno+",'"+name+"',"+per+")"; int k=stmt.executeUpdate(sql); if(k>0) System.out.println("Insert "+k); else System.out.println("Insert "+k); ResultSet rs=stmt.executeQuery("select * from student"); while(rs.next()) { System.out.println("rollno"+rs.getInt(1)); System.out.println("name"+rs.getString(2)); System.out.println("Percentage"+rs.getFloat(3)); } rs.close(); stmt.close(); c.close(); } catch (Exception e) { System.out.println(e); } } } 3.USING UPDATE STATEMENT import java.sql.*; import java.io.*; public class Post { public static void main(String args[]) { Connection c = null; try { Class.forName("org.postgresql.Driver"); c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat"); Statement stmt = c.createStatement(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Roll no: "); int rno=Integer.parseInt(br.readLine());
  • 45. 45 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II System.out.println("Enter Name: "); String name=br.readLine(); System.out.println("Enter percentage: "); float per=Float.parseFloat(br.readLine()); String sql="update student set name='"+name+"'"+","+"per="+per+" "+"where rollno="+rno; int k=stmt.executeUpdate(sql); if(k>0) System.out.println("Insert "+k); else System.out.println("Insert "+k); ResultSet rs=stmt.executeQuery("select * from student"); while(rs.next()) { System.out.println("rollno"+rs.getInt(1)); System.out.println("name"+rs.getString(2)); System.out.println("Percentage"+rs.getDouble(3)); } rs.close(); stmt.close(); c.close(); } catch (Exception e) { System.out.println(e); } } } 4. USING DELETE STATEMENT import java.sql.*; import java.io.*; public class Post { public static void main(String args[]) { Connection c = null; try {
  • 46. 46 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Class.forName("org.postgresql.Driver"); c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat"); Statement stmt = c.createStatement(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Roll no: "); int rno=Integer.parseInt(br.readLine()); String sql="delete from student where rollno="+rno; int k=stmt.executeUpdate(sql); if(k>0) System.out.println("Delete "+k); else System.out.println("Delete "+k); ResultSet rs=stmt.executeQuery("select * from student"); while(rs.next()) { System.out.println("rollno"+rs.getInt(1)); System.out.println("name"+rs.getString(2)); System.out.println("Percentage"+rs.getFloat(3)); } rs.close(); stmt.close(); c.close(); } catch(Exception e) { System.out.println(e); } } } Navigate the Database import java.sql.*; class stud3 { public static void main( String args[]) { try { Connection c=null; Class.forName("org.postgresql.Driver");
  • 47. 47 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II C=DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres"," redhat"); //Statement stmt=c.createStatement(); Statement stmt = c.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); String sql="select * from student"; ResultSet rs= stmt.executeQuery(sql); System.out.println("Display record next"); while( rs.next()) { System.out.println( rs.getInt(1)); System.out.println(rs.getString(2)); System.out.println(rs.getDouble(3)); } System.out.println("Display record previous"); while( rs.previous()) { System.out.println( rs.getInt(1)); System.out.println(rs.getString(2)); System.out.println(rs.getDouble(3)); } System.out.println("Display first record "); rs.first(); System.out.println( rs.getInt(1)); System.out.println(rs.getString(2)); System.out.println(rs.getDouble(3)); System.out.println("Display last record "); rs.last(); System.out.println( rs.getInt(1)); System.out.println(rs.getString(2)); System.out.println(rs.getDouble(3)); rs.close(); stmt.close(); c.close(); } catch(Exception e) { System.out.println("error"+e); } } } METADATA
  • 48. 48 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Metadata means information about data. Some application need to discover information about the tables, result set structure or underlying database dynamically. JDBC can provide additional information about the structure of a database and its tables. DatabaseMetadata Interface MetaData interface provides methods to get meta data of a database such as database product name, database product version, driver name, name of total number of tables, name of total number of views etc. How to get the object of DatabaseMetaData: The getMetaData() method of Connection interface returns the object of DatabaseMetaData. Syntax: public DatabaseMetaData getMetaData()throws SQLException Methods: o public String getDriverName()throws SQLException: it returns the name of the JDBC driver. o public String getDriverVersion()throws SQLException: it returns the version number of the JDBC driver. o public String getUserName()throws SQLException: it returns the username of the database. o public String getDatabaseProductName()throws SQLException: it returns the product name of the database. o public String getDatabaseProductVersion()throws SQLException: it returns the product version of the database. o public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)throws SQLException: it returns the description of the tables of the specified catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc. Example1: DatabaseMetaData dbmd=con.getMetaData(); System.out.println("Driver Name: "+dbmd.getDriverName()); System.out.println("Driver Version: "+dbmd.getDriverVersion()); System.out.println("UserName: "+dbmd.getUserName()); System.out.println("Database Product Name: "+dbmd.getDatabaseProductName()); System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());
  • 49. 49 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Example 2: To print no. of tables DatabaseMetaData dbmd=con.getMetaData(); String table[]={"TABLE"}; ResultSet rs=dbmd.getTables(null,null,null,table); while(rs.next()){ System.out.println(rs.getString(3)); ResultSetMetaData ResultSetMetaData interface The ResultSetMetaData interface provides information about the structure of a particular ResultSet How to get the object of ResultSetMetaData: The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syntax: public ResultSetMetaData getMetaData()throws SQLException Method Description public int getColumnCount()throws SQLException it returns the total number of columns in the ResultSet object. public String getColumnName(int index)throws SQLException it returns the column name of the specified column index. public String getColumnTypeName(int index)throws SQLException it returns the column type name for the specified index. public String getTableName(int index)throws SQLException it returns the table name for the specified column index. Example: PreparedStatement ps=con.prepareStatement("select * from stud"); ResultSet rs=ps.executeQuery(); ResultSetMetaData rsmd=rs.getMetaData(); System.out.println("Total columns: "+rsmd.getColumnCount()); System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1)); System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1) );
  • 50. 50 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Transaction Method Description void setAutoCommit(boolean status) It is true bydefault means each transaction is committed bydefault. void commit() commits the transaction. void rollback() cancels the transaction. con.setAutoCommit(false); Statement stmt=con.createStatement(); stmt.executeUpdate("insert into user420 values(190,'abhi',40000)"); stmt.executeUpdate("insert into user420 values(191,'umesh',50000)"); con.commit(); Savepoints The save point is a logical position in a transaction up to which we can rollback the transaction. When the save point is placed in the middle of the transaction, the logics placed before the save point will be committed and the logics placed after the save point will be rolled back. Statement st = con.createStatement (); con.setAutoCommit (false); st.executeUpdate ("insert into college values (‘am’, ‘mumbai’, 1009)"); Savepoint svpt = con.setSavepoint ("mysp"); st.executeUpdate ("update college set cname= ‘sm’ where code=1001"); st.executeUpdate ("insert into college values (‘mit’, ‘Bhubaneswar’, 1008)"); con.rollback (svpt); con.commit ();
  • 51. 51 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II NETWORKING Networking Basics Protocol A protocol is a set of rules and standards for communication. 1. IP (Internet Protocol): is a network layer protocol that breaks data into small packets and routes them using IP addresses. 2. TCP (Transmission Control Protocol): This protocol is used for connection-oriented communication between two applications on two different machines. It is most reliable and implements a connection as a stream of bytes from source to destination. 3.UDP (User Datagram Protocol): It is a connection less protocol and used typically for request and reply services. It is less reliable but faster than TCP. Addressing 1. MAC Address: Each machine is uniquely identified by a physical address, address of the network interface card. It is 48-bit address represented as 12 hexadecimal characters: For Example: 00:09:5B:EC:EE:F2 2.IP Address: It is used to uniquely identify a network and a machine in the network. Itis referred as global addressing scheme. Also called as logical address. Currently used type of IP addresses is: Ipv4 – 32-bit address and Ipv6 – 128-bit address. For Example: Ipv4 – 192.168.16.1 Ipv6 – 0001:0BA0:01E0:D001:0000:0000:D0F0:0010 3.Port Address: It is the address used in the network to identify the application on the network. Domain Name Service (DNS) It is very difficult to remember the IP addresses of machines in a network. Instead, we can identify a machine using a “domain name” which is character based naming mechanism. Example: www.google.com. The mapping between the domain name and the IP address is done by a service called DNS. URL A URL (Uniform Resource Locator) is a unique identifier for any resource located on the Internet. The syntax for URL is given as: <protocol>://<hostname>[:<port>][/<pathname>][/<filename>[#<section>]]
  • 52. 52 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Sockets Def:A socket represents the end-point of the network communication. It provides a simple read/write interface and hides the implementation details network and transport layer protocols. It is used to indicate one of the two end-points of a communication link between two processes. When client wishes to make connection to a server, it will create a socket at its end of the communication link. The socket concept was developed in the first networked version of UNIX developed at the University of California at Berkeley. So sockets are also known as Berkeley Sockets. Ports A port number identifies a specific application running in the machine. A port number is a number in the range 1-65535. Reserved Ports: TCP/IP protocol reserves port number in the range 1-1023 for the use of specified standard services, often referred to as “well-known” services. e.g FTP :21 HTTP:80 SNMP:161 SMTP:25 The java.net Package The java.net package provides classes and interfaces for implementing network applications such as sockets, network addresses, Uniform Resource Locators (URLs) etc. some important interfaces, classes and exceptions as follows : InetAddress Class Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host name for example www.google.com, www.facebook.com etc. Method Description public static InetAddress getByName(String host) throws UnknownHostException it returns the instance of InetAddress containing LocalHost IP and name. public static InetAddress getLocalHost() throws UnknownHostException it returns the instance of InetAdddress containing local host name and address. public String getHostName() it returns the host name of the IP address. public String getHostAddress() it returns the IP address in string format. URL Class The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web. The class has the following constructors:
  • 53. 53 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II 1. URL(String url_str): Creates a URL object based on the string parameter. If the URL cannot be correctly parsed, a MalformedURLException will be thrown. 2. URL(String protocol, String host, String path): Creates a URL object with the specified protocol, host and path. 3. URL(String protocol, String host, int port, String path): Creates a URL object with the specified protocol, host, port and file path. 4. URL(URL urlObj, String urlSpecifier): Allows you to use an existing URL as a reference context and then create a new URL from that context. Methods Method Description public String getProtocol() it returns the protocol of the URL. public String getHost() it returns the host name of the URL. public String getPort() it returns the Port Number of the URL. public String getFile() it returns the file name of the URL. public URLConnection openConnection() it returns the instance of URLConnection i.e. associated with this URL. URLConnection Class The Java URLConnection class represents a communication link between the URL and the application. This class can be used to read and write data to the specified resource referred by the URL. public class URLConnectionExample { public static void main(String[] args) { try { URL url=new URL("http://www.visionacademe.com/java-tutorial"); URLConnection urlcon=url.openConnection(); InputStream stream=urlcon.getInputStream(); int i; while((i=stream.read())!=-1) { System.out.print((char)i); } }catch(Exception e)
  • 54. 54 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II { System.out.println(e); } } } Connection Oriented Communication Using Socket Java performs the network communication. Sockets enables to transfer data through certain port. Socket class of Java makes it easy to write the socket program Sockets are broken into two types: 1. Datagram sockets (UDP Socket) 1.A Datagram socket uses user datagram protocol (UDP) to send datagrams (self contained units of information) in a connectionless manner. 2.This method does not guarantee delivery of the datagram. 3.The advantage is the datagram sockets require relatively few resources and so communication is faster. 4.Typically request-reply types of application use datagram socket. 5.Java uses java.net.DatagramSocket class to create datagram socket. The java.net.DatagramPacket represents a datagram. 2. Stream Socket (TCP Socket) 1.A stream socket is a “connected” socket through which data is transferred continuously. 2. It use TCP to create a connection between the client and server. TCP/IP sockets are used to implement reliable, bidirectional, persistent, point to point, stream-based connection between hosts on the internet. 3. The benefit of using a stream socket is the communication is reliable. because once connected ,the communication link is available till it is disconnected. So data transmission is done in real-time and data arrives reliably in the same order that it was sent. however this requires more resource. Application like file transfer require a reliable communication. For such application stream sockets are better. 4. Java uses java.net.Socket class to create stream socket for client and java.net.ServerSocket for server.
  • 55. 55 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Difference between Datagram and Stream socket 1.DatagramSocket is for sending UDP datagram Stream socket is used for sending TCP packets. 2. DatagramSocket is a packet based socket. Stream socket is a byte oriented socket. 3. DatagramSocket are unreliable. They may be dropped ,duplicate and delivered out of order. Stream socket is reliable ,if datas are lost on the way, TCP automatically re-sends. 4. DatagramSocket have less overheads and so faster. Stream sockets require more overhead and are slower. 5.Application which use datagram sockets are request-reply type of application such as DNS lookups,PING and SMTP. Stream sockets are used for application like file transfer which require reliability. ServerSocket Class This class is used to create a server that listens for incoming connections from clients. It is possible for client to connect with the server when server socket binds itself to a specific port. The various constructors of the ServerSocket class are: 1. ServerSocket(int port): binds the server socket to the specified port number. If 0 is passed, any free port will be used. However, clients will be unable to access the service unless notified the port number. 2. ServerSocket(int port, int numberOfClients): Binds the server socket to the specified port number and allocates sufficient space to the queue to support the specified number of client sockets. 3. ServerSocket(int port, int numberOfClients, InetAddress address): Binds the server socket to the specified port number and allocates sufficient space to the queue to support the specified number of client sockets and the IP address to which this socket binds The various methods of this class are:
  • 56. 56 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Method Description Socket Class This class is used to represents a TCP client socket, which connects to a server socket and initiate protocol exchanges. The various constructors of this class are: 1. Socket(InetAddress address, int port): creates a socket connected to the specified IP address and port. Can throw an IOException. 2. Socket(String host, int port): creates a socket connected to the specified host and port. Can throw an UnknownHostException or an IOException.
  • 57. 57 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II How to create a server socket 1. Create a ServerSocket object which listen to a specific port. 2. Call the accept() method which accepts client request. This method return the client socket object. 3. Use the socket object to communication with the client import java.net.*; import java.io.*; public class Server { public static void main(String[] ar) { try { int port = 6666; ServerSocket ss = new ServerSocket(port); System.out.println("Waiting for a client..."); Socket socket = ss.accept(); InputStream sin = socket.getInputStream(); DataInputStream in = new DataInputStream(sin);
  • 58. 58 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II String line = null; while(true) { line = in.readUTF(); System.out.println(“Receving line from client : " + line); System.out.println(); } } catch(Exception e) { System.out.println(e); } } } How to create a client socket 1.Create an object of the socket class using the server names and port as parameter. 2.Communication with the server. 3.Close the socket //Client import java.net.*; import java.io.*; public class Client { public static void main(String[] ar) { try { int serverPort = 6666; String address = "127.0.0.1"; InetAddress ipAddress = InetAddress.getByName(address); Socket socket = new Socket(ipAddress, serverPort); OutputStream sout = socket.getOutputStream(); DataOutputStream out = new DataOutputStream(sout);
  • 59. 59 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); String line = null; while(true) { line = keyboard.readLine(); System.out.println("Sending this line to the server..."); out.writeUTF(line); // send the above line to the server. out.flush(); System.out.println(); } } catch(Exception e) { System.out.println(e); } } }
  • 60. 60 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Servlet What Web server? ➢ Apache is a very popular server ➢ 66% of the web sites on the Internet use Apache Apache is: • Full-featured and extensible • Efficient • Robust • Secure (at least, more secure than other servers) • Up to date with current standards • Open source • Free What is Tomcat? Tomcat is the Servlet Engine that handles servlet requests for Apache. ➢Tomcat is a “helper application” for Apache ➢It’s best to think of Tomcat as a “servlet container” What is servlet? A servlet is a web component,managed by a container, that generates dynamic content. ➢ Client sends a request to server ➢ Server starts a servlet ➢ Servlet computes a result for server and does not quit ➢ Server returns response to client ➢ Another client sends a request ➢ Server calls the servlet again
  • 61. 61 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II The Life Cycle of a Servlet The Servlet API 1) Servlet class is loaded The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container. 2) Servlet instance is created The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle. 3) init method is invoked The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below: public void init(ServletConfig config) throws ServletException 4) service method is invoked The service() method of the Servlet is invoked to inform the Servlet about the client requests. This method uses ServletRequest object to collect the data requested by the client. This method uses ServletResponse object to generate the output content. public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
  • 62. 62 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II 5) destroy method is invoked When a servlet is unloaded by the servlet container, its destroy() method is called. This step is only executed once, since a servlet is only unloaded once. public void destroy() Servlet Package It includeTwo packages: ▪ javax.servlet ▪ javax.servlet.http 1.The javax.servlet Package The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate. Interface Description Servlet Declares life cycle methods for a servlet. ServletConfig Allows servlets to get initialization parameters. ServletContext Enables servlets to log events and access Information about their environment. ServletRequest Used to read data from a client request. ServletResponse Used to write data to a client response. Class Description GenericServlet Implements the Servlet and ServletConfig interfaces. ServletInputStream Provides an input stream for reading requests from a client. ServletOutputStream Provides an output stream for writing responses to a client. 2.javax.servlet.http Package Interface Description
  • 63. 63 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II HttpServletRequest Enables servlets to read data from an HTTP request. HttpServletResponse Enables servlets to write data to an HTTP response. HttpSession Allows session data to be read and written. Class Description Cookie Allows state information to be stored on a client machine. HttpServlet Provides methods to handle HTTP requests and responses. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException This method services a GET request Input is from the HttpServletRequest parameter Output is via the HttpServletResponse object, which we have named response
  • 64. 64 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException This method services post request Input is from the HttpServletRequest parameter Output is via the HttpServletResponse object, which we have named response import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B> Hi Vision Academy!"); pw.close(); } } How To retrieve value from the component Using doGet method <html> <body> <center> <form name="Form1" method="get" action="http://localhost:8080/examples/servlets/servlet/GetServlet"> Enter name <input type=text name=”t”> <br> <input type=submit value="Submit"> </body> </html> import java.io.*;
  • 65. 65 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class GetServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String s = request.getParameter("t"); pw.println(s); pw.close(); } } Using doPost method <html> <body> <center> <form name="Form1" method="post" action="http://localhost:8080/examples/servlets/servlet/PostServlet"> Enter name <input type=text name=”t”> <br> <input type=submit value="Submit"> </body> </html> import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class PostServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter();
  • 66. 66 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II String s = request.getParameter("t"); pw.println(s); pw.close(); } } 2 <html> <body> <center> <form name="Form1" action="http://localhost:8080/examples/servlets/servlet/ColorGetServlet"> <B>Color:</B> <select name="color" size="1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <br><br> <input type=submit value="Submit"> </form> </body> </html> import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ColorGetServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>The selected color is: "); pw.println(color); pw.close(); } } HTML-SERVLET COMMUNICATION 1.getParameter():Return the value of named parameter
  • 67. 67 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II 2.getParameterValues():Return array of values of named parameter 3.getPArameterNames():Gives the name of parameter What is a Cookie? A "cookie" is a small piece of information sent by a web server to store on a web browser so it can later be read back from that browser. A cookie’s value identify user Constructor of Cokkie class Constructor Description Cookie() constructs a cookie. Cookie(String name, String value) constructs a cookie with a specified name and value. Method of Cookie class Method Description public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds. public String getName() Returns the name of the cookie. The name cannot be changed after creation. public String getValue() Returns the value of the cookie. public void setName(String name) changes the name of the cookie. public void setValue(String value) changes the value of the cookie. Interface Method Description Public void addCookie(Cookie ck) method of HttpServletResponse interface is used to add cookie in response object. Public Cookie[] getCookies() method of HttpServletRequest interface is used to return all the cookies from the browser. Add cookie’s value <html> <body> <center> <form name="Form1" method="post" action="http://localhost:8080/examples/servlets/servlets/AddCookieServlet"> <B>Enter a value for MyCookie:</B> <input type=”text” name="t1" >
  • 68. 68 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II <input type=submit value="Submit"> </form> </body> </html> import java.io.*; import javax.servlet.*; import javax.servlet.http.*; SOFTWARE DEVELOPMENT USING JAVA public class AddCookieServlet extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); // Get parameter from HTTP request. String data = request.getParameter("t1"); // Create cookie. Cookie cookie = new Cookie("MyCookie", data); // Add cookie to HTTP response. //cookie.setMaxAge( 60 * 60 * 24 );//24 hours response.addCookie(cookie); // Write output to browser. pw.println("<B>MyCookie has been set to"); pw.println(data); pw.close(); } } Accessing cookie’s value import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetCookiesServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter();
  • 69. 69 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II // Get cookies from header of HTTP request. Cookie[] cookies = request.getCookies(); for(int i = 0; i < cookies.length; i++) { String name = cookies[i].getName(); String value = cookies[i].getValue(); pw.println("name = " + name +"; value = " + value); } pw.close(); } } Session Tracking HTTP is a stateless protocol. i.e Each request is independent of the previous one. In some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism. There are several ways through which it can provide unique identifier in request and response. 1. User Authentication – This is the very common way where we user can provide authentication from the login page and then we can pass the authentication information between server and client to maintain the session. This is not very effective method because it wont work if the same user is logged in from different browsers. 2. HTML Hidden Field – We can create a unique hidden field in the HTML and when user starts navigating, we can set its value unique to the user and keep track of the session. This method can’t be used with links because it needs the form to be submitted every time request is made from client to server with the hidden field. Also it’s not secure because we can get the hidden field value from the HTML source and use it to hack the session. 3. URL Rewriting – We can append a session identifier parameter with every request and response to keep track of the session. This is very tedious because we need to keep track of this parameter in every response and make sure it’s not clashing with other parameters. 4. Cookies: A "cookie" is a small piece of information sent by a web server to store on a web browser so it can later be read back from that browser. It can maintain a session with cookies but if the client disables the cookies, then it won’t work. 5. Session Management API:The servlet API provide methods and classes specifically designed to handle session.The HttpSession class provide various session tracking methods public void setAttribute( String name, Object value ) public Object getAttribute( String name )
  • 70. 70 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II public Object removeAttribute( String name ) USING JAA import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class DateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { // Get the HttpSession object. HttpSession hs = request.getSession(true); // Get writer. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String s = (String)hs.getAttribute("course"); if(s!= null) { hs.setAttribute("course", “bcs”); } else pw.println("data is: " + s); } } JDBC USING SERVLET import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello1 extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out=null; try { Connection c = null; res.setContentType("text/html");
  • 71. 71 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II out = res.getWriter(); Class.forName("org.postgresql.Driver"); c=DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat "); // Create a Statement object Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM student"); while(rs.next()) { out.println("rollno is" +rs.getString(1) ); out.println("name is" +rs.getString(2) ); out.println("per is" +rs.getString(3)); } rs.close(); stmt.close(); c.close(); } catch(Exception e) { out.println("error"+e); } } }
  • 72. 72 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II JSP(Java Server Page) Feature • JSP is a server side program. • JSP tags to enable dynamic content creation (Combination of HTML & JSP tag). • JSP provide excellent server side scripting support for creating database driven web applications • JSP enable the developers to directly insert java code into jsp file, this makes the development process very simple and its maintenance also becomes very easy. • JSP pages are efficient, it loads into the web servers memory on receiving the request very first time and the subsequent calls are served within a very short period of time. Life cycle of JSP There are 3 methods in JSP(Life cycle of JSP) A JSP page undergoes 3 phases during life cycle. 1.Translation phase:In this phase,JSP pages get translated into servlet code. 2.Compilation phase:In this phase, the servlet code compiled. The compilation is done only if the page is requested the first time or it is modified. 3.Excution phase:This is final phase where jsp servlet methods are executed.These are jspInit(),_jspService(),jspDestroy() 1.jspInt() • This method is identical to the init() method in Java servlet.
  • 73. 73 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II • This method is called first when the JSP is requested and is used to initialize objects & variables that are used throughout the life of the JSP. public void jspInit() { // Initialization code... } 2.jspDestroy() • This method is identical to the destroy() method in Java servlet. • This method is automatically called when JSP terminates normally. • This method is used for cleanup where resources used during execution of JSP are released. public void jspDestroy() { // Your cleanup code goes here. } 3._jspService() • This method is identical to the service() method in Java servlet. • This method is automatically processing request& sending response. void _jspService(HttpServletRequest request, HttpServletResponse response) { // Service handling code... }
  • 74. 74 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II JSP Architecture JSP Processing: The following steps explain how the web server creates the web page 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.
  • 75. 75 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II • 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, which the servlet engine passes to the web server inside an HTTP response. • The web server forwards the HTTP response to your browser in terms of static HTML content. JSP Tags 1.Comment Tags: It is denoted by <%-- --%> e.g <%-- This comment will not be visible in the page source --%> 2.Declaration statement tags: This tag is used for defining the functions and variables to be used in the JSP. It is denoted by <%! %> Eg <%! int age=25;%> 3.Scriptlet tags: It is used for Java control statements & loop. It is denoted by <% Eg. %> <% for(int i=0;i<=3;i++) { --- --- } %>
  • 76. 76 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II 4.Expression tags: The expression is evaluated and the result is inserted into the HTML page It is denoted by <%= expression %> Eg. <%=age%> 5.Directive tags: The jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet. There are three types of directives: o page directive o include directive o taglib directive 1.page directive The page directive defines attributes that apply to an entire JSP page. It is denoted by <%@ directive attribute="" %> Attribute as follows 1.language: It defines the programming language (underlying language) being used in the page. Syntax of language: <%@ page language="value" %> e.g <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 2.Extends: This attribute is used to extend (inherit) the class like JAVA does Syntax of extends: <%@ page extends="value" %> e.g
  • 77. 77 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II <%@ page extends="demotest.DemoClass" %> 3.Import: It is used to import Java package into the JSP program. Syntax of import: <%@ page import="value" %> e.g <%@page import=” java.sql.*” % 4.contentType: • It defines the character encoding scheme i.e. it is used to set the content type and the character set of the response • The default type of contentType is "text/html; charset=ISO-8859-1". Syntax of the contentType: <%@ page contentType="value" %> e.g <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 5.Session Specifies whether or not the JSP page participates in HTTP sessionsSyntax of session Syntax <%@ page session="true/false"%> e.g <%@ page language="java" contentType="text/html; charset=ISO-8859-1" session="false"%> 6.errorPage: This attribute is used to set the error page for the JSP page if JSP throws an exception and then it redirects to the exception page. Syntax of errorPage:
  • 78. 78 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II <%@ page errorPage="value" %> e.g <%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1" errorPage="errorHandler.jsp"%> 7. PageEncoding: The "pageEncoding" attribute defines the character encoding for JSP page.The default is specified as "ISO-8859-1" if any other is not specified. Syntax <%@ page pageEncoding="vaue" %> Here value specifies the charset value for JSP Example: <%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1" isErrorPage="true"%> 2.include directive: • include directive is used to include one file to the another file • This included file can be HTML, JSP, text files, etc. <%@ include file="/header.jsp" %> e.g a.jsp <%="HELLO bcs"%> p.jsp <%@ include file="p.jsp" %> <%="HELLO mcs"%> 3.taglib directive: JSP taglib directive is used to define the tag library with "taglib" as the prefix, which we can use in JSP. (custom tags allows us to defined our own tags).
  • 79. 79 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II Syntax of taglib directive: <%@ taglib uri="uri" prefix="value"%> Here "uri" attribute is a unique identifier in tag library descriptor and "prefix" attribute is a tag name. e.g <%@ taglib prefix="vtag" uri="http://java.sun.com/jsp/jstl/core" %> How To run JSP? <html> <head> <title> Sachin Sir 9823037693 </title> </head> JSP CODE <body> <%="HELLO Sachin Sir"%> <body> </html> Using Function <html> <head> <title> Sachin Sir 9823037693 Sum of first n numbers </title> </head> <body> <%! int sumoffirst(int n) int sum=0; for(int i=1;i<=n;i++) sum=sum+i; return(sum); } %>
  • 80. 80 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II JSP CODE <p>Sum of first n number: </p> <body> </html> JSP provides several predefined variables(implicit object) Implicit object:These objects are created automatically by JSP container. It can directly use these object.JSP Implicit Objects are also called pre-defined variables No. Object & Description 1 request This is the HttpServletRequest object associated with the request. 2 response This is the HttpServletResponse object associated with the response to the client. 3 out This is the PrintWriter object used to send output to the client. 4 session This is the HttpSession object associated with the request. 5 application This is the ServletContext object associated with the application context. 6 config This is the ServletConfig object associated with the page. <%=sumoffirst(5)%>
  • 81. 81 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II 7 pageContext This encapsulates use of server-specific features like higher performance JspWriters. 8 page This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. 9 Exception The Exception object allows the exception data to be accessed by designated JSP. 1.Display html & jsp page separate l.html <html> <head> <title>Login</title> </head> <body> <form method="post" action="http://localhost:8080/examples/jsp/login.jsp"> Username:<input type="text" name="t1"> <br> Password:<input type="password"name="t2"> <br> <input type="submit" value="Login"> <input type="reset" value="Clear"> </body> </html> Login.jsp <% String s1=request.getParameter("t1"); String s2=request.getParameter("t2"); if(s1.equals("sachin")&&s2.equals("sachin")) out.println("Login Sucessfully"); else out.println("Login incorrect");
  • 82. 82 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II %> Database connection using jsp <%@page import="java.sql.*"%> <%@page import="java.io.*"%> <html> <body> <% try { Class.forName("("org.postgresql.Driver""); con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/ty","postgres","redhat"); Statement sta = con.createStatement(); ResultSet rs=sta.executeQuery("select * from student"); while(rs.next()) { out.println("rollno"+rs.getInt(1)); out.println("name"+rs.getString(2)); out.println("Percentage"+rs.getFloat(3)); } rs.close(); sta.close(); con.close(); } catch(Exception e) { } %> </body> </html> JSP Benefits • Easy to combine static templates,including HTML or XML. • JSP pages compile dynamically into servlets. • JSP makes it easier to author pages "by hand" • JSP tags for invoking JavaBeansTM components Compare servlet &jsp
  • 83. 83 Vision Academy (9823037693/9822506209, http://www.visionacademe.com) (SACHIN SIR MCS,SET) Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) JAVA II JSP Servlets JSP is a webpage scripting language that can generate dynamic content. Servlets are Java programs that are already compiled which also creates dynamic web content. JSP run slower compared to Servlet as it takes compilation time to convert into Java Servlets. Servlets run faster compared to JSP. It’s easier to code in JSP than in Java Servlets. Its little much code to write here. In MVC, jsp act as a view. In MVC, servlet act as a controller. JSP are generally preferred when there is not much processing of data required. servlets are best for use when there is more processing and manipulation involved. The advantage of JSP programming over servlets is that we can build custom tags which can directly call Java beans. There is no such custom tag facility in servlets. We can achieve functionality of JSP at client side by running JavaScript at client side. There are no such methods for servlets. Vision Academy Since 2005 Prof. Sachin Sir(MCS,SET) 9822506209/9823037693 www.visionacademe.com Branch1:Nr Sm Joshi College,Abv Laxmi zerox,Ajikayatara Build,Malwadi Rd,Hadapsar Branch2:Nr AM College,Aditya Gold Society,Nr Allahabad Bank ,Mahadevnager