Java Full PDF
Java Full PDF
COURSE FILE
SEMESTER PATTERN
Syllabus
Text Book:
1. Jamie Jaworski, “Java Unleashed”, SAMS Techmedia Publications,1999.
2. Campione, Walrath and Huml, “The Java Tutorial”, AddisonWesley,1999.
Reference Book:
1.Jim Keogh,” The Complete Reference J2EE”, Tata McGrawHill Publishing Company Ltd,2010.
2. David Sawyer McFarland, “JavaScript And JQuery- The Missing Manual”, Oreilly Publications, 3rd
Edition,2011.
3. Deitel and Deitel, “Java How to Program”, Third Edition, PHI/Pearson Education Asia
Website Link:
1.https://www.javatpoint.com/servlet-tutorial
2. https://www.tutorialspoint.com/java/index.htm
3. https://onlinecourses.nptel.ac.in/noc19_cs84/preview
History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many set-top box
projects. The language, initially called 'Oak' after an oak tree that stood outside Gosling's office, also
went by the name 'Green' and ended up later being renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run
Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software under the terms
of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-source, aside
from a small portion of code to which Sun did not hold the copyright.
Java Syntax
Every programming language has certain rules and regulations that a programmer needs to
follow while writing programs. The respective language compiler checks your program for syntax
rules and validation. Java also has lots of constructs and components that make it easier for
programmers to write quality programs.
The “Hello, World” program in the previous tutorial gave you an idea about the basic structure
of a Java program in detail. Now let’s go to the other constructs/components that a Java program will
include.
Java Conventions
Given below are some of the conventions that a Java programmer needs to follow while programming
in Java.
(i) Class names: In Java, the first letter of class name for every class should be uppercase. For
example, a class salary will be named as per the convention as “Salary”.
If you have a class name that is combined using more than one word then each letter of the first word
will be an uppercase letter.
(iv) Case sensitive: Java programming language is case-sensitive. This means ‘Hi’ and ‘hi’ are two
different parameters.
(v) Main method: The method ‘main’ is the starting point of execution and is a compulsory method in
all Java programs.
Java Identifiers
Identifiers are the names given to various program components like methods, classes, variables,
objects, etc.
An identifier should always start with letters (A-Z/a-z) or an underscore character (_) or
currency character ($).
The identifier cannot have the same name as a Java reserved Keyword.
Beyond the first character, an identifier can have any combination of characters.
In Java, like other language syntax, identifiers are also case-sensitive.
Hence as per the above rules, the following identifiers are valid.
Variables
Java supports the following three types of variables:
Class or static variables: This type of variable can be accessed without an object.
Non-static or instance variables: These variables are member variables which are accessed
with the help of a class object.
Local variables: Local variables are local to a particular block of code and cease to exist out of
this block.
Keywords
There are certain words reserved in Java language for its own use and cannot be used as variable or
identifier names.
The following table gives the list of these words known as “Keywords”.
abstract double int super
assert else interface switch
boolean enum long synchronized
break extends native this
byte final new throw
case finally package throws
catch float private transient
char for protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instance of strictfp
Comments
Comments are the statements that are ignored by the compiler. You can provide comments for your
code to make the code more readable and easy to understand.
int (16-bit)
float (32-bit)
double (64-bit
boolean (true/false)
Operators
Operators are symbols that perform logical and mathematical operations on variables or identifiers.
These variables or identifiers are called Operands.
Decision Making
Also called as control statements. These statements change or control the program execution based on
a particular condition. If the condition is true, a block of code following this condition is executed, else
a different block is executed.
Loops
In programming languages, looping is included to repeatedly execute a block of code. The looping
usually starts with a test and the block of code is executed repeatedly for a fixed number of times
called iterations or till a condition is fulfilled.
ARRAYS
Arrays are nothing but a data structure that is used to hold the data elements of the same type
sequentially.
Java arrays are also similar to arrays in C/C++ and other programming languages.
int[] array = {1, 2, 3, 4, 5}; // it is initialized and declared at the same time.
Arrays can be of any primitive data type or object. Arrays have an instance variable "length" that we
can access to find out how big the array is. Remember that an Array can throw an
IndexOutOfBoundsException. Make use of it to make your code safe.
VECTORS
Unlike arrays, vectors can only hold objects, no primitive data types are allowed. Vectors can grow big
and unbounded. You may want to specify the capacity of the vector but you dont need to. The default
capacity is 10 and it doubles in size every time the capacity is reached.
Just like arrays have the "length" instance variable, Vectors have a .size() method that returns the
current size of the vector.
ENUMERATION
This is an iterator and it is very important concept in data structures for ICS211. An Enumeration lets
us visit every element of a Vector one by one.
Enumeration e = v.elements();
While(e.hasMoreElements()){
Object o = e.nextElement;
Java supports:
Single-dimensional arrays: A sequence of elements of the same type and can be accessed
using an array name.
Multi-dimensional array: Elements are arranged in the form of rows and columns i.e. in a
matrix form.
Java Class & OOPS
A class is a blueprint of any real-life entity, for example, a car. A class in Java consists of data
variables and the methods or functions that operate on these data.
Data variables or member variables and methods depict the behavior of objects which are instances of
the class. This means the state of the entity represented by a class at any given instant is defined by an
object.
Java Interfaces An interface in Java is a collection of method signatures and fields. An interface does
not have an implementation of methods. A class can inherit from the interface and then implement the
interface methods.
Java Packages
Classes and interfaces that have similar functionality or dependency are grouped to form a package.
The package makes modularization of code easier in Java.
The way in which events are handled changed significantly between the original version of Java
(1.0) and all subsequent versions of Java, beginning with version 1.1.
The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events. Its concept is quite
simple: a source generates an event and sends it to one or more listeners. In this scheme, the
listener simply waits until it receives an event. Once an event is received, the listener processes
the event and then returns.
The advantage of this design is that the application logic that processes events is cleanly
separated from the user interface logic that generates those events. A user interface element is
able to “delegate” the processing of an event to a separate piece of code.
In the delegation event model, listeners must register with a source in order to receive an
event notification. This provides an important benefit: notifications are sent only to listeners that
want to receive them. This is a more efficient way to handle events than the design used by the
original Java 1.0 approach. Previously, an event was propagated up the containment hierarchy
until it was handled by a component. This required components to receive events that they did
not process, and it wasted valuable time. The delegation event model eliminates this overhead.
Events
In the delegation model, an event is an object that describes a state change in a source.
Among other causes, an event can be generated as a consequence of a person interacting
with the elements in a graphical user interface.
Some of the activities that cause events to be generated are pressing a button, entering a
character via the keyboard, selecting an item in a list, and clicking the mouse.
Events may also occur that are not directly caused by interactions with a user interface.
Event Sources
A source is an object that generates an event. This occurs when the internal state of that
object changes in some way. Sources may generate more than one type of event.
A source must register listeners in order for the listeners to receive notifications about a
specific type of event.
Each type of event has its own registration method. Here is the general form:
Here, Type is the name of the event, and el is a reference to the event listener. For example,
the method that registers a keyboard event listener is called addKeyListener( ). The method
that registers a mouse motion listener is called addMouseMotionListener( ).
When an event occurs, all registered listeners are notified and receive a copy of the event
object. This is known as multicasting the event. In all cases, notifications are sent only
to listeners that register to receive them.
Some sources may allow only one listener to register. The general form of such a method
is this:
Here, Type is the name of the event, and el is a reference to the event listener.
When such an event occurs, the registered listener is notified. This is known as
A source must also provide a method that allows a listener to unregister an interest in a
specific type of event. The general form of such a method is this:
Here, Type is the name of the event, and el is a reference to the event listener. For
example, to remove a keyboard listener, you would call removeKeyListener( ).
The methods that add or remove listeners are provided by the source that generates
events. For example, the Component class provides methods to add and remove
keyboard and mouse event listeners.
Event Listeners
A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to receive
notifications about specific types of events. Second, it must implement methods to
receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces, such as
those found in java.awt.event. For example, the MouseMotionListener interface
defines two methods to receive notifications when the mouse is dragged or moved. Any
object may receive and process one or both of these events if it provides an
implementation of this interface.
Event Classes
The classes that represent events are at the core of Java’s event handling mechanism. Widely
used Event classes are those defined by AWT and those defined by Swing.
At the root of the Java event class hierarchy is EventObject, which is in java.util. It is
the superclass for all events. Its one constructor is shown here:
EventObject(Object src)
Object getSource( )
int getID( )
To summarize:
4 KeyEvent
On entering the character the Key event is generated.
5 MouseEvent
This event indicates a mouse action occurred in a component.
6 TextEvent
The object of this class represents the text events.
7 WindowEvent
The object of this class represents the change in state of a window.
8 AdjustmentEvent
The object of this class represents the adjustment event emitted by Adjustable
objects.
9 ComponentEvent
The object of this class represents the change in state of a window.
10 ContainerEvent
The object of this class represents the change in state of a window.
11 MouseMotionEvent
The object of this class represents the change in state of a window.
12 PaintEvent
The object of this class represents the change in state of a window.
Event handling has three main components:
Action: What user does is known as action. Example, a click over button. Here, click is the
action performed by the user.
Event: The action done by the component when the user’s action takes place is known
as event. That is, event is generated (not seen, it is software) against action.
Listener: It is an interface that handles the event. That is, the event is caught by the listener
and when caught, immediately executes some method filled up with code. Other way, the
method called gives life to the user action.
Now the object of concerned event class is created automatically and information about the
source and the event get populated with in same object.
Event object is forwarded to the method of registered listener class.
The method is now get executed and returns.
The VK constants specify virtual key codes and are independent of any modifiers, such
as control, shift, or alt.
® KeyEvent is a subclass of InputEvent. Here is one of its constructors:
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
Here, src is a reference to the component that generated the event. The type of the event
is specified by type. The system time at which the key was pressed is passed in when.
The modifiers argument indicates which modifiers were pressed when this key event
occurred. The virtual key code, such as VK_UP, VK_A, and so forth, is passed in code.
The character equivalent (if one exists) is passed in ch. If no valid character exists, then
ch contains CHAR_UNDEFINED.
For KEY_TYPED events, code will contain VK_UNDEFINED.
® The KeyEvent class defines several methods, but probably the most commonly used
ones are getKeyChar( ), which returns the character that was entered, and
getKeyCode(), which returns the key code. Their general forms are shown here:
® There are eight types of mouse events. The MouseEvent class defines the following
integer constants that can be used to identify them:
Here, src is a reference to the component that generated the event. The type of the event is
specified by type. The system time at which the mouse event occurred is passed in when. The
modifiers argument indicates which modifiers were pressed when a mouse event occurred. The
coordinates of the mouse are passed in x and y. The click count is passed in clicks. The
triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.
® Two commonly used methods in this class are getX( ) and getY( ). These return the X
and Y coordinates of the mouse within the component when the event occurred. Their
forms are shown here:
Alternatively, you can use the getPoint( ) method to obtain the coordinates of the mouse.
It is shown here:
Point getPoint( )
It returns a Point object that contains the X,Y coordinates in its integer members: x and y.
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 17
ADVANCED JAVA PROGRAMMING I MSC-CS
® The translatePoint( ) method changes the location of the event. Its form is shown here:
Here, the arguments x and y are added to the coordinates of the event.
® The getClickCount( ) method obtains the number of mouse clicks for this event. Its
signature is shown here: int getClickCount( )
® The isPopupTrigger( ) method tests if this event causes a pop-up menu to appear on this
platform. Its form is shown here:
boolean isPopupTrigger( )
int getButton( )
It returns a value that represents the button that caused the event. For most cases, the
return value will be one of these constants defined by MouseEvent:
int getYOnScreen( )
The getLocationOnScreen( ) method returns a Point object that contains both the X and Y
coordinate. The other two methods return the indicated coordinate.
® Instances of this class describe text events. These are generated by text fields and text
areas when characters are entered by a user or program.
® TextEvent defines the integer constant TEXT_VALUE_CHANGED.
Here, src is a reference to the object that generated this event. The type of the event is
specified by type.
® The TextEvent object does not include the characters currently in the text component
that generated the event. Instead, your program must use other methods associated with
the text component to retrieve that information. This operation differs from other event
objects discussed in this section. Think of a text event notification as a signal to a listener
that it should retrieve information from a specific text component.
There are ten types of window events. The WindowEvent class defines integer constants
that can be used to identify them. The constants and their meanings are shown here:
Here, src is a reference to the object that generated this event. The type of the event is type. The
next three constructors offer more detailed control:
WindowEvent(Window src, int type, Window other) WindowEvent(Window src, int type,
int fromState, int toState)
WindowEvent(Window src, int type, Window other, int fromState, int toState)
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 19
ADVANCED JAVA PROGRAMMING I MSC-CS
Here, other specifies the opposite window when a focus or activation event occurs. The
fromState specifies the prior state of the window, and toState specifies the new state that the
window will have when a window state change occurs.
® A commonly used method in this class is getWindow( ). It returns the Window object
that generated the event. Its general form is shown here:
Window getWindow( )
® WindowEvent also defines methods that return the opposite window (when a focus or
activation event has occurred), the previous window state, and the current window state.
These methods are shown here:
Window getOppositeWindow( )
int getOldState( )
int getNewState( )
Sources of Events
As explained, the delegation event model has two parts: sources and listeners. Listeners are
created by implementing one or more of the interfaces defined by the java.awt.event package.
When an event occurs, the event source invokes the appropriate method defined by the listener
and provides an event object as its argument. Following table lists several commonly used
listener interfaces and provides a brief description of the methods that they define.
This interface defines the actionPerformed( ) method that is invoked when an action event
occurs. Its general form is shown here:
This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method
is called. When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( )
methods are invoked when the mouse is pressed and released, respectively.
Using the delegation event model is actually quite easy. Just follow these two steps:
1. Implement the appropriate interface in the listener so that it can receive the type of event
desired.
2. Implement code to register and unregister (if necessary) the listener as a recipient for the
event notifications.
Remember that a source may generate several types of events. Each event must be registered
separately. Also, an object may register to receive several types of events, but it must implement
all of the interfaces that are required to receive these events.
So, before an application can respond to an event for a particular GUI component, you
must:
1. Create a class that represents the event handler and implements an appropriate interface—
known as an event-listener interface.
2. Indicate that an object of the class from Step 1 should be notified when the event occurs—
known as registering the event handler.
In order to design a listener class we have to implement some listener interfaces. These Listener
interfaces forecast some public abstract callback methods which must be implemented by the
listener class.
If you do not implement the any if the predefined interfaces then your class can not act as a
listener class for a source object.
We can put the event handling code into one of the following places:
Within class
Other class
Inner Class / Anonymous inner class
Example of event handling within a class import
javax.swing.*;
import java.awt.event.*;
class EventDemo extends JFrame implements ActionListener{ JTextField tf;
EventDemo(){
//create components tf=new JTextField();
tf.setBounds(60,50,170,20);
JButton b=new JButton("click me"); b.setBounds(100,120,80,30);
//register listener b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility add(b);add(tf);
setSize(300,300); setLayout(null);
setVisible(true);
package eventhandlingpackage;
import java.awt.event.*;
}
}
};
b.addActionListener(ac); add(b);add(tf);
setSize(300,300); setLayout(null);
setVisible(true);
}
public static void main(String args[]){ new AE3();
}
}
To handle mouse events, you must implement the MouseListener and the
MouseMotionListener interfaces
To handle keyboard events, you use the same general architecture as that shown in the mouse event
example in the preceding section. The difference, of course, is that you will be implementing the
KeyListener interface. Before looking at an example, it is useful to review how key events are
generated.
® When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the
keyPressed( ) event handler. When the key is released, a KEY_RELEASED event is generated and
Thus, each time the user presses a key, at least two and often three events are generated. If all you care
about are actual characters, then you can ignore the information passed by the key press and release
events. However, if your program needs to handle special keys, such as the arrow or function keys,
then it must watch for them through the keyPressed( ) handler.
Adapter Classes
Java provides a special feature, called an adapter class, that can simplify the creation of event handlers
in certain situations. An adapter class provides an empty implementation of all methods in an event
listener interface. Adapter classes are useful when you want to receive and process only some of the
events that are handled by a particular event listener interface. You can define a new class to act as an
event listener by extending one of the adapter classes and implementing only those events in which you
are interested.
Actually problem does not occur with every listener, but occurs with a few. A few listeners contain
more than one abstract method. For example, WindowListener, used for frame closing, comes with 7
abstract methods. We are interested in only one abstract method to close the frame, but being
WindowListener is an interface, we are forced to override remaining 6 methods also, just at least with
empty body. This is the only problem, else fine. Some listeners
like ActionListener comes with only one abstract method and with them no problem at all.
® Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
® Adapters are replacement to listeners. The advantage with adapter is we can override any number of
methods we would like and not all. For example, if we
use WindowAdapter(instead of WindowListener), we can override only one method to close
the frame.
® Adapters make event handling simple. Any listener has more than one abstract method has got a
corresponding adapter class. For example, MouseListener with 5 abstract methods has got a
corresponding adapter known as MouseAdapter.
But ActionListener and ItemListener do not have corresponding adapter class as they contain
only one abstract method.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
Any class which handles events must implement a listener interface for the event type it wishes
to handle. A class can implement any number of listener interfaces.
An adapter class is a class that already implements all the methods in its corresponding interface. Your
class must extend the adapter class by inheritance so you can extend only one adapter class in your
class (Java does not support multiple inheritance). Here are the Java adapter classes and the listener
interfaces they implement.
Inner Classes
® An inner class is a class defined within another class, or even within an expression.
® Listener classes are generally designed with just one purpose in mind: the creation of the listener
object for some GUI object (e.g., a button, window, checkbox, etc...). Given this relationship,
separating the code for the Listener class from the code for the class of the related GUI object
seems to, in a certain sense, work against the notion of the benefits of code encapsulation.
® Fortunately, in Java, within the scope of one class, we are allowed to define one or
more inner classes(or nested classes). (Technically, the compiler turns an inner class into a
regular class file named: OuterClassName$InnerClassName.class.
® Such inner classes can be defined inside the framing class, but outside its methods -- or it may
even be defined inside a method, and they can reference data and methods defined in the outer
class in which it nests.
Multithreading
It enables you to write very efficient programs that maximizes the CPU utilization and
reduces the idle time.
Most I/O devices such as network ports, disk drives or the keyboard are much slower than CPU
A program will spend much of it time just send and receive the information to or
from the devices, which in turn wastes the CPU valuable time.
By using the multithreading, your program can perform another task during this idle time.
For example, while one part of the program is sending a file over the internet, another
part can read the input from the keyboard, while other part can buffer the next block to
send.
It is possible to run two or more threads in multiprocessor or multi core systems
simultaneously.
A thread can be in one of the several states. In general terms, a thread can running. It can
be ready to run as soon as it gets the CPU time. A running thread can be suspended, which is a
temporary halt to its execution. It can later be resumed. A thread can be blocked when waiting
for the resource. A thread can be terminated.
A Thread is similar to simple program that contains single flow of control. It has
beginning, body, and ending. The statements in the body are executed in sequence.
//Body
} //ending
Multithreaded Program
A unique property of the java is that it supports the multithreading. Java enables us the
multiple flows of control in developing the program. Each separate flow of control is thought
as tiny programknown as "thread" that runs in parallel with other threads. In the following
example when the main thread is executing, it may call thread A, as the Thread A is in execution
again a call is mad for Thread B. Now the processor is switched from Thread A to Thread B.
After the task is finished the flow of controlcomes back to the Thread A. The ability of the
language that supports multiple threads is called "Concurrency". Since threads in the java are
small sub programs of the main program and share the same address space, they are called
"light weight processes".
Main
thread
Start
Start
Start
switch
Thread A
Thread B switch Thread C
static Thread.currentThread( )
This method returns a reference to the thread in which it is called. Once you have a reference
to the main thread, you can control it just like any other thread.
Let’s begin by reviewing the following example:
CurrentThreadDemo.java
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
System.out.println(n);
Thread.sleep(1000);
catch (InterruptedException e)
Output
Creation of Thread
Creating the threads in the Java is simple. The threads can be implemented in the form of
object that contains a method "run()". The "run()" method is the heart and soul of any thread. It
makes up the entire body of the thread and is the only method in which the thread behavior can be
implemented.
{ //1 STEP
{ //2 STEP
for(int i=0;i<=5;i++)
System.out.println("The Thread x
}
}
class RunnableTest
{
x r=new x();
Thread threadx=new
Thread(r); threadx.start();
III. Create a thread and call the "start()" method to instantiate the Thread Execution.
Declaring the class
}
Starting the new Thread
To actually to create and run an instance of the thread class, we must write the following:
Example program:
ThreadTest.java
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
for(int k=1;k<=5;k++)
class ThreadTest
System.out.println("main thread
started");
A a=new A();
a.start();
B b=new B();
b.start();
C c=new
C();
c.start();
} FIRST RUN
Second Run: Produces different out put in the second run, because of the processor switching
from onethread to other.
So far, you have been using only two threads: the main thread and one child thread. However,
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 40
ADVANCED JAVA PROGRAMMING I MSC-CS
your program can spawn as many threads as it needs. For example, the following program
creates three child threads:
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
} //end of NewThread
class MultiThreadDemo
{
public static void main(String args[])
{
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try
{
// wait for other threads to end
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
It is often very important to know which thread is ended. This helps to prevent the main from
terminating before the child Thread is terminating. To address this problem "Thread" class
provides two methods: 1) Thread.isAlive() 2) Thread.join().
This method returns the either "TRUE" or "FALSE" . It returns "TRUE" if the thread is alive,
returns "FALSE" otherwise.
While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for
a thread to finish is called join( ), shown here:
This method waits until the thread on which it is called terminates. Its name comes from the
concept of the calling thread waiting until the specified thread joins it. Additional forms of join(
) allow you to specify a maximum amount of time that you want to wait for the specified thread
to terminate.
Example Program:
class DemoJoin
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: " + ob2.t.isAlive());
System.out.println("Thread Three is alive: " + ob3.t.isAlive());
ob2.t.join();
ob3.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}
Thread priorities are used by the thread scheduler to decide when and which thread should be
allowed to run. In theory, higher-priority threads get more CPU time than lower-priority
threads. In practice, the amount of CPU time that a thread gets often depends on several factors
besides its priority. A higher-priority thread can also preempt a lower-priority one. For instance,
when a lower-priority thread is running and a higher-priority thread resumes (from sleeping or
waiting on I/O, for example), it will preempt the lower priority thread.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.
This is its general form:
The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY.
Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify
NORM_PRIORITY, which is currently 5. These priorities are defined as static final variables
within Thread.
You can obtain the current priority setting by calling the getPriority( ) method of Thread,
shown here:
Example Program:
class PTest
{
public static void main(String args[])
{
Synchronization
When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization.
Here, in the following example to threads are accessing the same resource (object) to print the
Table. The Table class contains one method, printTable(int ), which actually prints the table. We
are creating two Threads, Thread1 and Thread2, which are using the same instance of the Table
Resource (object), to print the table. When one thread is using the resource, no other thread is
allowed to access the same resource Table to print the table.
Class Table
{
void printTable(int n)
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
} //end of the Thread1
} //end of Thread2
class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
The output for the above program will be as follow:
Output: 5
100
10
200
15
300
20
400
25
500
In the above output, it can be observed that both the threads are simultaneously accessing the
Table object to print the table. Thread1 prints one line and goes to sleep, 400 milliseconds, and
Thread1 prints its task.
{
//body of the method
}
where synchronized is the keyword, method contains the type, and method_name represents the
name of the method, and para_list indicate the list of the parameters.
Class Table
{
catch(InterruptedException ie)
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
} //end of Thread2
class TestSynchronization1
{
public static void main(String args[])
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 50
ADVANCED JAVA PROGRAMMING I MSC-CS
t2.start();
}
}
Output: 5
10
15
20
25
100
200
300
400
500
In the above output it can be observed that when Thread1 is accessing the Table object,
Thread2 is not allowed to access it. Thread1 preempts the Thread2 from accessing the
printTable() method.
Inter-Thread Communication
If two or more Threads are communicating with each other, it is called "inter thread"
communication. Using the synchronized method, two or more threads can communicate
indirectly. Through, synchronized method, each thread always competes for the resource. This
way of competing is called polling. The polling wastes the much of the CPU valuable time. The
better solution to this problem is, just notify other threads for the resource, when the current
thread has finished its task. This is explicit communication between the threads.
Java addresses this polling problem, using via wait(), notify(), and notifyAll() methods. These
methods are implemented as final methods in Object, so all classes have them. All three
methods can be called only from within a synchronized context.
wait( ) tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify( ).
notify( ) wakes up a thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of
the threads will be granted access.
class Q
{
int n;
boolean valueSet = false;
{
while(!valueSet)
try {
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify()
;return
n;
{
while(valueSet)
try {
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n = n; valueSet = true;
System.out.println("Put: " + n);
notify();
Whenever we want stop a thread we can stop from running using "stop()" method of
threadclass. It's general form will be as follows:
Thread.stop();
This method causes a thread to move from running to dead state. A thread will also
move todead state automatically when it reaches the end of its method.
Blocking Thread
A thread can be temporarily suspended or blocked from entering into the runnable and
running state by using the following methods:
These methods cause the thread to go into the blocked state. The thread will return to
the runnable state when the specified time is elapsed in the case of sleep(), the resume()
method is invokedin the case of suspend(), and the notify() method is called in the case of
wait().
Example program:
catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class SuspendResume
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try
{
Thread.sleep(1000); ob1.t.suspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.t.resume();
System.out.println("Resuming thread One");
ob2.t.suspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.t.resume();
System.out.println("Resuming thread Two");
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
// wait for threads to finish
try
{
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
During the life time of the thread, there are many states it can enter. They include the following:
Newborn state
Runnable State
Running State
Blocked state
Dead state
A thread can always in any one of the five states. It can move from one state to other via
variety ofways as shown in the fig.
Newborn state Stop
Start
Running Runnable
Fig: Life State State
Cycle of Yield
Thread Stop
suspend() resume()
sleep() notify()
wait()
Blocked State
Newborn State: When we create a thread it is said to be in the new born state. At this state we
can do the following:
schedule it for running using the start() method.
Kill it using stop() method.
Runnable State: A runnable state means that a thread is ready for execution and waiting for the
availability of the processor. That is the thread has joined the queue of the threads for execution.
If all the threads have equal priority, then they are given time slots for execution in the round
rabin fashion, first-come, first-serve manner. The thread that relinquishes the control will join
the queue at the end and again waits for its turn. This is known as time slicing.
Running State:
Running state: Running state means that the processor has given its time to the thread for it
execution. The thread runs until it relinquishes the control or it is preempted by the other higher
priority thread. As shown in the fig. a running thread can be preempted using the suspen(), or
wait(), or sleep() methods.
Blocked state: A thread is said to be in the blocked state when it is prevented from entering into
runnable state and subsequently the running state.
Dead state: Every thread has a life cycle. A running thread ends its life when it has completed
execution. It is a natural death. However we also can kill the thread by sending the stop() message
to it at any time.
Thread Exceptions
Note that a call to the sleep() method is always enclosed in try/ catch block. This is necessary
because the sleep() method throws an exception, which should be caught. If we fail to catch the
exception the program will not compile.
try
{
Thread.sleep(1000);
catch(Exception e)
{
Deadlock
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another thread and second thread is waiting for an
object lock that is acquired by first thread. Since, both threads are waiting for each other to
release the lock, the condition is called deadlock.
Thread Thread
1 2
Y
Here, in the above figure, the resource X is held by Thread1, and at the same time the Thread1 is
trying to access the resource which is held by the Thread2. This is causing the circular
dependency between two Threads. This is called, Deadlock.
Thread.sleep(100);catchException()
{
System.out.println(e);
}
synchronized (resource2)
{
System.out.println("Thread 1: locked resource 2");
}
}
} //end of run()
}; //end of t1
synchronized (resource1)
{
System.out.println("Thread 2: locked resource 1");
}
}
}//end of run()
}; //end of t2
t1.start();
t2.start();}}
InetAddress
TCP/ IP client sockets
TCP/ IP server sockets
URL
URL Connection
Datagrams
Client/ Server application using RMI.
Networking Basics
In Java Networking is a concept of connecting two or more computing devices together so that
we can share resources.
Java socket programming provides facility to share data between different computing devices.
1. Sharing resources
2. Centralize software management
1) IP Address
2) Protocol
3) Port Number
6) Socket
java.net package
The java.net package provides many classes to deal with networking applications in Java.
A list of these classes is given below:
InetAddress class
Method Description
public static InetAddress getByName(String host) it returns the instance of InetAddress
throws UnknownHostException containing LocalHost IP and name.
public static InetAddress getLocalHost() throws it returns the instance of InetAdddress
UnknownHostException 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.
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}
Output:
Socket Programming
Java Socket programming is used for communication between the applications running on
different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
The client in socket programming must know two information:
TCP/IP Client
Socket Socket class
Methods:
Metho Descriptio
d n
1) public InputStream getInputStream() returns the InputStream attached with this socket.
2) public OutputStream returns the OutputStream attached with this
getOutputStream() socket.
3) public synchronized void close() closes this socket
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Methods:
Method Description
1) public Socket accept() returns the socket and establish a connection
between server and client.
2) public synchronized void close() closes the server socket.
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 63
ADVANCED JAVA PROGRAMMING I MSC-CS
Creating Server:
To create the server application, we need to create the instance of ServerSocket class.
Here, we are using 6666 port number for the communication between the client and server.
You may also choose any other port number.
The accept() method waits for the client. If clients connects with the given port number, it
returns an instance of Socket.
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection and waits for the client
Creating Client:
To create the client application, we need to create the instance of Socket class.
Here, we need to pass the IP address or hostname of the Server and a port number.
Here, we are using "localhost" because our server is running on same system.
Socket s=new Socket("localhost",6666);
URL
URL(String spec)
Creates an instance of a URL from the String representation.
URL(String protocol, String host, int port, String file)
Creates an instance of a URL from the given protocol, host, port number, and file.
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates an instance of a URL from the given protocol, host, port number, file, and
handler.
URL(String protocol, String host, String file)
Creates an instance of a URL from the given protocol name, host name, and file name.
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 64
ADVANCED JAVA PROGRAMMING I MSC-CS
URL(URL context, String spec)
Creates an instance of a URL by parsing the given spec within a specified context.
URL(URL context, String spec, URLStreamHandler handler)
Creates an instance of a URL by parsing the given spec with the specified handler
within a given context.
The java.net.URL class provides many methods. The important methods of URL class are
given below.
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 String getAuthority() It returns the authority of the URL.
public String toString() It returns the string representation of the URL.
public String getQuery() It returns the query string of the URL.
public String getDefaultPort() It returns the default port of the URL.
public URLConnection openConnection() It returns the instance of URLConnection i.e.
associated with this URL.
public boolean equals(Object obj) It compares the URL with the given object.
public Object getContent() It returns the content of the URL.
public String getRef() It returns the anchor or reference of the URL.
//URLDemo.java import
java.net.*; public class
URLDemo{
Output:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
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.
The URLConnection class provides many methods, we can display all the data of a webpage by
using the getInputStream() method.
The getInputStream() method returns all the data of the specified URL in the stream that can be
read and displayed.
Example of URLConnection class
import java.io.*;
import java.net.*;
}
}catch(Exception e){System.out.println(e);}
}
}
The Java HttpURLConnection class is http specific URLConnection. It works for HTTP
protocol only.
By the help of HttpURLConnection class, you can information of any HTTP URL such as
header information, status code, response code etc.
The java.net.HttpURLConnection is subclass of URLConnection class.
The openConnection() method of URL class returns the object of URLConnection class.
Syntax:public URLConnection openConnection()throws IOException{}
import java.net.*;
Output:
DatagramSocket class
DatagramPacket class
//DSen
der.jav
a
import
java.ne
t.*;
public
class
DSend
er{
DatagramSocket ds = new
DatagramSocket(); String str =
"Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");
//DRec
eiver.ja
va
import
java.ne
t.*;
public
class
DRecei
ver{
DatagramPacket dp = new
DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0,
dp.getLength()); System.out.println(str);
ds.close();
}
}
The Java Media Techniques
There are a number of APIs that fall within the purview of media and
communications. These, and what they enable in the Java platform, include:
Sun has also discussed several less well-defined Media APIs, both at JavaOne in March 1998
and in previous public forums:
Image basics
Java is popular because it has the promise of creating rich graphical experiences. Java has a
number of classes designed to deal with images and image manipulation. Java follows both
JPEG (Joint Photographic Expert Group) and GIF (Graphics Interchange Format ) as the
formats for image data. In general , JPEG images are better suited to natural color images
such as photo graphs, and GIF images are best for graphical logos, rules, and button images.
There are five types of objects that one will need to deal with or at least understand
when dealing with Images. These are :
Image
ImageObserver
ImageProducer
ImageConsumer
ImageFilter
These are basics, all of them defined in java.awt package, and many more also related
to image manipulation.
Image class: With this class one can load an image object that obtains its pixel data from a
specific URL. The most common way to do this is through the use of the getImage() method
of the java.applet.Applet class, which has the following two forms :
public Image getImage (URL url ) - returns an Image object given a URL.
public Image getImage (URL url, String name )- returns an Image object given a ba
se URL and file name.
import java.applet.*;
import java.awt.*;
public class ImageTest extends Applet {
Image mona;
public void init ( ) {
mona = getImage (getDocumentBase ( ), "monalisa.gif ");
}
In the above mentioned applet, first init() method loads the image object from the
specified URL and file name. The paint() method uses drawImage() method ( it is defined in
Component class); it has the form as below :
public abstract boolean drawImage ( Image imageName, int x, int y, ImageObserver
imgObs );
imageName is the image reference that has to be drawn, the x, y coordinates to paint
at, and imgObs is the ImageObserver that can monitors an image while it loads, we will learn
more about it during the subsequent discussion. In the example Illustration 9.3, this represents
the default ImageObserver.
When this applet runs, it starts loading "monalisa.gif " in the init() method. On screen
you can see the image as it loads from the Network ( or local machine), because the default
ImageObserver interface calls paint() method every time more image data arrives from the
source.
ImageObserver class :ImageObserver is an abstract interface used to get notification as an
image is being generated. As we have seen in the last example, the drawImage() method
takes both an Image object and an ImageObserver object. In the case of an ImageObserver
object, because ImageObserver is an interface, we need to pass a reference to an instance of a
class that implements the ImageObserver interface. Classes that implements the
ImageObserver interface are required to have an imageUpdate() method as follows :
public abstract boolean imageUpdate (Image img, int status , int x, int y, int width, int
height);
Before going to know the use of this method in an applet, let us see about the various
arguments in it :
Image img - the Image object references that has to be drawn on the applet.
int status - this gives us the status information of the image "img" being processed. The "
status" integer is tested bit wise against the value of one or more flags. The available flags
and the information they provide are listed in Table 9.1
int (x, y, width, height )- is a configuration for rectangle that reports different information
about the image under loading.
Bits Indicator
WIDTH The width of the base image is now available and can be taken from
the width argument.
HEIGHT The height of the base image is now available and can be taken from
the height argument
PROPERTIES The properties of the image are now available. One can access the properties
with img.properties.
SOMEBITS More pixels needed for drawing a scaled variation of the image are available.
The bounding box of the new pixels can be taken from the x, y, width,
and height argu ments.
FRAMEBITS Another complete frame of a multiple frame image, which was previously
drawn, is now available to be redrawn. The x, y, height, and width arguments
should be ignored.
ALLBITS The image being drawn is now complete and can be drawn again in its final
form. The x , y, width, and height arguments are no longer meaningful.
ERROR An image that was being tracked has encountered an error. No further image
informa tion will be available and drawing the image will fail.
ABORT An image that was being tracked was aborted before production was complete.
No more image information will become available.
Now let us look at an example that uses ImageObserver to see how many scan lines of the
image have been processed and then prints the progress to the console.
import java.applet.*;
import java.awt.*;
import java.awt. image.*;
public class ImageLoadTest extends Applet implement ImageObserver {
image mona;
Dimension d;
int progress;
boolean loaded;
public void init ( ) {
mona = getImage ( getDocumentBase ( ), "monalisa.gif " );
loaded = false;
progress = 0;
}
public void paint (Graphics g ) {
d = this.size;
This applet, loads an image just as in Illustration 9.3. The difference in this example is that
we are implementing our own imageUpdate() method over the default one. The
imageUpdate() method processes the status of the image load. A summary of the status is
passed in through info, against which the static variable ALLBITS is tested. If we have not
yet received all of the bits in our image, we add the height value to the total number of scan
line processed which will be printed to the system console. The run() method repaints the
applet five times a second (every 200 milliseconds) while the image "mona" is not loaded.
How long the status monitor will run depends on how quickly the Network connection can
deliver the image date.
ImageProducer class :ImageProducer is an abstract interface for objects that want to
produce data for Images. An object that implements the ImageProducer interface will supply
integer or byte arrays that represent image data. The createImage() method (will be discussed
shortly ) takes an ImageProducer object and returns an Image object.
We will examine a valuable class called MemoryImageSource that implements
ImageProducer. We will create a new Image object from data generated by this producer.
MemoryImageSource : It is a class used to create a new Image from an array of pixels. Here
is a constructor used to create a MemoryImageSource object :
public ImageProducer MemoryImageSource (int width, int height, int pixel[ ],int offset,
int scan linewidth);
The MemoryImageSource object is constructed out of an array of integers pixel[ ], in the
default RGB color model to produce data for an image object. The constructor for
MemoryImageSource also takes the width and height of the result, the offset into the pixel
array, and the width of a scan line, This constructor returns an ImageProducer object which is
used with createImage() to result in a usable image. Following is an illustration of
ImageProducer.
Import java.applet.*;
import java.awt.*;
import java.awt.image.*;
public class MemoryImageProduce extends Applet {
Image art;
Dimension d;
public void init ( ) {
generateImage ( );
}
int r, g, b;
for (int y = 0 ; y < d.height; y++ ) { // Create a set of pixels
for (int x = 0, x < d.width; x++ ) {
r = (x ^ y ) & 0xff;
g = ( x * 2 ^ y * 2 ) & 0xff ;
b = ( x* 4 ^ y * 4 ) 0xff ;
pixels [ i++ ] = (255< 24 ) | (r < 16 ) | (g < 8) | b;
}
}
art = createImage( new MemoryImageSource( d.width, pixels, 0,
d.width ));
}
public void paint( Graphics g )
g.drawImage (art, 0, 0, this ));
}
}
Here, the data for the new MemoryImageSource is created in the generateImage() method.
An array of integers is created to hold pixel values; Then integer array elements get shifted
into a pixel in the pixel array. Finally, we call createImage() to create a new Image from the
'pixels' array with MemoryImageSource.
Audio basics
To play an audio data, it requires a specific format that the working platform can support.
Java can play back audio data over a wide range of platforms. According to Java convention,
all audio data should come from a URL ( Universal Resource Locator ) in a .au audio file. In
order to use existing sounds in formats such as .wav or .aiff, one need to convert these to .au
using a sound program that supports audio conversion. If one try to use .wav then Java is
unable to support it and throws an InvalidAudioFormatException, which will not play the
audio. The .au file refers to an 8-bit, 8Khz encoded audio file. This format doesn't represent
the state of the art in audio fidelity, but is adequate for most sound clips.
There are two ways to play a sound file from an applet. The first way to play a sound is
through the play() method and the other through the AudioClip of the Applet class object.
Using play() method :This method comes in two versions, both of which take a URL for a
sound file, load the file into the memory, and then play the sound for one time. The play()
method is as follows :
public void play (URL url ) - plays an audio clip if the audio clip referred to by the
URL is found.
public void play (URL url, String name) - same as the previous method, but uses a b
ase URL and file name to locate the audio file.
import java.applet.*;
import java.awt.*;
public class AudioPlayTest extends Applet {
public void init ( ) { // To Place a Play button in
the applet
setLayout (new FlowLayout (FlowLayout. CENTER ));
Button playButton = new Button ("Play" );
add (playButton );
}
This applet simply plays the audio file bell.au which is located in the audio sub directory of
the directory of the HTML file that loaded the applet. The audio file is cached in memory
before playing it.
Note : URL actually a source of an object in Internet site. A typical URL which is actually
having various component may look like as below :
Here, we have specified an audio file "music.au" which is available in the sub directory
"audio" at the server node "sun".
There are two methods defined in Applet class, getDocumentBase() and getCodeBase()
which are very useful to load data from the directory that had the HTML file that started the
applet(document base), and the directory that the class file was loaded from (code base ).
These two methods return a URL object.
Using Audio clip object :The disadvantage of using the play() method is that the first time
you call it with a given audio file, it will have to down load the file if it hasn't been used
before. This can happen responsiveness in cases like the previous example, where we want to
play the sound in response to a user action, and the user ends up waiting for the sound to load
in response to hitting a button. Also, the play() method is present only in the applet, which
means that to use it from a component, or from within a thread, we need to have a reference
to the applet. Last, the play() method plays a sound only once and must be called again if one
wants to play the sound next.
The AudioClip object solves many of these limitations. To obtain an AudioClip object, one
has to call the Applet's getAudioClip() method, which is defined as follows :
public AudioClip getAudioClip (URL url ) - returns an AudioClip object. This meth
od will not return until the AudioClip has been loaded from the specified URL, so one should
consider placing it in a separate thread if the file is expected to take a while to down load.
public AudioClip getAudioClip (URL url, String name ) - same as the previous met
hod, but finds the audio file using the base URL and file name.
The AudioClip object specifies three methods which are stated below :
Here, audio played by the AudioClip() is asynchronous play that can be possible with the abo
ve three methods. Following is the Illustration 9.2 of an applet that plays a sound as long as th
e applet is on - screen or until the 'Stop' button is clicked :
import java.applet.*;
import java.awt.*;
public class AudioClipTest extends Applet {
AudioClip flute ;
AudioClip piano ;
public void init ( ) { // applet initialize
setLayout (new FlowLayout (FlowLayout.CENTER ));
Button testButton = new Button ( "Start" );
add(testButton);
testButton = new Button( "Continue");
add(testButton);
testButton = new Button ( "Stop");
add(testButton);
flute = getAudioClip( getDocumentBase( ), "flute.au");
piano = getAudioClip( getDocumentBase( ), "piano.au");
}
public void start( ) { // Continue the play of Piano
piano.loop( );
}
public void stop( ) { // Stop the Piano play
piano.stop( );
}
public boolean action( Event e, Object button) {
if( "Start".equals(button) )
flute.play( );
if( "Continue".quals(button) )
piano.loop( );
if ( "Stop".equals(button) )
piano.stop( );
return true;
}
}
In the above illustration, applet loads two audio clips vide its init() method. First is "flute.au"
and the second is "piano.au". The init() method will not finish until the sounds have been
loaded. When the applet's start() is called, it starts the "piano.au". The thread of an event
driven method action() is started, thus, if user hit "Start" button the "flute.au" audio clip will
come into play. Note that, two audio clips will then come into play simultaneously. Thus,
using AudioClip object multiple audio can be played, provided that the working platform
supports multiple audio channel. The play will continue until the applet is closed.
In most cases, this evasion seems to be sufficient except for the MIDI
(Musical Instrument Digital Interface) file format. A MIDI audio file is
sufficiently different than the others in that it is not an actual recording as AU
or WAV files are. MIDI files are computer programs, which instruct a
synthesizer to produce sounds. Therefore, one cannot rely on utility
programs to convert MIDI files to AU files. JavaSoft has addressed MIDI in
its recently released Java Media API.
import java.applet.*;
import java.awt.*;
play(getCodeBase(),"spacemusic.au");
Most applications that utilize audio provide the user with a mechanism to
play the audio clip when they are ready to hear it. They also allow the user to
replay the audio clip if they want to hear it again. The second Java audio
example adds a “play” button to the applet. The output screen for the Sound2
applet is displayed in Figure.
import java.applet.*;
import java.awt.*;
Butto play;
AudioClip aclip;
play = new
Button("Play");add(play);
if(arg.equals("Play"))
if(aclip == null)
} // end of action
}
The audio clip is loaded at initialization time using the following Java statement:
When the “play” pushbutton is pressed, the Sound2 applet will gain control
in its action method. The audio clip will be played using the play method of
the AudioClip class. If the audio clip has not been successfully loaded, the
action method will print a message out accordingly.
Two pushbuttons are provided. When the user presses the “Loop”
pushbutton, the audio clip is played using the loop method of the AudioClip
class. This method differs from the play method in that it will continuously
play the audio clip in a loop. The stop method of the AudioClip class is used
to stop playing the clip. The source code for this final Java audio example is
given in Figure 17.
Similar to MIDI support, the base Java classes in the latest level of the JDK
do not support video playback. This is most probably due to the fact that
there are numerous non-Java video solutions available for the Internet today.
STANDARD VIDEO
Downloading and playing stored video files over the Internet is the older of the
two available video playback approaches. Here, digital video files are stored on a
server (typically in MPEG1or QuickTime Movie format) and, when someone
wants to access the video, they must download it in full before viewing
Button loop;
Button stop;
loopClip.loop();
STREAMING VIDEO
Streaming video (and audio) represents a second and more complex area of
video on the Internet. Streaming involves the delivery of video or audio "in
real time" through a number of techniques, including some that place several
frames of video into a buffer on the client's hard drive, and then begin
playing the video, as more files are placed into the buffer
Each streaming video solution defines its own proprietary movie file format
with a corresponding encoder utility that converts a standard movie file such
as AVI or MPEG to their own native format.
The Java Media API defines a set of multimedia classes which support a
wide range of rich, interactive media on and off the Web, including audio,
video, 2D, 3D, animation, telephony, and collaboration
The Java Media API is composed of several distinct components, each
associated with either a specific type of media (audio, video, 2D, 3D), or a
media-related activity (animation, collaboration, telephony). Collectively,
these interfaces provide Java Language programmers with the ability to
handle a wide variety of different media types within their applications and
applets.
The Java Media API is highly extensible. The API accommodates today's
large and ever- changing suite of media transports, containers, and encoding
formats, and allows the addition of new media-related functionality as they
become available.
MIDI API - Provides support for timed-event streams. It uses the Media
Framework for synchronization with other activities, and for an
extensibility mechanism for new synthesizers and effects.
Java Share API - Provides the basic abstraction for live, two-way, multi-
party communication between objects over a variety of networks and
transport protocols. The API enables synchronization and session
management, and allows sharing of both "collaboration-aware" and
"collaboration-unaware" applets.
UNIT –II
The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java.
The RMI allows an object to invoke methods on an object running in another JVM.
The RMI provides remote communication between the applications using two objects
stub and skeleton.
RMI uses stub and skeleton object for communication with the remote object.
Remote object is an object whose method can be invoked from another JVM.
RMI Registry
• RMI registry is a namespace on which all server objects are placed. Each time the
server creates an object, it registers this object with the RMIregistry
(using bind() or reBind() methods). These are registered using a unique name known
as bind name.
• To invoke a remote object, the client needs a reference of that object. At that time, the
client fetches the object from the registry using its bind name
(using lookup() method).
Goals of RMI
• To minimize the complexity of the application.
• To preserve type safety.
• Distributed garbage collection.
• Minimize the difference between working with local and remote objects.
Skeleton
The skeleton is an object, acts as a gateway for the server side object.
All the incoming requests are routed through it.
When the skeleton receives the incoming request, it does the following tasks:
1. It reads the parameter for the remote method
2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.
In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons.
If any application performs these tasks, it can be distributed application.
The RMI application has all these features, so it is called the distributed application.
RMI Example
The following 6 steps given are to write the RMI program:
3. Compile the implementation class and create the stub and skeleton objects using
thermic tool
4. Start the registry service by rmiregistry tool
In this example, we have followed all the 6 steps to create and run the rmi application.
The client application need only two files, remote interface and client application.
In the rmi application, both client and server interacts with the remote interface.
The client application invokes methods on the proxy object, RMI sends the request to
theremote JVM.
The return value is sent back to the proxy object and then to the client application.
For creating the remote interface, extend the Remote interface and declare the
RemoteException with all the methods of the remote interface.
Here, we are creating a remote interface that extends the Remote interface.
There is only one method named add() and it declares RemoteException.
import java.rmi.*;
public interface Adder extends Remote
{
public int add(int x,int y)throws RemoteException;
}
Now provide the implementation of the remote interface. For providing the
implementation of the Remote interface, we need to
o Either extend the UnicastRemoteObject class, (or)
o Use the exportObject() method of the UnicastRemoteObject class
In case, you extend the UnicastRemoteObject class, you must define a constructor that
declares RemoteException.
import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements
Adder{ AdderRemote()throws RemoteException{
super();
}
public int add(int x,int y){return x+y;}
}
3) Create the stub and skeleton objects using the rmic tool
Next step is to create stub and skeleton objects using the rmi compiler.
The rmic tool invokes the RMI compiler and creates stub and skeleton objects.
rmic AdderRemote
rmiregistry 5000
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 91
Advanced java programming I Msc (cs)
In this example, we are binding the remote object by the name sonoo.
import java.rmi.*;
import java.rmi.registry.*;
public class MyServer{
public static void main(String args[]){
try{
Adder stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/sonoo",stub);
}catch(Exception e){System.out.println(e);}
}
}
At the client we are getting the stub object by the lookup() method of the Naming class
and invoking the method on this object.
In this example, we are running the server and client applications, in the same machine
so we are using localhost.
If you want to access the remote object from another machine, change the localhost to
the host name (or IP address) where the remote object is located.
import java.rmi.*;
public class MyClient{
public static void main(String args[]){
try{
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println(stub.add(34,4));
}catch(Exception e){}
}
}
• The RMI daemon, rmid, provides a Java virtual machine from which other
JVM instances may be spawned
The Remote Interface
import java.rmi.*;
java.rmi.activation.Activatable
import java.rmi.*;
import java.rmi.activation.*;
• The job of the "setup" class is to create all the information necessary for the
activatable class, without necessarily creating an instance of the remote object
• The setup class passes the information about the activatable class to rmid, registers
a remote reference (an instance of the activatable class's stub class) and an
• identifier (name) with the rmiregistry, and then the setup class may exit
• Create an ActivationGroupinstance
• Create an ActivationDescinstance
Class Summary
The Activatable class provides support for
remote objects that require persistent access
Activatable
over time and that can be activated by the
system.
An activation descriptor contains the
ActivationDesc
information necessary to activate an object:
An ActivationGroup is responsible for creating
new instances of "activatable" objects in its
ActivationGroup
group, informing its ActivationMonitor when
either:
ActivationGroup_Stub is a stub class for the
subclasses
ActivationGroup_Stub of java.rmi.activation.ActivationGroup that are
exported as
a java.rmi.server.UnicastRemoteObject.
An activation group descriptor contains the
ActivationGroupDesc information necessary to create/recreate an
activation group in which to activate objects.
Startup options for ActivationGroup
ActivationGroupDesc.CommandEnvironment
implementations.
The identifier for a registered activation group
ActivationGroupID serves several purposes: identifies the group
uniquely within the activation system,
Activation makes use of special identifiers to
ActivationID denote remote objects that can be activated
over time.
Package java.rmi.activation
Interface Summary
An ActivationInstantiator is responsible for creating instances of
ActivationInstantiator
"activatable" objects.
An ActivationMonitor is specific to an ActivationGroup and is
ActivationMonitor obtained when a group is reported active via a call
to ActivationSystem.activeGroup (this is done internally).
The ActivationSystem provides a means for registering groups
ActivationSystem
and "activatable" objects to be activated within those groups.
Activator The Activator facilitates remote object activation.
Exception Summary
This exception is thrown by the RMI runtime when activation fails
ActivateFailedException
during a remote call to an activatable object.
ActivationException General exception used by the activation interfaces.
An UnknownGroupException is thrown by methods of classes and
interfaces in the java.rmi.activation package when
UnknownGroupException
the ActivationGroupID parameter to the method is determined to be
invalid, i.e., not known by the ActivationSystem.
An UnknownObjectException is thrown by methods of classes and
interfaces in the java.rmi.activation package when
UnknownObjectException
the ActivationID parameter to the method is determined to be
invalid.
Serialization in Java:
It is a mechanism of writing the state of an object into a byte-stream. It is mainly used in
Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization where byte-stream is converted into an
object. The serialization and deserialization process is platform-independent, it means you can
serialize an object on one platform and deserialize it on a different platform.
For serializing the bject ,wec all the writeObject() method of ObjectOutputStream class, and
for deserialization we call the readObject() method of ObjectInputStream class.
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes
so that the objects of these classes may get a certain capability. The Cloneable and Remote are also
marker interfaces.
The Serializable interface must be implemented by the class whose object needs to be persisted.
The String class and all the wrapper classes implement the java.io.Serializable interface by default.
Let's see the example given below:
Student.java
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
In the above example, Student class implements Serializable interface. Now its objects can be
converted into stream. The main class implementation of is showed in the next code.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to streams.
Building distributed applications is difficult because you must take into account several issues, such as
partial failure, increased latency, distributed persistence, and language compatibility.
Java Spaces
The JavaSpaces technology is a simple and powerful high-level tool for building distributed
and collaborative applications. Based on the concept of shared network -based space that serves as
both object storage and exchange area, it provides a simple API that is easy to learn and yet expressive
for building sophisticated distributed applications.
Distributed Computing
The JavaSpaces technology is a high-level tool for building distributed applications, and it can
also be used as a coordination tool. A marked departure from classic distributed models that rely on
message passing or RMI, the JavaSpaces model views a distributed application as a collection of
processes that cooperate through the flow of objects into and out of one or more spaces.
It should provide a platform that simplifies the design and implementation of distributed computing
systems.
The client side should have few classes, both to keep the client simple and to speed the
downloading of client classes.
The client side should have a small footprint because it will run on computers with limited local
memory.
A variety of implementations should be possible.
It should be possible to create a replicated JavaSpaces service.
The data you can store there is persistent and later searchable. But a JavaSpaces service is not a
relational or object database. JavaSpaces services are not used primarily as data repositories. They are
designed for a different purpose than either relational or object databases.
Although a JavaSpaces service functions somewhat like a file system and somewhat like a
database, it is neither. The key differences between JavaSpaces technology and databases are the
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 98
Advanced java programming I Msc (cs)
following:
Relational databases understand the data they store and manipulate it directly through query
languages such as SQL. JavaSpaces services, on the other hand, store entries that they understand
only by type and the serialized form of each field. As a result, there are no general queries in the
JavaSpaces application design, only "exact match" or "don't care" for a given field.
Object databases provide an object-oriented image of stored data that can be modified and used,
almost as if it were transient memory. JavaSpaces systems do not provide a nearly transparent
persistent or transient layer, and they work only on copies of entries.
Application components (or processes) use the persistent storage of a space to store objects and to
communicate. The components coordinate actions by exchanging objects through spaces; the objects
do not communicate directly. Processes interact with a space through a simple set of operations.
You can invoke four primary operations on a JavaSpaces service:
write(): Writes new objects into a space
take(): Retrieves objects from a space
read(): Makes a copy of objects in a space
notify: Notifies a specified object when entries that match the given template are written into
a space
Both the read() and take() methods have variants: readIfExists() and takeIfExists(). If they are
called with a zero timeout, then they are equivalent to their counterpart. The timeout parameter comes
into effect only when a transaction is used.
Each operation has parameters that are entries. Some are templates, which are a kind of
entry. The write() operation is a store operation. The read() and take() operations are a combination of
search and fetch operations. The notify method sets up repeated search operations as entries are
written to the space. If a take() or read() operation doesn't find an object, the process can wait until an
object arrives.
Unlike conventional object stores, objects are passive data. Therefore, processes do not modify
objects in the space or invoke their methods directly. In order to modify an object, a process must
explicitly remove, update, and reinsert it into the space.
A JavaSpaces service holds entries, each of which is a typed group of objects expressed in a
class that implements the interface net.jini.core.entry.Entry. Once an entry is written into a JavaSpaces
service, it can be used in future look-up operations. Looking up entries is performed using templates,
which are entry objects that have some or all of their fields set to specified values that must be
matched exactly. All remaining fields, which are not used in the lookup, are left as wildcards.
There are two look-up operations: read() and take(). The read() method returns either an entry
that matches the template or an indication that no match was found. The take() method operates
like read(), but if a match is found, the entry is removed from the space.
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 99
Advanced java programming I Msc (cs)
All operations are invoked on an object that implements the net.jini.space.JavaSpace interface. A
space stores entries, each of which is a collection of typed objects that implements the Entry interface.
Code Sample 1 shows a MessageEntry that contains one field: content, which is null by default.
Information on how to compile and run the sample application appears later in this article.
The write() operation places a copy of an entry into the given JavaSpace service, and
the Entry passed is not affected by the operation. Each write() operation places a new Entry into the
space even if the same Entry object is used in more than one write().
If you like, you can change the lease (when the write() operation is invoked) to one hour as follows: >
space.write(msg, null, 60 * 60 * 1000);
write()Lease
Once the entry exists in the space, any process with access to the space can perform a read() on
it. To read an entry, a template is used, which is an entry that may have one or more of its fields set
to null. An entry matches a template if (a) the entry has the same type as or is a subtype of the
template and (b) if for every specified non- null field in the template, their fields match exactly.
The null fields act as wildcards and match any value. The following code segment shows how to
create a template and perform a read() on the space:
Transactions
The JavaSpaces API uses the package net.jini.core.transaction to provide basic atomic
transactions that group multiple operations across multiple JavaSpaces services into a bundle that acts
as a single atomic operation. Either all modifications within the transactions will be applied or none
will, regardless of whether the transaction spans one or more operations or one or more JavaSpaces
services.
A read(), write(), or take() operation that has a null transaction acts as if it were in a committed
transaction that contained that operation. As an example, a take() with a null transaction parameter
performs as if a transaction was created, the take() was performed under that transaction, and then the
transaction was committed.
The Jini Technology Starter Kit comes with the package com.sun.jini.outrigger, which provides an
implementation of a JavaSpaces technology-enabled service. You can run it two ways:
As a transient space that loses its state between executions:
Use com.sun.jini.outrigger.TransientOutriggerImpl.
As a persistent space that maintains state between executions:
Use com.sun.jini.outrigger.PersistentOutriggerImpl.
TransientOutriggerImplPersistentOutriggerImpl
To compile and run the sample application in this article, do the following:
1. Compile the code in Code Sample 1 ( MessageEntry.java) using javac as follows:
prompt> javac -classpath <pathToJiniInstallation\lib\jini-ext.jar> MessageEntry.java
Note that you need to include the JAR file jini-ext.jar in your classpath. This JAR file comes with the
starter kit and is in the lib directory of your installation.
2. Compile the code in Code Sample 2 ( SpaceClient.java). Note that this code makes use of a utility
class called Lookup to locate or discover a JavaSpace space. Therefore, before you
compile SpaceClient.java, you should download Lookup.java and then compile both classes
using javac as shown in step 2. Note that you should include the directory that
contains MessageEntry.class in your classpath when compiling SpaceClient.java.
3. Run Launch-All, which is in the installverify directory of your Jini installation directory. This will
start a service browser (as shown in Figure 2) and six contributed Jini network technology services,
one of which is the JavaSpace service.
UNIT III
DATABASE
JDBC - Introduction
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated
with database usage.
Making a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the database.
Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable
access to an underlying database. Java can be used to write different types of executables, such as −
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and take advantage
of the stored data.
• Database Vendor: Provides a set of APIs for accessing data managed by database
server. Eg. Oracle, Sybase etc
• Client applications: written in C/C++ can use these vendor specific APIs
• JDBC Driver: A Middleware layer that translates the JDBC calls to vendor Specific
APIs
• Packages: java.sql --- J2SE
javax.sql---J2EE
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in general,
JDBC Architecture consists of two layers –
Driver − This interface handles the communications with the database server. You will interact directly with
Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type.
It also abstracts the details associated with working with Driver objects.
Connection − This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection object only.
Statement − You use objects created from this interface to submit the SQL statements to the database.
Some derived interfaces accept parameters in addition to executing stored procedures.
ResultSet − These objects hold data retrieved from a database after you execute an SQL query using
Statement objects. It acts as an iterator to allow you to move through its data.
SQLException − This class handles any errors that occur in a database application.
JDBC Driver Types
• JDBC Driver is a software component that enables java application to interact with
the database.
• There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
Type 1-JDBC-ODBC bridge driver
• The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls. This is now discouraged because of thin driver.
• In Java 8 and later versions, the JDBC-ODBC Bridge has been removed.
TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 106
ADVANCED JAVA PROGRAMMING I- MSC(CS)
• Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends
that you use JDBC drivers provided by the vendor of your database instead of the
JDBC-ODBC Bridge.
JDBC-ODBC architecture
• The Native API driver uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API. It is not written
entirely in java.
Native API Driver Architecture
Advantage:
• Better performance than all other drivers.
• No software is required at client side or server side.
Disadvantage:
• Drivers depend on the Database.
Java.sql package
• Class groups based on functionalities
• Connection Management
• Database Access
• Data Types
• Database MetaData
• Exceptions and Warnings
• Example:
• Class.forName("com.mysql.jdbc.Driver");
DriverManager class
• can manage multiple drivers
• Each driver has to register with DriverManager class
• In JDBC we load database driver using java.lang.Class loader object
• At runtime classloader locates and loads the driver from the class path using bootstrap
class loader
Step 2: Create the connection object
• The getConnection() method of DriverManager class is used to establish connection
with the database.
• Syntax:
1) public static Connection getConnection(String url)throws SQLException
TRINITY COLLEGE FOR WOMEN, NAMAKKAL Page 112
ADVANCED JAVA PROGRAMMING I- MSC(CS)
• Execute():
– Syntax:public boolean execute(String sql) throws SQLException
• ExecuteQuery():
– Syntax:public ResultSet executeQuery(String sql) throws SQLException
Methods to retrieve data
• getArray()
• getBlob()
• getBoolean()
• getInt()
• getDate()
• getByte()
• getLong()
• getString()
• getDouble()
getObject()
getTime
Step 5 :Close the connection object
• By closing connection object statement and ResultSet will be closed automatically.
• The close() method of Connection interface is used to close the connection.
• Syntax: public void close()throws SQLException
• Example: con.close()
JDBC Connectivity using Type 1 – JDBC ODBC
DriverCreate a database
JDBC Connectivity using Type 1 – JDBC ODBC DriverCreate new data source
Prepared statements
• Creating parameterized statement such that data for parameters can be substituted
dynamically
• Creating statement involving data values that can always be represented as character
strings
Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException{}
Create a table
create table emp(id number(10),name varchar2(50));
Insert the records using PreparedStatement
Multimedia Databases
The multimedia databases are used to store multimedia data such as images,
animation, audio, video along with text. This data is stored in the form of multiple file types
like .txt(text), .jpg(images), .swf(videos), .mp3(audio) etc.
keyword data can be date and time of the image, description of the image etc.
Multimedia databases are used in industries that require a large set of documentation and
records, such as the insurance claim industry.
Education
Multimedia data provides an interactive way to represent data. It makes multimedia databases
effective knowledge dissemination tools. Examples are multimedia datasets in digital
libraries and computer-aided learning software.
Multimedia databases act as data providers for entertainment applications like video-on-
demand apps and news-on-demand apps. They can provide multimedia data for
advertisements and digital marketing processes.
Real-time Monitoring
When combined with various software tools, multimedia databases can be used to monitor
and manage multimedia data in real-time. For example, a geographic information system
(GIS) makes use of multimedia databases to analyze and visualize geographical multimedia
data in real-time.
Database design plays a key role in the operation of your website and provides you with
information regarding transactions, data integrity, and security issues. In this article, you will learn the role
of databases in web application development.
Database
Data is the foundation of a web application. It is used to store user information, session data, and
other application data. The database is the central repository for all of this data. Web applications use a
variety of databases to store data such as flat files, relational databases, object-relational databases, and
NoSQL databases.
A database is a collection of data and information that is stored in an organized manner for easy
retrieval. The primary purpose of a database is to store, retrieve, and update information. A database can
be used to store data related to any aspect of business operations.
Databases can be very large, containing millions of records, or very small, containing just a few
records or even a single record. They may be stored on hard disks or other media, or they may exist only
in memory. In the early days of computing, databases were stored on tape drives or punch cards. Today
they're stored on hard drives, flash memory cards, and other media.
Databases are designed to ensure that the data they contain is organized and easily retrievable. A
database management system (DBMS) is the software used to create and maintain a database.
The database is used to store all the information that the user needs to store. For example, if you
are developing a shopping cart website then it will contain product details, customer details, order details,
etc. In this case, you need to store this information in a database so that we can use them later on.
Security
A web application database provides security features such as encryption and password protection. If a
user’s password becomes lost or compromised, it will not be possible for someone else to access the
information stored in the database.
Accessibility
Users can access their data from any internet-enabled device, which includes smartphones and tablets as
well as laptops and desktops. This means that users do not have to worry about losing their valuable data
because it is stored on another device.
Reliability and scalability
Web applications are usually accessed by many users simultaneously, unlike traditional desktop
applications that are accessed by one person at a time, so web apps need to be able to handle more
requests simultaneously than their desktop counterparts. Web application databases use distributed
architecture (multiple servers) to scale up quickly when demand increases, so they can handle large
numbers of simultaneous requests without slowing down or crashing.
Ease of maintenance for IT staff
Because web application databases use distributed architecture, problems can be isolated and fixed
quickly, which reduces downtime for the end user and reduces costs for IT staffs responsible for
maintaining the system. Also, with database automation tools we can make database tasks easier and
safer.
Relational
A database is a large collection of structured data, which can be accessed to find specific information.
Relational databases are famous for their structure and have been used by programmers for years.
A relational database is data storage that maintains a relationship between two or more entities. It is used
whenever you want to store information in a way that it can be retrieved by your application. In general,
we can say that a relational database is a data storage structure where each tuple on its own occupies one
record and consists of values of attributes.
Advantages
The main advantages of relational databases include:
Data integrity. A correctly implemented relational database ensures that all data entered remains
accurate, complete, and consistent over time. This helps ensure that all users have access to the most up-
to-date data possible at any given moment without having to worry about whether it will still be there
when they need it later on down the line.
They're easy to use. Relational databases are designed to be easy to understand and use. The
relationships between all the tables and data elements are clearly defined, making it easy to understand
how they work together.
Scalability. Relational databases scale easily from small applications up to large enterprise systems. You
can add more disk space and memory resources when needed without taking down your application or
disrupting end users. This makes relational databases ideal for large-scale applications, such as data
warehouses or customer relationship management systems.
High availability and disaster recovery capabilities. Relational databases provide automated backup
capabilities that allow you to recover quickly from hardware failures or other disasters without requiring
human intervention or manual restoration procedures.
Disadvantages
Not suitable for real-time data analysis. Relational databases can't be used for real-time data analysis
because they don't store the data in such a way that it can be queried quickly. This means that if you want
to analyze your data in real-time, you need a technology other than Relational databases.
The inability to store documents or graphs in their native format. This means that you need to
transform your data into tabular format before storing it. This can be very inconvenient if you want to
query your data in a different way
Not very good at storing sparse data (i.e., large empty spaces). For example, if you want to store all
email addresses from your customers and only non-empty addresses are stored, then this will take up a lot
of space compared to storing every single email address even if it's empty
Relational databases have a fixed schema. You cannot change the structure of the database during its
lifetime, this is called fixed schema. For example, if you want to add a new column for an existing table
in a relational database, you will have to re-write all queries .
Non-Relational
Non-relational databases (sometimes called object-oriented databases) are very different from
Relational databases. The term non-relational (or NoSQL) database describes any kind of database in
which there is no strict distinction between relations, rows, and columns. The term non-relational comes
from the fact that the objects stored within the databases are not based on relationships (also called joins),
but rather are based on an implicit, often unstructured structure.
Non-relational databases (or NoSQL) is a class of database management systems that were
designed to be more flexible than a relational database. The main reason is that they are disconnected
from the original data structure and don't use the traditional relationships between tables in database
design.
Advantages
Speed. The most obvious advantage of non-relational databases is that they can be extremely fast. Non-
relational databases can do things that would take too long in a relational database, such as searching
every record or even all records on disk, without having to query the database first.
Simplicity. Non-relational databases are generally easier to understand and use than relational ones,
making them ideal for smaller projects where there aren't many users or developers working with the data
at any given time. NoSQL databases might not be ideal for complex projects.
Scalability. Because they are not constrained by the schema, non-relational databases can scale more
easily than relational databases. You can add more hardware and therefore more nodes, which increases
the overall performance of the system. This is particularly useful when you need to perform complex
computations on large amounts of data.
Data can be stored in any format necessary for the application. For example, if your application
requires XML documents, then you can store them in an XML column instead of forcing them into a
table schema.
The processing time for queries is faster in some cases because there is no need to traverse through
multiple tables or join across multiple databases like with relational databases.
Disadvantages
No standardization. Each vendor has its own APIs and features, making it challenging to implement
cross-platform applications.
Some non-relational databases (especially those used for big data) have problems dealing with
large amounts of data at once because they don't have good query optimization algorithms built into
them as relational databases do.
A non-relational database doesn't have a fixed structure like a relational database, so you'll need to
write code that can handle the unexpected — for example, you might have to write code that handles
different field lengths depending on what kind of data is being stored.
The biggest disadvantage of non-relational databases is that they don't support ACID
transactions. In other words, to update data in a non-relational database, you need to perform multiple
queries and then combine them together.
Graph-based database management systems provide a way to model relationships between objects as
nodes connected by edges (lines). Graphs can be used to represent complex relationships among people,
places, and things in your world such as connections between people on social media sites like Facebook.
Advantages
Easy to model real-world situations: The structure of a graph database allows you to model any type of
relationship that exists in your real-world business problem — not just the ones that fit into a traditional
table
Efficient for traversing linked data: Graphs are particularly useful for traversing linked data because
they allow you to follow links between objects as easily as searching within an object. You can easily
find all records related to a particular item or set of items by following related links between those
records.
Graph databases also allow you to query data on both nodes and edges at the same time, so they're
great for analyzing relationships between entities no matter how deep those relationships may go!
Disadvantages
Performance. Graphs are not known for their fast performance. They do not perform well when there
are multiple levels of nesting or loops in the graph structure. This means that they can be slow when
dealing with large amounts of data or graphs with high-degree vertices
Scalability. Graphs are not scalable in an easy way like tables are in relational databases. Because graphs
are implemented as networks and each vertex can have multiple edges linking it to other vertices, adding
more vertices and edges to a graph makes it more difficult to manage efficiently.
They are relatively new. Many organizations have already invested heavily in relational or document-
oriented databases and may not want to throw away all that investment.
MySQL (Relational)
MySQL is a relational database management system (RDBMS) based on SQL. It is a popular
database server, and a multi-user, multi-threaded SQL database. MySQL is developed by Oracle
Corporation. MySQL database is often used for data storage, especially in web applications, and it is also
widely used for creating and maintaining relational database tables.
MySQL is owned by Oracle Corporation and was developed by a Swedish company called
MySQL AB, which was bought by Sun Microsystems in 2008. As of 2009, the project is managed by
Oracle Corporation.
PostgreSQL (Relational)
An object-relational database management system that supports SQL-based queries, similar to
those used by other RDBMS systems such as MySQL or Oracle Database. PostgreSQL is developed and
maintained by PostgreSQL Global Development Group, which is made up of several companies and
individuals who have contributed code to the project over time.The software is distributed under an ISC
license, which allows anyone to use it for any purpose without paying royalties or fees.
MongoDB (Non-Relational)
MongoDB is an open-source document-oriented database developed by MongoDB Inc.
(formerly 10gen). The first version was released in 2009. It is written in C++ and provides a document-
oriented data model that can be queried using a JSON-like query language.
A document can be thought of as a virtual "sheet" or "document" in a spreadsheet application
such as Microsoft Excel or Google Sheets. A document contains multiple fields that may be similar to
cells in an Excel spreadsheet or cells in an Access database table. These fields can have different types:
text, numbers, dates, and so on.
.
Cassandra (Non-Relational)
Cassandra is an open-source database management system that runs on many servers, making it
well-suited for handling large amounts of data. It offers fast performance and can scale up to a petabyte of
data across multiple servers, making it useful for applications with high write-throughput requirements.
The technology was developed at Facebook and released as an Apache Incubator project in
2009. It graduated from incubation in June 2010 and became an Apache Top-level Project (TLP) in
January 2012.
It aims to provide high availability by making it easy to deploy multiple copies of the data across
many hosts while tolerating failures at any one host. Cassandra is a key-value store, but it has flexible data
models, so you can use it to store virtually any kind of data. You can also use Cassandra for full-text
search, or even for storing graph data
MariaDB (Relational)
MariaDB is a fork of the MySQL relational database management system intended to remain
free under the GNU GPL. MariaDB was forked in 2009 by some of the original developers of MySQL
when Oracle announced that it would no longer fully support the community-developed version of
MySQL in favor of a paid enterprise product.
The original developers of MySQL created MariaDB to provide a better development environment and
more robust performance. MariaDB strives to be compatible with MySQL and includes most of its
storage engines.
MSSQL (Relational)
MSSQL databases are the core of Microsoft SQL Server. It is a relational database management
system (RDBMS), a special type of database software that is used to create, store and manipulate data in
an organized manner.
MSSQL can be used to build enterprise-level business solutions and applications. Regardless of the
platform or device your users are using, you can use MSSQL to create a centralized data store with a
single version of the truth.
There are a few ways to do it. The simplest way is to use a direct query to get the value you need.
This is not recommended because it will severely limit your flexibility .
Another approach is to use a stored procedure that returns the value. This can be done in SQL
Server, MySQL server, or other RDBMSs. If your web application needs more than one value from the
database, You would need to issue multiple queries or use another method.
The most common way to connect a database to an application is by using an Object Relational
Mapper (ORM). This technology connects your program to the database and allows you to use it like a
normal object. Eg:Active Record (AR).
UNIT IV
SERVLETS
CommonGateway Interface(CGI):
The Common Gateway Interface (CGI) provides the middleware between WWW
servers and external databases and information sources.
The World Wide Web Consortium (W3C) defined the Common Gateway Interface (CGI) and
also defined how a program interacts with a HyperText Transfer Protocol (HTTP) server. The
Web server typically passes the form information to a small application program that
processes the data and may send back a confirmation message.
This process or convention for passing data back and forth between the server and the
application is called the common gateway interface (CGI). The following image describes
how a web server acts as an intermediate between the CGI program and the client browser.
The following table explains the difference between the servlet and CGI:
Basis Servlet CGI
Since codes are written in Since codes are written in any language,
Object- Java, it is object oriented and all the languages are not object-oriented
Oriented the user will get the benefits thread-based. So, the user will not get
of OOPs the benefits of OOPs
It remains in the memory until It is removed from the memory after the
Persistence
it is not explicitly destroyed. completion of the process-basedrequest.
Server It can use any of the web- It can use the web-server that supports
Independent server. it.
It can read and set HTTP It can neither read nor set HTTP
HTTP server
servers. servers.
Compiling a Servlet
Let us create a file with name HelloWorld.java with the code shown above. Place this
file at C:\ServletDevel (in Windows) or at /usr/ServletDevel (in Unix). This path location
must be added to CLASSPATH before proceeding further.
Assuming your environment is setup properly, go in ServletDevel directory and
compile HelloWorld.java as follows –
$ javac HelloWorld.java
This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK). For this command to work properly,
you have to include the location of the Java SDK that you are using in the PATH
environment variable.
If everything goes fine, above compilation would produce HelloWorld.class file in the same
directory.
Servlet Deployment
A servlet application is located at the path <Tomcat-
installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes.
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet
class must be located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries
in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.
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
GET Method
The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the ? (question mark) symbol as
follows −
http://www.test.com/hello?key1 = value1&key2 = value2
The GET method is the default method to pass information from browser to web
server and it produces a long string that appears in your browser's Location:box. Never use
the GET method if you have password or other sensitive information to pass to the server.
The GET method has size limitation: only 1024 characters can be used in a request string.
This information is passed using QUERY_STRING header and will be accessible
through QUERY_STRING environment variable and Servlet handles this type of requests
using doGet() method.
POST Method
A generally more reliable method of passing information to a backend program is the
POST method. This packages the information in exactly the same way as GET method, but
instead of sending it as a text string after a ? (question mark) in the URL it sends it as a
separate message. This message comes to the backend program in the form of the standard
input which you can parse and use for your processing. Servlet handles this type of requests
using doPost() method.
getParameterValues() − Call this method if the parameter appears more than once
and returns multiple values, for example checkbox.
getParameterNames() − Call this method if you want a complete list of all
parameters in the current request.
GET Method Example using URL
Here is a simple URL which will pass two values to HelloForm program using GET
method.
http://localhost:8080/HelloForm?first_name = ZARA&last_name = ALI
Given below is the HelloForm.java servlet program to handle input given by web browser.
We are going to use getParameter() method which makes it very easy to access passed
information
Assuming your environment is set up properly, compile HelloForm.java as follows −
$ javacHelloForm.java
If everything goes fine, above compilation would produce HelloForm.class file. Next
you would have to copy this class file in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries
in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name
=ALI in your browser's Location:box and make sure you already started tomcat server, before
firing above command in the browser. This would generate following result
Using GET Method to Read Form Data
First Name: ZARA
Last Name: ALI
Try to enter First Name and Last Name and then click submit button
to see the result on your local machine where tomcat is running. Based on the input provided,
it will generate similar result as mentioned in the above example.
POST Method Example Using Form
Let us do little modification in the above servlet, so that it can handle GET as well as POST
methods. Below is HelloForm.java servlet program to handle input given by web browser
using GET or POST methods.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
PrintWriterout=response.getWriter();
String title ="Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 "+
"transitional//en\">\n";
out.println(docType +
"<html>\n"+
"<head><title>"+ title +"</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n"+
"<h1 align = \"center\">"+ title +"</h1>\n"+
"<ul>\n"+
" <li><b>First Name</b>: "
+request.getParameter("first_name")+"\n"+
" <li><b>Last Name</b>: "
+request.getParameter("last_name")+"\n"+
"</ul>\n"+
"</body>"
"</html>"
);
}
doGet(request, response);
}
}
Now compile and deploy the above Servlet and test it using Hello.htm with the POST method
as follows −
<html>
<body>
<formaction="HelloForm"method="POST">
First Name: <inputtype="text"name="first_name">
<br/>
Last Name: <inputtype="text"name="last_name"/>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>
Here is the actual output of the above form, Try to enter First and Last Name and then click
submit button to see the result on your local machine where tomcat is running.
Based on the input provided, it would generate similar result as mentioned in the above
examples.
Accept
This header specifies the MIME types that the browser or other clients can
1
handle. Values of image/png or image/jpeg are the two most common
possibilities.
Accept-Charset
2 This header specifies the character sets the browser can use to display the
information. For example ISO-8859-1.
3 Accept-Encoding
This header specifies the types of encodings that the browser knows how to
handle. Values of gzip or compress are the two most common possibilities.
Accept-Language
4 This header specifies the client's preferred languages in case the servlet can
produce results in more than one language. For example en, en-us, ru, etc
Authorization
5 This header is used by clients to identify themselves when accessing
password-protected Web pages.
Connection
This header indicates whether the client can handle persistent HTTP
6 connections. Persistent connections permit the client or other browser to
retrieve multiple files with a single request. A value of Keep-Alive means
that persistent connections should be used.
Content-Length
7 This header is applicable only to POST requests and gives the size of the
POST data in bytes.
Cookie
8 This header returns cookies to servers that previously sent them to the
browser.
Host
9
This header specifies the host and port as given in the original URL.
Cookie[] getCookies()
1 Returns an array containing all of the Cookie objects the client sent with this
request.
Enumeration getAttributeNames()
2 Returns an Enumeration containing the names of the attributes available to
this request.
Enumeration getHeaderNames()
3
Returns an enumeration of all the header names this request contains.
Enumeration getParameterNames()
4 Returns an Enumeration of String objects containing the names of the
parameters contained in this request
HttpSession getSession()
5
Returns the current session associated with this request, or if the request does
PrintWriterout=response.getWriter();
String title ="HTTP Header Request Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 "+"transitional//en\">\n";
out.println(docType +
"<html>\n"+
"<head><title>"+ title +"</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n"+
"<h1 align = \"center\">"+ title +"</h1>\n"+
"<table width = \"100%\" border = \"1\" align = \"center\">\n"+
"<tr bgcolor = \"#949494\">\n"+
"<th>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n"
);
while(headerNames.hasMoreElements()){
String paramName =(String)headerNames.nextElement();
out.print("<tr><td>"+ paramName +"</td>\n");
doGet(request, response);
}
}
Now calling the above servlet would generate the following result −
HTTP Header Request Example
accept */*
accept-language en-us
host localhost:8080
connection Keep-Alive
cache-control no-cache
...
</body>
</html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in
the example), and a very short message corresponding to the status code (OK in the
example).
Following is a summary of the most useful HTTP 1.1 response headers which go back to the
browser from web server side and you would use them very frequently in web programming
−
Sr.No. Header & Description
Allow
1 This header specifies the request methods (GET, POST, etc.) that the server
supports.
Cache-Control
This header specifies the circumstances in which the response document can
safely be cached. It can have values public, private or no-cache etc. Public
2
means document is cacheable, Private means document is for a single user
and can only be stored in private (non-shared) caches and nocache means
document should never be cached.
Connection
This header instructs the browser whether to use persistent in HTTP
3
connections or not. A value of close instructs the browser not to use persistent
HTTP connections and keepalive means using persistent connections.
Content-Disposition
4 This header lets you request that the browser ask the user to save the response
to disk in a file of the given name.
Content-Encoding
5 This header specifies the way in which the page was encoded during
transmission.
Content-Language
6 This header signifies the language in which the document is written. For
example en, en-us, ru, etc
Content-Length
This header indicates the number of bytes in the response. This information is
7
needed only if the browser is using a persistent (keep-alive) HTTP
connection.
Content-Type
8 This header gives the MIME (Multipurpose Internet Mail Extension) type of
the response document.
Expires
9
This header specifies the time at which the content should be considered out-
Last-Modified
This header indicates when the document was last changed. The client can
10
then cache the document and supply a date by an If-Modified-Since request
header in later requests.
Location
This header should be included with all responses that have a status code in
11
the 300s. This notifies the browser of the document address. The browser
automatically reconnects to this location and retrieves the new document.
Refresh
This header specifies how soon the browser should ask for an updated page.
12
You can specify time in number of seconds after which a page would be
refreshed.
Retry-After
13 This header can be used in conjunction with a 503 (Service Unavailable)
response to tell the client how soon it can repeat its request.
Set-Cookie
14 This header specifies a cookie associated with the page.
boolean isCommitted()
4
Returns a Boolean indicating if the response has been committed.
void flushBuffer()
9
Forces any content in the buffer to be written to the client.
void reset()
10
Clears any data that exists in the buffer as well as the status code and headers.
void resetBuffer()
11 Clears the content of the underlying buffer in the response without clearing
headers or status code.
that if request is sent by the user, cookie is added with request by default. Thus, we recognize
the user as the old user.
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It
is removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot
of useful methods for cookies.
Constructor Description
Cookie(String name, String value) constructs a cookie with a specified name and value.
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.
For adding cookie or getting the value from the cookie, we need some methods provided by other
interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add
cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the
cookies from the browser.
create Cookies
Let's see the simple code to create cookie.
1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
2. response.addCookie(ck);//adding cookie in the response
Delete Cookies
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
1. Cookie ck=new Cookie("user","");//deleting value of cookie
2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response
Getting Cookies
Let's see the simple code to get all the cookies.
1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
4. }
Advantages of JSP
Following table lists out the other advantages of using JSP over other technologies −
vs. Active Server Pages (ASP)
The advantages of JSP are twofold. First, the dynamic part is written in Java, not
Visual Basic or other MS specific language, so it is more powerful and easier to use. Second,
it is portable to other operating systems and non-Microsoft Web servers.
vs. Pure Servlets
It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
vs. Server-Side Includes (SSI)
SSI is really only intended for simple inclusions, not for "real" programs that use form
data, make database connections, and the like.
vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with
the web server to perform complex tasks like database access and image processing etc.
vs. Static HTML
Regular HTML, of course, cannot contain dynamic information.
JSP - Environment Setup
A development environment is where you would develop your JSP programs, test
them and finally run them.
Tomcat can be started by executing the following commands on the Windows machine –
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-5.5.29\bin\startup.bat
Tomcat can be started by executing the following commands on the Unix (Solaris, Linux,
etc.) machine –
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apache-tomcat-5.5.29/bin/startup.sh
After a successful startup, the default web-applications included with Tomcat will be
available by visiting http://localhost:8080/.
Further information about configuring and running Tomcat can be found in the
documentation included here, as well as on the Tomcat web site − https://tomcat.apache.org/.
Tomcat can be stopped by executing the following commands on the Windows machine –
%CATALINA_HOME%\bin\shutdown
or
C:\apache-tomcat-5.5.29\bin\shutdown
Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.)
machine –
$CATALINA_HOME/bin/shutdown.sh
or
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify
the servlet classes to the compiler.
If you are running Windows, you need to put the following lines in
your C:\autoexec.bat file.
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are
the scripting elements first.
JSP Scripting elements
The scripting elements provides the ability to insert java code inside the jsp. There are three
types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag
JSP scriptlet tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
File: index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>
Scriptlets
JavaServer Pages often present dynamically generated content as part of an XHTML
document sent to the client in response to a request. In some cases, the content is static, but is
output only if certain conditions are met during a request (such as providing values in a form
that submits a request). JSP programmers can insert Java code and logic in a JSP using
scripting.
Scripting Components
JSP scripting components include scriptlets, comments, expressions, declarations and
escape sequences. This section describes each of these scripting components. Many of these
scripting components are demonstrated in Fig. 10.4 .
Scriptlets are blocks of code delimited by <% and %>. They contain Java statements
that the container places in method _jspService at translation time.
JSPs support three comment styles: JSP comments, XHTML comments and
comments from the scripting language. JSP comments are delimited by <%-- and --%>. Such
comments can be placed throughout a JSP, but not inside scriptlets. XHTML comments are
delimited with <!-- and -->. These comments can be placed throughout a JSP, but not inside
scriptlets.
Scripting language comments are currently Java comments, because Java is the only
JSP scripting language at the present time. Scriptlets can use Java’s single-line comments
(delimited by/ and /) and multiline comments (delimited by /* and */).JSP comments and
scripting-language comments are ignored and do not appear in the response to a client.
When clients view the source code of a JSP response, they will see only the XHTML
comments in the source code. The different comment styles are useful for separating
comments that the user should be able to see from comments that document logic
processed on the server.
A JSP expression, delimited by <%= and %>, contains a Java expression that is
evaluated when a client requests the JSP containing the expression. The container converts
the result of a JSP expression to a String object, then outputs the String as part of the
response to the client.
Declarations (delimited by <%! and %>) enable a JSP programmer to define variables
and methods. Variables become instance variables of the servlet class that represents the
translated JSP. Similarly, methods become members of the class that represents the translated
JSP. Declarations of variables and methods in a JSP use Java syntax. Thus, a variable
declaration must end in a semicolon, as in
Special characters or character sequences that the JSP container normally uses to
delimit JSP code can be included in a JSP as literal characters in scripting elements, fixed
template data and attribute values using escape sequences. Figure 10.3 shows the literal
character or characters and the corresponding escape sequences and discusses where to use
the escape sequences.
Scripting Example
The JSP of Fig. 10.4 demonstrates basic scripting capabilities by responding to get
requests. The JSP enables the user to input a first name, then outputs that name as part of the
response. Using scripting, the JSP determines whether a firstName parameter was passed to
the JSP as part of the request; if not, the JSP returns an XHTML document containing a form
through which the user can input a first name. Otherwise, the JSP obtains the firstName value
and uses it as part of an XHTML document that welcomes the user to JavaServer Pages.
Directives
Directives are messages to the JSP container that enable the programmer to specify
page settings (such as the error page), to include content from other resources and to specify
custom- tag libraries for use in a JSP. Directives (delimited by <%@ and %>) are processed
at translation time.
Thus, directives do not produce any immediate output, because they are processed
before the JSP accepts any requests. Figure 10.26 summarizes the three directive types. These
directives are discussed in the next several subsections.
Page Directive
The page directive specifies global settings for the JSP in the JSP container. There can
be many page directives, provided that there is only one occurrence of each attribute. The
only exception to this rule is the import attribute, which can be used repeatedly to import Java
packages used in the JSP. Figure 10.27 summarizes the attributes of the page directive.
Directive Description
page Defines page settings for the JSP container to process.
include Causes the JSP container to perform a translation-time insertion of
another resource’s content. As the JSP is translated into a servlet and
compiled, the referenced file replaces the include directive and is
translated as if it were originally part of the JSP.
taglib Allows programmers to include their own new tags in the form of tag
libraries. These libraries can be used to encapsulate functionality and
simplify the coding of a JSP.
include Directive
The include directive includes the content of another resource once, at JSP translation
time. The include directive has only one attribute—file—that specifies the URL of the page
to include. The difference between directive include and action <jsp:include> is noticeable
only if the included content changes.
For example, if the definition of an XHTML document changes after it is included
with directive include, future invocations of the JSP will show the original content of the
XHTML document, not the new content. In contrast, action <jsp:include> is processed in
each request to the JSP.
Therefore, changes to included content would be apparent in the next request to the
JSP that uses action <jsp:include>. JavaServer Page includeDirective.jsp (Fig. 10.28)
reimplements JavaServer Page include.jsp (Fig. 10.10) using include directives. To test
includeDirective. jsp in Tomcat, copy includeDirective.jsp into the jsp directory created in
Section 10.3. Open your Web browser and enter the following URL to test include-
Directive.jsp:
http://localhost:8080/advjhtp1/jsp/includeDirective.jsp
The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
So it doesn't get memory at each request.
Syntax of JSP declaration tag
The jsp scriptlet tag can only declare variables The jsp declaration tag can declare variables as
not methods. well as methods.
The declaration of scriptlet tag is placed inside The declaration of jsp declaration tag is placed
the _jspService() method. outside the _jspService() method.
index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
index.jsp
1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
</html>
UNIT V
ADVANCED TECHNIQUES
In Java, JAR stands for Java ARchive, whose format is based on the zip format.
The JAR files format is mainly used to aggregate a collection of files into a single one.
It is a single cross-platform archive format that handles images, audio, and class files.
With the existing applet code, it is backward-compatible. In Java, Jar files are
completely written in the Java programming language.
We can either download the JAR files from the browser or can write our own JAR files
using Eclipse IDE.
The steps to bundle the source code, i.e., .java files, into a JAR are given below.
In the first step, we will open Eclipse IDE and select the Export option from the File When we
select the Export option, the Jar File wizard opens with the following screen:
From the open wizard, we select the Java JAR file and click on the Next. The Next button opens
JAR Export for JAR File Specification.
1. Now, from the JAR File Specification page, we select the resources needed for exporting in
the Select the resources to export.
After that, we enter the JAR file name and folder. By default, the Export
generated class files and resources checkbox is checked. We also check the Export
If there are other Java files or resources which we want to include and which are
available in the open project, browse to their location and ensure the file or resource is
checked in the window on the right.
2. On the same page, there are three more checkboxes, i.e., Compress the content of the JAR
file, Add directory entries, and Overwrite existing files without warning. By default,
the Compress content of the JAR file checkbox is checked.
3. Now, we have two options for proceeding next, i.e., Finish and Next. If we click on the Next,
it willimmediately create a JAR file to that location which we defined in the Select the export
destination.
4. If we click on the Next button, it will open the Jar Packaging Option wizard for creating a
JAR description, setting the advance option, or changing the default manifest.
5. For now, we skip the Next and click on the Finish button.
6. Now, we go to the specified location, which we defined in the Select the export destination,
to ensure that the JAR file is created successfully or not.
7.
Internationalization
Internalization or I18N refers to the capability of an Application to be able to serve users in
multiple and different languages. Java has in-built support for Internationalization. Java also provides
formatting of numbers, currencies and adjustment of date and time accordingly.
Java Internationalization helps to make a java application handle different languages, number
formats, currencies, region specific time formatting.
Localization
Localization or L10N is the adaptability of an application that is how an application adapts
itself with a specific language, number formats, date and time settings etc.
A java application should be internationalized in order to be able to localize itself.
Culturally Dependent Information
Following information items often varies with different time zones or cultures.
Messages
Date
Time
Number
Currency
Measurements
Phone Numbers
Postal Addresses
GUI labels
Internationalization Classes
Java has a set of built-in classes which help in internationalization of an application. These
classes are following:
Locale
1
Represents a language along with country/region.
ResourceBundle
2
Contains localized text or objects.
NumberFormat
3
Use to format numbers/currencies as per the locale.
DecimalFormat
4
Use to format numbers as per customized format and as per locale.
DateFormat
5
Use to format dates as per locale.
SimpleDateFormat
6
Use to format dates as per customized format and as per locale.
Java Swing
o Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create
window-based applications.
o It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in
java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
There are many differences between java awt and swing that are given below.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and
feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
The methods of Component class are widely used in java swing that are given below.
Method Description
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.
Let's see a simple swing example where we are creating one button and adding it on the
JFrame object inside the main() method.
File: FirstSwingExample.java
1. import javax.swing.*;
2. public class FirstSwingExample
Components:
In general, Swing components are derived from the JComponent class. JComponent provides
the functionality that is common to all components. The following figure shows hierarchy of classes
of javax.swing
Containers:
Glass pane: This is the first pane and is very close to the monitor’s screen. Any
components to be displayed in the foreground are attached to this glass pane.
Root Pane: This pane is below the glass pane. Any components to be displayed in the
background are displayed in this frame.
Layered pane: This pane is below the root pane. When we want to take several
components as a group, we attach them in the layered pane.
Conent pane: This is bottom most of all, Individual components are attached to this
pane. To reach this pane, we can call getContentPane() method of JFrame class
which returns Container class object.
JFrame:
Frame represents a window with a title bar and borders. Frame becomes the basis for
creating the GUIs for an application because all the components go into the frame.
To create a frame, we have to create an object to JFrame class in swing as
JFrame jf=new JFrame(); // create a frame without title
JFrame jf=new JFrame(“title”); // create a frame with title
To close the frame, use setDefaultCloseOperation() method of JFrame class
setDefaultCloseOperation(constant)
where constant values are
Example:
import javax.swing.*;
class FrameDemo
{
public static void main(String arg[])
{
JFrame jf=new JFrame("PVPSIT");
jf.setSize(200,200);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE );
class FrameDemo
{
public static void main(String arg[])
{
JFrame jf=new JFrame("PVPSIT");
jf.setSize(200,200);
jf.setVisible(true);
Container c=jf.getContentPane();
c.setBackground(Color.green);
}
}
JApplet:
Fundamental to Swing is the JApplet class, which extends Applet. Applets that use
Swing must be subclasses of JApplet. JApplet is rich with functionality that is not found in
Applet. For example, JApplet supports various “panes,” such as the content pane, the glass
pane, and the root pane.
One difference between Applet and JApplet is, When adding a component to an
instance of JApplet, do not invoke the add( ) method of the applet. Instead, call add( ) for
the content pane of the JApplet object.
The content pane can be obtained via the method shown here:
Container getContentPane( )
The add( ) method of Container can be used to add a component to a content pane.
Its form is shown here:
void add(comp)
JComponent:
The class JComponent is the base class for all Swing components except top-level
containers. To use a component that inherits from JComponent, you must place the
component in a containment hierarchy whose root is a top-level SWING container.
Constructor: JComponent();
The following are the JComponent class's methods to manipulate the appearance of
the component.
JLabel:
JText Fields
The Swing text field is encapsulated by the JTextComponent class, which extends
JComponent. It provides functionality that is common to Swing text components. One of its
subclasses is JTextField, which allows you to edit one line of text. Some of its constructors
Here, s is the string to be presented, and cols is the number of columns in the text
field.
The following example illustrates how to create a text field. The applet begins by
getting its content pane, and then a flow layout is assigned as its layout manager. Next, a
JTextField object is created and is added to the content pane.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends JFrame implements ActionListener
{
JLabel jl, jl2;
JTextField jtf;
MyFrame()
{
setLayout(new FlowLayout());
jl=new JLabel("Enter your name");
jl2=new JLabel();
jtf=new JTextField("PVPSIT",15);
add(jl);
add(jtf);
add(jl2);
jtf.addActionListener(this);
}
The JButton class provides the functionality of a push button. JButton allows an
icon, a string, or both to be associated with the push button. Some of its constructors are
shown here:
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
Here, s and i are the string and icon used for the button.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends JFrame implements ActionListener
{
JButton jb,jb1,jb2;
JLabel jl;
MyFrame()
{
setLayout(new FlowLayout());
jl=new JLabel();
jb=new JButton("VRSEC");
ImageIcon ii=new ImageIcon("pvp.JPG");
jb1=new JButton("PVPSIT",ii);
jb.addActionListener(this);
jb1.addActionListener(this);
jb2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
jl.setText("You Pressed: "+ae.getActionCommand());
}
}
class FrameDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setTitle("Welcome to Swings");
f.setSize(500,500);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
JCheckBox:
The JCheckBox class, which provides the functionality of a check box, is a concrete
implementation of AbstractButton. Its immediate super class is JToggleButton, which
provides support for two-state buttons (true or false). Some of its constructors are shown here:
JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is true, the check
box is initially selected. Otherwise, it is not.
The state of the check box can be changed via the following method:
void setSelected(boolean state)
Here, state is true if the check box should be checked.
When a check box is selected or deselected, an item event is generated. This is
handled by itemStateChanged( ). Inside itemStateChanged( ), the getItem( ) method gets
the JCheckBox object that generated the event. The getText( ) method gets the text for that
check box and uses it to set the text inside the text field.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends JFrame implements ItemListener
{
JCheckBox jcb,jcb1,jcb2;
JLabel jl;
MyFrame()
{
setLayout(new FlowLayout());
jl=new JLabel();
jcb=new JCheckBox("VRSEC");
jcb1=new JCheckBox("PVPSIT");
jcb2=new JCheckBox("BEC" );
jcb.addItemListener(this);
jcb1.addItemListener(this);
jcb2.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox jc=(JCheckBox)ie.getItem();
jl.setText("You Selected :"+jc.getText() );
}
}
class FrameDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
f.setTitle("Welcome to Swings");
f.setSize(500,500);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
JRadioButton:
Radio buttons are supported by the JRadioButton class, which is a concrete
implementation of AbstractButton. Its immediate superclass is JToggleButton, which
provides support for two-state buttons. Some of its constructors are shown here:
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is true, the button
is initially selected. Otherwise, it is not.
Radio buttons must be configured into a group. Only one of the buttons in that group
can be selected at any time. For example, if a user presses a radio button that is in a group,
any previously selected button in that group is automatically deselected. The ButtonGroup
class is instantiated to create a button group. Its default constructor is invoked for this
purpose. Elements are then added to the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.
Radio button presses generate action events that are handled by actionPerformed( ).
The getActionCommand( ) method returns the text that is associated with a radio button and
uses it to set the text field.
TRINITY COLLEGE FOR WOMEN,NAMAKKAL Page 170
ADVANCED JAVA PROGRAMMING I-MSC-CS
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends JFrame implements ActionListener
{
JRadioButton jrb,jrb1,jrb2;
JLabel jl;
MyFrame()
{
setLayout(new FlowLayout());
jl=new JLabel();
jrb=new JRadioButton("VRSEC");
jrb1=new JRadioButton("PVPSIT");
jrb2=new JRadioButton("BEC" );
JComboBox :
Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class, which extends JComponent.
A combo box normally displays one entry. However, it can also display a drop-down
list that allows a user to select a different entry. You can also type your selection into the text
field.
Two of JComboBox’s constructors are shown here:
JComboBox( )
JComboBox(Vector v)
Here, v is a vector that initializes the combo box. Items are added to the list of choices
via the addItem( ) method, whose signature is shown here:
void addItem(Object obj)
Here, obj is the object to be added to the combo box.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyFrame extends JFrame implements ItemListener
{
JComboBox jcb;
MyFrame()
{
setLayout(new FlowLayout());
String cities[]={"Amaravati","Guntur","Vijayawada","Vizag","Kurnool"};
jcb=new JComboBox(cities);
jcb.addItem("Tirupati");
jcb.setEditable(true);
add(jcb);
jcb.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
JOptionPane.showMessageDialog(null,jcb.getSelectedItem());
}
}
public class JComboBoxDemo
{
public static void main(String[] args)
{
MyFrame jf = new MyFrame();
jf.setSize(500,500);
jf.setVisible(true);
jf.setTitle("Frame Example");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
JList:
• JList class is useful to create a list which displays a list of items and allows the user toselect
one or more items.
– Constructors
• JList()
• JList(Object arr[])
• JList(Vector v)
– Methods
• getSelectedIndex() – returns selected item index
• getSelectedValue() – to know which item is selected in the list
• getSelectedIndices() – returns selected items into an array
• getSelectedValues() – returns selected items names into an array
• JList generates ListSelectionEvent
– ListSelectionListener
• void valueChanged(ListSelectionEvent)
– Package is javax.swing.event.*;
Example:
import javax.swing.*; import
javax.swing.event.*; import
java.awt.*;
import java.awt.event.*;
j=new JList(arr);
add(jl);
add(j);
j.setToolTipText("I am PVPSIT");
j.addListSelectionListener(this);
}
public void valueChanged(ListSelectionEvent le)
Introduction
Core Java (J2SE) and Advanced Java are the two components that make up the Java
programming language (JEE).
The foundations of the Java programming language, including its data types, functions,
operators, loops, threads, and exception handling.
It is used in the process of developing apps for widespread usage. Whereas Intermediate
Java focuses on more advanced topics, such as database connection, networking, Servlet, web
services, and so on,
Advanced Java addresses more fundamental ideas.
Advanced java
Everything that is beyond Core Java is known as Advanced Java. This includes the application
programming interfaces (APIs) that are specified in Java Enterprise Edition, as well as Servlet programming,
Web Services, the API, and so on.
a. Java Servlets
It’s used to create dynamic and interactive web pages. Servlets create web dynamic pages, have the
great feature for User Interaction that quickly creates responses that match your actions.
Servlets act as a fast messenger between your web browser and servlet. Servlet manages users
request and response, as the servlet receives users request, it processes and sends back a tailored response.
2. Concurrency
Concurrency having the ability in Advanced Java to execute multiple tasks simultaneously, that
runs independently and concurrently by allowing different programs.
Concurrency plays an important role as it maximises the performance, enhances responsiveness, in
simpler terms concurrency implements multiple tasks at once, it has the synchronisation that prevents the
data corruption and race conditions, and deadlocks.
is vital in modern software development where Java provides thread-safe collections like
ConcurrentMap and ConcurrentQueue that are accessed by multiple threads concurrently.
3. Multithreading
Multithreading is the process of having several tasks running together parallelly. Multithreading has
Java API features that creates and manages thread easily. In Advanced Java by using multithreading in
applications developers can create more fast, secure, responsive, and capable, so that could handle complex
tasks efficiently.
Java Persistence API is a collection of classes and methods to persist or store the vast amount of
data into a database. JPA is a specification to store or manage Java objects or classes into the databases,
which use Object-Relational Mapping (ORM) as implementation internally to persist the database. JPA
Persistence framework needs to follow:
Spring Data JPA: Spring Data JPA provides a higher-level abstraction layer on the top of JPA that
reduces the amount of boilerplate code needed for common database operations.
Spring Repository: It is a JPA specific extension for Repository, it has full API CRUD Repository
also the Paging and Sorting Repository. So basically, the JPA repository contains APIs for basic CRUD
operations, the APIs for pagination and the APIs for Sorting.
6. Spring Framework
1. Pluggability
It allows us to associate and remove business layer objects of with each other
.2. Dependency Injection
It allows you to lose coupling by creating the business layer objects based on the description in the
spring configuration file.
7. Hibernate
Hibernate is a Java Persistence Framework. Persistence is the availability of the object/data even
after the process that created it,is terminated.
2. Session: The session object provides an interface between the application and data stored into the
database.
9. Java Security
The term ‘Security’ means to ensure that your application is secured, and it checks for valid users if
they login, it may login successfully if the user is authorised, but if the user is invalid then it is denied
access to the application. So basically, it works on two scenarios i.e. Authentication, and Authorization.
Java supports secure communication through protocoles like SSL/TLS, that enables encrypted data
exchange over the network. independent(no session management), or Single-Sign-On (SSO) and manages
authorization to control access to specific functionalities.