You are on page 1of 74

Chapter 1

AWT and Swing

Concepts of AWT

AWT stands for Abstract Window Toolkit. It is a platform dependent API for

creating Graphical User Interface (GUI) for java programs.

Abstract Window Toolkit (AWT) is a set of application program interfaces (API s)

used by Java programmers to create graphical user interface (GUI) objects, such

as buttons, scroll bars, and windows. AWT is part of the Java Foundation Classes

(JFC) from Sun Microsystems, the company that originated Java. The JFC are a

comprehensive set of GUI class libraries that make it easier to develop the user

interface part of an application program.

API-An application programming interface (API) is a computing interface which

defines interactions between multiple software intermediaries. It defines the

kinds of calls or requests that can be made, how to make them, the data formats

that should be used, the conventions to follow, etc.

Why AWT is platform dependent? Java AWT calls native platform (Operating

systems) subroutine for creating components such as textbox, checkbox, button

etc. For example an AWT GUI having a button would have a different look and feel

across platforms like windows, Mac OS & Unix, this is because these platforms

have different look and feel for their native buttons and AWT directly calls their

native subroutine that creates the button. In simple, an application build on AWT

would look like a windows application when it runs on Windows, but the same

application would look like a Mac application when runs on Mac OS.

P a g e 1 | 74
AWT hierarchy

Component class

Component class is at the top of AWT hierarchy. It is an abstract class that


encapsulates all the attributes of visual component. A component object is
responsible for remembering the current foreground and background colors and
the currently selected text font.

Container

Container is a component in AWT that contains another component like button,


text field, tables etc. Container is a subclass of component class. Container class
keeps track of components that are added to another component.

Panel

Panel class is a concrete subclass of Container. Panel does not contain title bar,
menu bar or border. It is container that is used for holding components.

P a g e 2 | 74
Window class

Window class creates a top level window. Window does not have borders and menu
bar.

Frame

Frame is a subclass of Window and have resizing canvas. It is a container that


contain several different components like button, title bar, textfield, label etc. In
Java, most of the AWT applications are created using Frame window.

Java AWT Example

We can create a GUI using Frame in two ways:


1) By extending Frame class
2) By creating the instance of Frame class
Lets have a look at the example of each one.

AWT Example 1: creating Frame by extending Frame class

import java.awt.*;
/* We have extended the Frame class here,
 * thus our class "SimpleExample" would behave
 * like a Frame
 */
public class SimpleExample extends Frame{
    SimpleExample(){  
        Button b=new Button("Button!!");
        
        // setting button position on screen
        b.setBounds(50,50,50,50);  
        
        //adding button into frame
        add(b);
        
        //Setting Frame width and height
        setSize(500,300);
        
        //Setting the title of Frame
        setTitle("This is my First AWT example");
        
        //Setting the layout for the Frame
        setLayout(new FlowLayout());
P a g e 3 | 74
        
        /* By default frame is not visible so
         * we are setting the visibility to true
         * to make it visible.
         */
        setVisible(true);  
    }  
    public static void main(String args[]){  
         // Creating the instance of Frame
         SimpleExample fr=new SimpleExample();  
    }
}
Output:

Concepts of swing

What is Swing in Java?

Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets for
building optimized window based applications. It is a part of the JFC (Java
Foundation Classes). It is built on top of the AWT API and entirely written in java.
It is platform independent unlike AWT and has lightweight components.

It becomes easier to build applications since we already have GUI components like
button, checkbox etc. This is helpful because we do not have to start from the
scratch.

Container Class

P a g e 4 | 74
Any class which has other components in it is called as a container class. For
building GUI applications at least one container class is necessary.

Following are the three types of container classes:

Panel – It is used to organize components on to a window

Frame – A fully functioning window with icons and titles

Dialog – It is like a pop up window but not fully functional like the frame

Java Swing Class Hierarchy

Explanation: All the components in swing like JButton, JComboBox, JList, JLabel
are inherited from the JComponent class which can be added to the container
classes. Containers are the windows like frame and dialog boxes. Basic swing
components are the building blocks of any gui application. Methods like setLayout
override the default layout in each container. Containers like JFrame and JDialog
can only add a component to itself. Following are a few components with examples
to understand how we can use them.

P a g e 5 | 74
Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

No Java AWT Java Swing


.

1) AWT components are platform-dependent. Java swing components


are platform-independent.

2) AWT components are heavyweight. Swing components are lightweight.

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.

5) AWT doesn't follows MVC(Model View Controller) Swing follows MVC.


where model represents data, view represents
presentation and controller acts as an interface
between model and view.

JButton Class
P a g e 6 | 74
It is used to create a labelled button. Using the ActionListener it will result in
some action when the button is pushed. It inherits the AbstractButton class and is
platform independent. Output

import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JButton b = new JButton("click me");
b.setBounds(40,90,85,20);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
JTextField Class

It inherits the JTextComponent class and it is used to allow editing of single line

text.
import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JTextField b = new JTextField("harambee");
b.setBounds(50,100,200,30);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}

JScrollBar Class
P a g e 7 | 74
It is used to add scroll bar, both horizontal and vertical.

Example:
import javax.swing.*;
class example{
example(){
JFrame a = new JFrame("example");
JScrollBar b = new JScrollBar();
b.setBounds(90,90,40,90);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[]){
new example();
}
}
JPanel Class
It inherits the JComponent class and provides space for an application which can
attach any other component. Output:

import java.awt.*;
import javax.swing.*;
public class Example{
Example(){
JFrame a = new JFrame("example");
JPanel p = new JPanel();
p.setBounds(40,70,200,200);
JButton b = new JButton("click me");
b.setBounds(60,50,80,40);
p.add(b);
a.add(p);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}

P a g e 8 | 74
JMenu Class

It inherits the JMenuItem class, and is a pull down menu component which is
displayed from the menu bar.

import javax.swing.*;
class Example{
JMenu menu;
JMenuItem a1,a2;
Example()
{
JFrame a = new JFrame("Example");
menu = new JMenu("options");
JMenuBar m1 = new JMenuBar();
a1 = new JMenuItem("example");
a2 = new JMenuItem("example1");
menu.add(a1);
menu.add(a2);
m1.add(menu);
a.setJMenuBar(m1);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
JList Class

It inherits JComponent class, the object of JList class represents a list of text
items.

import javax.swing.*;
public class Example
{
Example(){
JFrame a  = new JFrame("example");
DefaultListModel<String> l = new
DefaultListModel< >();
l.addElement("first item");
l.addElement("second item");
JList<String> b = new JList< >(l);
b.setBounds(100,100,75,75);
a.add(b);
a.setSize(400,400);

P a g e 9 | 74
a.setVisible(true);
a.setLayout(null);
}
public static void main(String args[])
{
new Example();
}
}

JCheckBox
}
The class JCheckBox is an implementation of a check box - an item that can be
selected or deselected, and which displays its state to the user.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JCheckBox jcb = new JCheckBox("yes"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("no"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("maybe"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

}
}

P a g e 10 | 74
JLabel

JLabel is a class of java Swing. JLabel is used to display a short string or an image
icon. JLabel can display text, image or both. JLabel is only a display of text or
image and it cannot get focus. JLabel is inactive to input events such a mouse focus
or keyboard focus.

Constructor of the class are:

1. JLabel() : creates a blank label with no text or image in it.

2. JLabel(String s) : creates a new label with the string specified.

3. JLabel(Icon i) : creates a new label with a image on it.

4. JLabel(String s, Icon i, int align) : creates a new label with a string, an


image and a specified horizontal alignment

JLabel label1 = new JLabel("A basic label."); OR


JLabel label1;
label1 = new JLabel("A basic label.");

P a g e 11 | 74
JComboBox

JComboBox is a part of Java Swing package. JComboBox inherits JComponent


class. JComboBox shows a popup menu that shows a list and the user can select an
option from that specified list. JComboBox can be editable or read- only depending
on the choice of the programmer.

Constructor of the JComboBox are:

1. JComboBox() : creates a new empty JComboBox .

2. JComboBox(ComboBoxModel M) : creates a new JComboBox with items


from specified ComboBoxModel

3. JComboBox(E [ ] i) : creates a new JComboBox with items from specified


array.

4. JComboBox(Vector items) : creates a new JComboBox with items from the


specified vector

Event Handling

What is an Event?

Change in the state of an object is known as event i.e. event describes the change
in state of source. Events are generated as result of user interaction with the
graphical user interface components. For example, clicking on a button, moving the
mouse, entering a character through keyboard, selecting an item from list, scrolling
the page are the activities that causes an event to happen.

Types of Event

The events can be broadly classified into two categories:

 Foreground Events - Those events which require the direct interaction of


user. They are generated as consequences of a person interacting with the
graphical components in Graphical User Interface. For example, clicking on a

P a g e 12 | 74
button, moving the mouse, entering a character through keyboard, selecting
an item from list, scrolling the page etc.

 Background Events - Those events that require the interaction of end user
are known as background events. Operating system interrupts, hardware or
software failure, timer expires, an operation completion are the example of
background events.

Currently, the Java core consists of 12 event types defined


in java.awt.events:-

 ActionEvent  ItemEvent

 AdjustmentEvent  KeyEvent

 ComponentEvent  MouseEvent

 ContainerEvent  PaintEvent

 FocusEvent  TextEvent

 InputEvent  WindowEvent

ActionEvent

The Java ActionListener is notified whenever you click on the button or menu item.
It is notified against ActionEvent. The ActionListener interface is found in
java.awt.event package. It has only one method: actionPerformed().

actionPerformed() method

The actionPerformed() method is invoked automatically whenever you click on the


registered component.

public abstract void actionPerformed(ActionEvent e);

How to write ActionListener

The common approach is to implement the ActionListener. If you implement the


ActionListener class, you need to follow 3 steps:

P a g e 13 | 74
1) Implement the ActionListener interface in the class:

public class ActionListenerExample Implements ActionListener  

2) Register the component with the Listener:

component.addActionListener(instanceOfListenerclass); 

3) Override the actionPerformed() method:

public void actionPerformed(ActionEvent e){  
           //Write the code here  

Java ActionListener Example: On Button click

import java.awt.*;  
import java.awt.event.*;  
//1st step  
public class ActionListenerExample implements ActionListener{  
public static void main(String[] args) {  
    Frame f=new Frame("ActionListener Example");  
    final TextField tf=new TextField();  
    tf.setBounds(50,50, 150,20);  
    Button b=new Button("Click Here");  
    b.setBounds(50,100,60,30);  
    //2nd step  
    b.addActionListener(this);  
    f.add(b);f.add(tf);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);   
}  
//3rd step  
public void actionPerformed(ActionEvent e){  
            tf.setText("Welcome to Action Listner.");  
}  
}  

P a g e 14 | 74
P a g e 15 | 74
Chapter 2

Streams and File I/O

Stream represents a sequence of objects from a source, which supports aggregate


operations. There are a few key definitions we need to go through to understand
this notion of a Stream and why it differs from a Collection:

A Stream does not hold any Data

Stream does not hold any data. This is very important to keep that in mind and
understand.

There is no data in a Stream, however, there is data held in a Collection.

A Collection is a structure that holds its data. A Stream is just there to process
the data and pull it out from the given source, or move it to a destination. The
source might be a Collection, though it might also be an array or I/O resource. The
stream will connect to the source, consume the data, and process the elements in it
in some way.

Stream Characteristics

 Element sequence - Streams provide a set of elements of a particular type


in a sequential manner. The stream gets an element on demand and never
stores an item.

P a g e 16 | 74
 Source - Streams take a collection, array, or I/O resources as a source for
their data.

 Aggregate operations - Streams support collective operations such


as forEach, filter, map, sorted, match, and others.

 Overriding - Most operations over a Stream returns a Stream, which means


their results can be chained. The function of these operations is to take
input data, process it, and return the target output. The collect() method is
a terminal operation that is usually present at the end of operations to
indicate the end of the Stream processing.

 Automated iterations - Stream operations carry out iterations internally


over the source of the elements, as opposed to collections where explicit
iteration is required.

Types of Streams

Java provides I/O Streams to read and write data where, a Stream represents an
input source or an output destination which could be a file, i/o devise, other
program etc.

In general, a Stream will be an input stream or, an output stream.

 InputStream − this is used to read data from a source.

 OutputStream − this is used to write data to a destination.

Based on the data they handle there are two types of streams −

Byte Streams − these handle data in bytes (8 bits) i.e., the byte stream classes
read/write data of 8 bits. Using these you can store characters, videos, audios,
images etc.

Character Streams − these handle data in 16 bit Unicode. Using these you can read
and write text data only.

P a g e 17 | 74
Standard Streams

Java provides 3 standard streams representing the input and, output devices.

 Standard Input − this is used to read data from user through input devices.
Keyboard is used as standard input stream and represented as System.in.

 Standard Output − this is used to project data (results) to the user through
output devices. A computer screen is used for standard output stream and
represented as System.out.

 Standard Error − This is used to output the error data produced by the
user's program and usually a computer screen is used for standard error
stream and represented as System.err.

Java defines two types of streams. They are,

Byte Stream: It provides a convenient means for handling input and output of
byte.

Character Stream: It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.

Java Byte Stream Classes

Byte stream is defined by using two abstract class at the top of hierarchy, they
are InputStream and OutputStream.

P a g e 18 | 74
These two abstract classes have several concrete classes that handle various
devices such as disk files, network connection etc.

Some important Byte stream classes.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard data

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method

These classes define several key methods. Two most important are

1. read() : reads byte of data.

2. write() : Writes byte of data.

Java Character Stream Classes


P a g e 19 | 74
Character stream is also defined by using two abstract class at the top of
hierarchy, they are Reader and Writer.

These two abstract classes have several concrete classes that handle unicode
character.

Some important Character stream classes

Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

P a g e 20 | 74
Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

File Handling

File handing in java comes under IO operations. Java IO package java.io classes are


specially provided for file handling in java.

Some of the common file handling operations are;

1. Create file

2. Delete file

3. Read file

4. Write file

5. Change file permissions

Create File

We can use File class createNewFile() method to create new file. This method


returns true if file is successfully created, otherwise it returns false. Below is a
simple program showing how to create a new file in java.

import java.io.File;
import java.io.IOException;

P a g e 21 | 74
public class FileCreateDemo1
{
public static void main(String[] args)
{
try
{
File Obj = new File("FileDemo.txt");
if (Obj.createNewFile()) {
System.out.println("******File created******");
System.out.println("Name of the file = " + Obj.getName());
}
else{
System.out.println("File already exists.");
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
Writing in a file

After creating a file, now will write data to the file. To write data, a method of
Filewrite class is used. It will write the data but may throw exception so make sure
to handle the excecptions as well.

import java.io.FileWriter;
import java.io.IOException;
public class FileWriteDemo1
{
public static void main(String[] args)
{
try
{
FileWriterobj = new FileWriter("FileDemo.txt");
obj.write("Welcome to First File Writing.");
obj.close();
System.out.println("File is Updated.");
}
catch (IOException e)
{
e.printStackTrace();
} } }

Reading a file
P a g e 22 | 74
To read data from the file we used File and Scenner classes both are used to
handle input and output of system resources. Here we are using two
method hasNextLine() and nextLine() to read the data sequentially.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReadDemo1
{
public static void main(String[] args)
{
try
{
File Obj = new File( "FileDemo.txt" );
Scanner obj1 = new Scanner(Obj);
while (obj1.hasNextLine())
{
String obj2 = obj1.nextLine();
System.out.println(obj2);
}
obj1.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}

Copying a file

Let’s take another example to copy data of one file to another. Here we are using
fileinput and output streams to read and write data. Although this is just a
procedure to copy one file data to another whereas Java provides built-in methods
to direct copy one file data to another file. See the below example.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopyDemo1 {
public static void main(String[] args) {
FileInputStream a = null;
FileOutputStream b = null;
try {
P a g e 23 | 74
File obj_in = new File( "FileDemo.txt" );
File obj_out = new File( "FileDemo1.txt" );

a = new FileInputStream(obj_in);
b = new FileOutputStream(obj_out);

byte[] buffer = new byte[1024];

int length;
while ((length = a.read(buffer)) > 0) {
b.write(buffer, 0, length);
}
a.close();
b.close();
System.out.println( "File copied successfully!!" );
} catch (IOException e) {
e.printStackTrace();
}
}
}
File permissions

We can check permissions like: reading, writing, deleting etc of a file by using the
built-in methods. The File class provides methods canRead(), canWrite() etc to
check whether the operation is permissible or not.

import java.io.*;
public class FilePermissionDemo1 {
public static void main(String[] args) {
File a = new File("FileDemo1.txt");
boolean b = a.exists();
if (b == true) {
System.out.println ( "Executable: " + a.canExecute());
System.out.println( "Readable: " + a.canRead());
System.out.println( "Writable: " + a.canWrite());
} else {
System.out.println( "File not found." );
}
}}
Retrieving file information
P a g e 24 | 74
This is one of the important part of file handling, getting metadata of a file is
necessary to keep the information about the file like: type of file, location of file,
permissions of file etc. in this example, we are using some built-in methods of File
class to get information about the file. See the below example
import java.io.File;
public class FileInfoDemo1
{
public static void main(String[] args)
{
File Obj = new File( "FileDemo1.txt" );
if (Obj.exists())
{
System.out.println( "File name= " +
Obj.getName());
System.out.println( "***********************************" );
System.out.println( "Absolute path= " +
Obj.getAbsolutePath());
System.out.println( "***********************************" );
System.out.println( "Writeable= " + Obj.canWrite());
System.out.println( "***********************************" );
System.out.println( "Readable= " + Obj.canRead());
System.out.println("***********************************");
System.out.println( "File size in bytes= " + Obj.length());
}
else
{
System.out.println( "file does not exist." );
}
}
}

Deleting a file

In case, we need to delete a file then Java provides the method delete() that helps
to delete a file using a code. In this example, we are deleting file. The method
returns a boolean value to ensure that file has deleted successfully.

import java.io.File;

public class FileDeleteDemo1 {

public static void main(String[] args) {

P a g e 25 | 74
File Obj = new File("FileDemo.txt");

if (Obj.delete()) {

System.out.println(Obj.getName() + " has been deleted" );

else {

System.out.println("Failed");

Exception handling

Exception handling is one of the most important feature of java programming that
allows us to handle the runtime errors caused by exceptions.

An Exception is an unwanted event that interrupts the normal flow of the program.
When an exception occurs program execution gets terminated. In such cases we
get a system generated error message. The good thing about exceptions is that
they can be handled in Java. By handling the exceptions we can provide a
meaningful message to the user about the issue rather than a system generated
message, which may not be understandable to a user.

Why an exception occurs?

There can be several reasons that can cause a program to throw exception. For
example: Opening a non-existing file in your program, Network connection problem,
bad input data provided by user etc.

Exception Handling

P a g e 26 | 74
If an exception occurs, which has not been handled by programmer then program
execution gets terminated and a system generated error message is shown to the
user.

Difference between error and exception

Errors indicate that something severe enough has gone wrong, the application
should crash rather than try to handle the error.

Exceptions are events that occurs in the code. A programmer can handle such
conditions and take necessary corrective actions. Few examples:
NullPointerException – When you try to use a reference that points to null.
ArithmeticException – When bad data is provided by user, for example, when you
try to divide a number by zero this exception occurs because dividing a number by
zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an
array out of its bounds, for example array size is 5 (which means it has five
elements) and you are trying to access the 10th element.

Types of exceptions

There are two types of exceptions in Java:


1)Checked exceptions
2)Unchecked exceptions

Checked exceptions

All exceptions other than Runtime Exceptions are known as Checked exceptions as
the compiler checks them during compilation to see whether the programmer has
handled them or not. If these exceptions are not handled/declared in the program,
you will get compilation error. For example, SQLException, IOException,
ClassNotFoundException etc.

P a g e 27 | 74
Unchecked Exceptions

Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are
not checked at compile-time so compiler does not check whether the programmer
has handled them or not but it’s the responsibility of the programmer to handle
these exceptions and provide a safe exit. For example, ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.

P a g e 28 | 74
Chapter 3
Multi-threading Concept
Before we talk about multithreading, let’s discuss threads. A thread is a light-

weight smallest part of a process that can run concurrently with the other

parts(other threads) of the same process. Threads are independent because they

all have separate path of execution that’s the reason if an exception occurs in one

thread, it doesn’t affect the execution of other threads. All threads of a process

share the common memory. The process of executing multiple threads

simultaneously is known as multithreading.

Multithreading is a Java feature that allows concurrent execution of two or more

parts of a program for maximum utilization of CPU. Each part of such program is

called a thread. So, threads are light-weight processes within a process.

Let’s summarize the discussion in points:

1. The main purpose of multithreading is to provide simultaneous execution of two

or more parts of a program to maximum utilize the CPU time. A multithreaded

program contains two or more parts that can run concurrently. Each such part of a

program called thread.

2. Threads are lightweight sub-processes, they share the common memory space.

In Multithreaded environment, programs that are benefited from multithreading,

utilize the maximum CPU time so that the idle time can be kept to minimum.

3. A thread can be in one of the following states:

NEW – A thread that has not yet started is in this state.

RUNNABLE – A thread executing in the Java virtual machine is in this state.

BLOCKED – A thread that is blocked waiting for a monitor lock is in this state.

P a g e 29 | 74
WAITING – A thread that is waiting indefinitely for another thread to perform a

particular action is in this state.

TIMED_WAITING – A thread that is waiting for another thread to perform an

action for up to a specified waiting time is in this state.

TERMINATED – A thread that has exited is in this state.

Multitasking vs Multithreading vs Multiprocessing vs parallel processing

If you are new to java you may get confused among these terms as they are used
quite frequently when we discuss multithreading. Let’s talk about them in brief.

Multitasking: Ability to execute more than one task at the same time is known as
multitasking.

Multithreading: We already discussed about it. It is a process of executing


multiple threads simultaneously. Multithreading is also known as Thread-based
Multitasking.

Multiprocessing: It is same as multitasking, however in multiprocessing more than


one CPUs are involved. On the other hand one CPU is involved in multitasking.

Parallel Processing: It refers to the utilization of multiple CPUs in a single


computer system.

Creating a thread

There are two ways to create a thread in Java:


1) By extending Thread class.
2) By implementing Runnable interface.

Before we begin with the programs(code) of creating threads, let’s have a look at
these methods of Thread class. We have used few of methods are:-

P a g e 30 | 74
 getName(): It is used for Obtaining a thread’s name

 getPriority(): Obtain a thread’s priority

 isAlive(): Determine if a thread is still running

 join(): Wait for a thread to terminate

 run(): Entry point for the thread

 sleep(): suspend a thread for a period of time

 start(): start a thread by calling its run() method

Method 1: Thread creation by extending Thread class

class MultithreadingDemo extends Thread{


public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}
}
Output:

My thread is in running state.


Method 2: Thread creation by implementing Runnable Interface

A Simple Example

class MultithreadingDemo implements Runnable{


public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
Thread tobj =new Thread(obj);
tobj.start();
}
}
Process and thread

Process:
Process means any program is in execution. Process control block controls the

P a g e 31 | 74
operation of any process. Process control block contains information about
processes for example Process priority, process id, process state, CPU, register,
etc. A process can creates other processes which are known as Child Processes.
Process takes more time to terminate and it is isolated means it does not share
memory with any other process.

The process can have states like new, ready, running, waiting, terminated, and
suspended.

Thread:
Thread is the segment of a process means a process can have multiple threads and
these multiple threads are contained within a process. A thread have 3 states:
running, ready, and blocked.

Thread takes less time to terminate as compared to process and like process
threads do not isolate.

P a g e 32 | 74
S.NO PROCESS THREAD

Process means any program is in


1. execution. Thread means segment of a process.

2. Process takes more time to terminate. Thread takes less time to terminate.

3. It takes more time for creation. It takes less time for creation.

It also takes more time for context


4. switching. It takes less time for context switching.

Process is less efficient in term of Thread is more efficient in term of


5. communication. communication.

6. Process consume more resources. Thread consume less resources.

7. Process is isolated. Threads share memory.

Process is called heavy weight


8. process. Thread is called light weight process.

9. Process switching uses interface in Thread switching does not require to call a
operating system. operating system and cause an interrupt to
P a g e 33 | 74
the kernel.

If one server process is blocked no


other server process can execute Second thread in the same task could run,
10. until the first process unblocked. while one server thread is blocked.

Multithreading 

Multithreading is a concept of running multiple threads simultaneously. Thread is a


lightweight unit of a process that executes in multithreading environment.

A program can be divided into a number of small processes. Each small process can
be addressed as a single thread (a lightweight process). You can think of a
lightweight process as a virtual CPU that executes code or system calls. You usually
do not need to concern yourself with lightweight processes to program with
threads. Multithreaded programs contain two or more threads that can run
concurrently and each thread defines a separate path of execution. This means
that a single program can perform two or more tasks simultaneously. For example,
one thread is writing content on a file at the same time another thread is
performing spelling check.

In Java, the word thread means two different things.

 An instance of Thread class.

 or, A thread of execution.

An instance of Thread class is just an object, like any other object in java. But a
thread of execution means an individual "lightweight" process that has its own call
stack. In java each thread has its own call stack.

P a g e 34 | 74
Advantage of Multithreading

Multithreading reduces the CPU idle time that increase overall performance of the


system. Since thread is lightweight process then it takes less memory and
perform context switching as well that helps to share the memory and reduce time
of switching between threads.

Multitasking

Multitasking is a process of performing multiple tasks simultaneously. We can


understand it by computer system that perform multiple tasks like: writing data to
a file, playing music, downloading file from remote server at the same time.

Multitasking can be achieved either by using multiprocessing or multithreading.


Multitasking by using multiprocessing involves multiple processes to execute
multiple tasks simultaneously whereas Multithreading involves multiple threads to
execute multiple tasks.

Why Multithreading?

Thread has many advantages over the process to perform multitasking. Process is
heavy weight, takes more memory and occupy CPU for longer time that may lead to
performance issue with the system. To overcome these issue process is broken into
small unit of independent sub-process. These sub-process are called threads that

P a g e 35 | 74
can perform independent task efficiently. So nowadays computer systems prefer
to use thread over the process and use multithreading to perform multitasking.

How to Create Thread?

To create a thread, Java provides a class Thread and an interface Runnable both


are located into java.lang package.

We can create thread either by extending Thread class or implementing Runnable


interface. Both includes a run method that must be override to provide thread
implementation.

The main thread

When we run any java program, the program begins to execute its code starting
from the main method. Therefore, the JVM creates a thread to start executing
the code present in main method. This thread is called as main thread. Although
the main thread is automatically created, you can control it by obtaining a
reference to it by calling currentThread() method.

Two important things to know about main thread are,

 It is the thread from which other threads will be produced.

 It must be always the last thread to finish execution.

class MainThread
{
public static void main(String[] args)
{
Thread t = Thread.currentThread();
t.setName("MainThread");
System.out.println("Name of thread is "+t);
}
}
Output

Name of thread is Thread [MainThread, 5, main]


Life cycle of a Thread

P a g e 36 | 74
Like process, thread have its life cycle that includes various phases like: new,
running, terminated etc. we have described it using the below image.

1. New : A thread begins its life cycle in the new state. It remains in this
state until the start() method is called on it.
2. Runnable : After invocation of start() method on new thread, the thread
becomes runnable.
3. Running : A thread is in running state if the thread scheduler has selected
it.
4. Waiting : A thread is in waiting state if it waits for another thread to
perform a task. In this stage the thread is still alive.
5. Terminated : A thread enter the terminated state when it complete its
task.
Thread Priorities

Priority of a thread describes how early it gets execution and selected by the
thread scheduler. In Java, when we create a thread, always a priority is assigned
to it. In a Multithreading environment, the processor assigns a priority to a thread
scheduler. The priority is given by the JVM or by the programmer itself explicitly.
The range of the priority is between 1 to 10 and there are three constant variables
which are static and used to fetch priority of a Thread. They are as following:

P a g e 37 | 74
1. public static int MIN_PRIORITY

It holds the minimum priority that can be given to a thread. The value for this is 1.

2. public static int NORM_PRIORITY

It is the default priority that is given to a thread if it is not defined. The value for
this is 0.

3. public static int MAX_PRIORITY

It is the maximum priority that can be given to a thread. The value for this is 10.

Get and Set methods in Thread priority

1. public final intgetPriority()

In Java, getPriority() method is in java.lang.Thread package. it is used to get the


priority of a thread.

2. public final void setPriority(intnewPriority)

In Java setPriority(intnewPriority) method is in java.lang.Thread package. It is


used to set the priority of a thread. The setPriority() method throws
IllegalArgumentException if the value of new priority is above minimum and
maximum limit.

P a g e 38 | 74
Chapter Four
Introduction to Java Networking

Java Networking is a notion of connecting two or more computing devices together

to share the resources. Java program communicates over the network at

the application layer. java.net package is useful for all the Java networking

classes and interfaces. 

The java.net package provides support for two protocols. They are as follows:

 TCP − Transmission Control Protocol allows reliable communication between

two applications. TCP is typically used over the Internet Protocol, which is

referred to as TCP/IP.

 UDP − User Datagram Protocol is a connection-less protocol that allows

packets of data to be transmitted between applications.

Java Networking Terminology

The widely used java networking terminologies are given below:

1. IP Address

2. Protocol

3. Port Number

4. MAC Address

5. Connection-oriented and connection-less protocol

6. Socket

1) IP Address

IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It

is composed of octets that range from 0 to 255.

P a g e 39 | 74
It is a logical address that can be changed. An IP(Internet Protocol) address is an

identifier assigned to each computer and other device(e.g., router, mobile, etc)

connected to a TCP/IP network that is used to locate and identify the node in

communication with other nodes on the network. IP addresses are usually written

and displayed in human-readable notation such as 192.168.1.35 in IPv4(32-bit IP

address).

An IP address serves two principle functions : host or network interface

identification and local addressing. It’s role has been characterized as follows : “A

name indicate what we seek. An address indicate where it is.

2) Protocol

A protocol is a set of rules basically that is followed for communication. For

example:

o TCP

Transmission Control Protocol (TCP) – a connection-oriented communications

protocol that facilitates the exchange of messages between computing devices in a

network. It is the most common protocol in networks that use the Internet

Protocol (IP); together they are sometimes referred to as TCP/IP.

TCP takes messages from an application/server and divides them into packets,

which can then be forwarded by the devices in the network – switches, routers,

security gateways – to the destination. TCP numbers each packet and reassembles

them prior to handing them off to the application/server recipient. Because it is

connection-oriented, it ensures a connection is established and maintained until the

exchange between the application/servers sending and receiving the message is

complete.

P a g e 40 | 74
o FTP

FTP is a widely used network protocol for transferring files between computers

over a TCP/IP-based network, such as the Internet. FTP lets people

and applications exchange and share data within their offices and across the

Internet.

o Telnet

A terminal emulation that enables a user to connect to a remote host or device

using a telnet client. For example, typing telnet hostname would connect a user to a

hostname named hostname. Telnet enables a user to manage an account or device

remotely. For example, a user may telnet into a computer that hosts their website

to manage his or her files remotely. In the image is an example of a telnet session.

o SMTP

Simple Mail Transfer Protocol

An SMTP (Simple Mail Transfer Protocol) server is an application that's primary

purpose is to send, receive, and/or relay outgoing mail between email senders and

receivers.

o POP

3) Port Number

The port number is used to uniquely identify different applications. It acts as a

communication endpoint between applications.

The port number is associated with the IP address for communication between two

applications.

P a g e 41 | 74
4) MAC Address

MAC (Media Access Control) Address is a unique identifier of NIC (Network

Interface Controller). A network node can have multiple NIC but each with unique

MAC.

5) Connection-oriented and connection-less protocol

In connection-oriented protocol, acknowledgement is sent by the receiver. So it is

reliable but slow. The example of connection-oriented protocol is TCP.

But, in connection-less protocol, acknowledgement is not sent by the receiver. So it

is not reliable but fast. The example of connection-less protocol is UDP.

6) Socket

A socket is an endpoint between two way communications.

A socket in Java is one endpoint of a two-way communication link between two

programs running on the network. A socket is bound to a port number so that the

TCP layer can identify the application that data is destined to be sent to.

Now that you know various terminologies used in Java Networking, let’s move

further and understand some of the important classes that it supports.

Inet Address

Inet Address is used to encapsulate both the numerical IP address and the domain

name for that address. It can handle both IPv4 and Ipv6 addresses.

Connecting to a server

Client Side Programming

Establish a Socket Connection

P a g e 42 | 74
To connect to other machine we need a socket connection. A socket connection

means the two machines have information about each other’s network location (IP

Address) and TCP port.The java.net.Socket class represents a Socket. To open a

socket:
Socket socket = new Socket(“127.0.0.1”, 5000)
 First argument – IP address of Server. ( 127.0.0.1  is the IP address of

localhost, where code will run on single stand-alone machine).

 Second argument – TCP Port. (Just a number representing which application

to run on a server. For example, HTTP runs on port 80. Port number can be

from 0 to 65535)

Communication

To communicate over a socket connection, streams are used to both input and

output the data.

Closing the connection

The socket connection is closed explicitly once the message to server is sent.

In the program, Client keeps reading input from user and sends to the server until

“Over” is typed.

Java Implementation

// A Java program for a Client


import java.net.*;
import java.io.*;
  
public class Client
{
    // initialize socket and input output streams
    private Socket socket            = null;
    private DataInputStream  input   = null;
    private DataOutputStream out     = null;
  
    // constructor to put ip address and port

P a g e 43 | 74
    public Client(String address, int port)
    {
        // establish a connection
        try
        {
            socket = new Socket(address, port);
            System.out.println("Connected");
  
            // takes input from terminal
            input  = new DataInputStream(System.in);
  
            // sends output to the socket
            out    = new
DataOutputStream(socket.getOutputStream());
        }
        catch(UnknownHostException u)
        {
            System.out.println(u);
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
 
        // string to read message from input
        String line = "";
  
        // keep reading until "Over" is input
        while (!line.equals("Over"))
        {
            try
            {
                line = input.readLine();
                out.writeUTF(line);
            }
            catch(IOException i)
            {
                System.out.println(i);
            }
        }
  
        // close the connection
        try
        {
            input.close();

P a g e 44 | 74
            out.close();
            socket.close();
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
    }
  
    public static void main(String args[])
    {
        Client client = new Client("127.0.0.1", 5000);
    }
}

Server Programming

Establish a Socket Connection

To write a server application two sockets are needed.

 A ServerSocket which waits for the client requests (when a client makes a

new Socket())

 A plain old Socket socket to use for communication with the client.

Communication

getOutputStream() method is used to send the output through the socket.

Close the Connection

After finishing,  it is important to close the connection by closing the socket as

well as input/output streams.


// A Java program for a Server
import java.net.*;
import java.io.*;
 
public class Server
{
    //initialize socket and input stream
    private Socket          socket   = null;
    private ServerSocket    server   = null;

P a g e 45 | 74
    private DataInputStream in       =  null;
  
    // constructor with port
    public Server(int port)
    {
        // starts server and waits for a connection
        try
        {
            server = new ServerSocket(port);
            System.out.println("Server started");
  
            System.out.println("Waiting for a client ...");
  
            socket = server.accept();
            System.out.println("Client accepted");
  
            // takes input from the client socket
            in = new DataInputStream(
                new
BufferedInputStream(socket.getInputStream()));
  
            String line = "";
  
            // reads message from client until "Over" is sent
            while (!line.equals("Over"))
            {
                try
                {
                    line = in.readUTF();
                    System.out.println(line);
  
                }
                catch(IOException i)
                {
                    System.out.println(i);
                }
            }
            System.out.println("Closing connection");
  
            // close connection
P a g e 46 | 74
            socket.close();
            in.close();
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
    }
  
    public static void main(String args[])
    {
        Server server = new Server(5000);
    }
}
Important Points

 Server application makes a ServerSocket on a specific port which is 5000.

This starts our Server listening for client requests coming in for port 5000.

 Then Server makes a new Socket to communicate with the client.

socket = server.accept()

 The accept() method blocks(just sits there) until a client connects to the

server.

 Then we take input from the socket using getInputStream() method. Our

Server keeps receiving messages until the Client sends “Over”.

 After we’re done we close the connection by closing the socket and the input

stream.

 To run the Client and Server application on your machine, compile both of

them. Then first run the server application and then run the Client

application.

To run on Terminal or Command Prompt

Open two windows one for Server and another for Client

1. First run the Server application as ,


P a g e 47 | 74
$ java Server

Server started

Waiting for a client …

2. Then run the Client application on another terminal as,

$ java Client

It will show – Connected and the server accepts the client and shows,

Client accepted

3. Then you can start typing messages in the Client window. Here is a sample input

to the Client

Hello

I made my first socket connection

Over

Which the Server simultaneously receives and shows,

Hello

I made my first socket connection

Over

Closing connection

P a g e 48 | 74
Chapter 5
Remote Method Invocation
RMI stands for Remote Method Invocation. It is a mechanism that allows an

object residing in one system (JVM) to access/invoke an object running on another

JVM.

RMI is used to build distributed applications; it provides remote communication

between Java programs. It is provided in the package java.rmi.

A RMI application can be divided into two part,Client program and Server program.

A Server program creates some remote object, make their references available

for the client to invoke method on it. A Client program make request for remote

objects on server and invoke method on them. Stub and Skeleton are two

important object used for communication with remote object.

Understanding stub and skeleton

RMI uses stub and skeleton object for communication with the remote object.

A remote object is an object whose method can be invoked from another JVM.
Let's understand the stub and skeleton objects:

Stub

The stub is an object, acts as a gateway for the client side. All the outgoing
requests are routed through it. It resides at the client side and represents the
remote object. When the caller invokes method on the stub object, it does the
following tasks:

1. It initiates a connection with remote Virtual Machine (JVM),


2. It writes and transmits (marshals) the parameters to the remote Virtual
Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and

P a g e 49 | 74
5. It finally, returns the value to the caller.

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.

Marshalling and Unmarshalling

Whenever a client invokes a method that accepts parameters on a remote object,


the parameters are bundled into a message before being sent over the network.
These parameters may be of primitive type or objects. In case of primitive type,
the parameters are put together and a header is attached to it. In case the
parameters are objects, then they are serialized. This process is known as
marshalling.

At the server side, the packed parameters are unbundled and then the required
method is invoked. This process is known as unmarshalling.

Architecture of an RMI Application

In an RMI application, we write two programs, a server program (resides on the

server) and a client program (resides on the client).

 Inside the server program, a remote object is created and reference of

that object is made available for the client (using the registry).

 The client program requests the remote objects on the server and tries to

invoke its methods.

P a g e 50 | 74
The following diagram shows the architecture of an RMI application

Let us now discuss the components of this architecture.

 Transport Layer − This layer connects the client and the server. It manages

the existing connection and also sets up new connections.

 Stub − A stub is a representation (proxy) of the remote object at client. It

resides in the client system; it acts as a gateway for the client program.

 Skeleton − This is the object which resides on the server side. 

stub communicates with this skeleton to pass request to the remote object.

 RRL(Remote Reference Layer) − It is the layer which manages the

references made by the client to the remote object.

Working of an RMI Application

The following points summarize how an RMI application works −

P a g e 51 | 74
 When the client makes a call to the remote object, it is received by the
stub which eventually passes this request to the RRL.
 When the client-side RRL receives the request, it invokes a method
called invoke() of the object remoteRef. It passes the request to the RRL
on the server side.
 The RRL on the server side passes the request to the Skeleton (proxy on
the server) which finally invokes the required object on the server.
 The result is passed all the way back to the client.

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

The following illustration explains the entire process –

P a g e 52 | 74
Goals of RMI

Following are the 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.

Remote interface

A Remote interface is available in the java.rmi package it is a marking/tagging


interface, it is used with remote method invocation(RMI).

RMI is a mechanism that allows an object residing in one system (JVM) to


access/invoke an object running on another JVM.

To it is a marking interface, to mark an object of a class remote, you need to


implement this interface.

To create a remote interface −


P a g e 53 | 74
 Create an interface that extends the predefined interface Remote which
belongs to the package or, implement the Remote interface with the class,
which you need to make remote.

 Declare all the business methods that can be invoked by the client in this
interface.

 Since there is a chance of network issues during remote calls, an exception


named RemoteException may occur; throw it.

These abstraction layers are:

The Stub and Skeleton layer, which intercepts method calls made by the client to
the interface reference variable and redirects these calls to a remote RMI
service.

The Remote Reference layer understands how to interpret and manage references
made from clients to the remote service objects.

The bottom layer is the Transport layer, which is based on TCP/IP connections
between machines in a network. It provides basic connectivity, as well as some
firewall penetration strategies.

On top of the TCP/IP layer, RMI uses a wire-level protocol called Java Remote
Method Protocol (JRMP), which works like this:

1. Objects that require remote behavior should extend


the RemoteObject class, typically through
the UnicastRemoteObject subclass.
P a g e 54 | 74
a. The UnicastRemoteObject subclass exports the remote object to
make it available for servicing incoming RMI calls.

b. Exporting the remote object creates a new server socket, which is


bound to a port number.

c. A thread is also created that listens for connections on that socket.


The server is registered with a registry.

d. A client obtains details of connecting to the server from the registry.

e. Using the information from the registry, which includes the hostname
and the port details of the server's listening socket, the client
connects to the server.

2. When the client issues a remote method invocation to the server, it creates
a TCPConnection object, which opens a socket to the server on the port
specified and sends the RMI header information and the marshalled
arguments through this connection using the StreamRemoteCall class.

3. On the server side:

a. When a client connects to the server socket, a new thread is assigned


to deal with the incoming call. The original thread can continue
listening to the original socket so that additional calls from other
clients can be made.

b. The server reads the header information and creates


a RemoteCall object of its own to deal with unmarshalling the RMI
arguments from the socket.

c. The serviceCall() method of the Transport class services the incoming


call by dispatching it

d. The dispatch() method calls the appropriate method on the object and


pushes the result back down the wire.

e. If the server object throws an exception, the server catches it and


marshals it down the wire instead of the return value.

4. Back on the client side:

P a g e 55 | 74
a. The return value of the RMI is unmarshalled and returned from the
stub back to the client code itself.

b. If an exception is thrown from the server, that is unmarshalled and


thrown from the stub.

P a g e 56 | 74
Chapter 6 –
Java Database Connectivity
What is Database?

The Database is an essential part of our life. As we encounter several activities

that involve our interaction with database, for example in the bank, in the railway

station, in school, in a grocery store, etc. These are the places where we need to a

large amount of data at one place and fetching of this data should be easy.

A database is a collection of data which is organized, which is also called as

structured data. It can be accessed or stored at the computer system. It can be

managed through Database management system (DBMS), which is a software which

is used to manage data. Database refers to related data which is in a structured

form.

In Database, data is organized into tables which consist of rows and columns and it

is indexed so data gets updated, expanded and deleted easily. Computer databases

typically contain file records data like transactions money in one bank account to

another bank account, sales and customer details, fee details of student and

product details. There are different kinds of databases, ranging from the most

prevalent approach, the relational database, to a distributed database, cloud

database or NoSQL database.

 Relational Database:

A relational database is made up of a set of tables with data that fits into a

predefined category.

 Distributed Database:

A distributed database is a database in which portions of the database are

stored in multiple physical locations, and in which processing is dispersed or

replicated among different points in a network.

P a g e 57 | 74
Cloud Database:

A cloud database is a database that typically runs on a cloud computing platform.

Database service provides access to the database. Database services make the

underlying software-stack transparent to the user.

Structured Query Language (SQL)

Structured Query Language is a standard Database language which is used to

create, maintain and retrieve the relational database. Following are some

interesting facts about SQL.

 SQL is case insensitive. But it is a recommended practice to use keywords

(like SELECT, UPDATE, CREATE, etc) in capital letters and use user defined

things (liked table name, column name, etc) in small letters.

 We can write comments in SQL using “–” (double hyphen) at the beginning of

any line.

 SQL is the programming language for relational databases (explained below)

like MySQL, Oracle, Sybase, SQL Server, Postgre, etc. Other non-relational

databases (also called NoSQL) databases like MongoDB, DynamoDB, etc do

not use SQL

 Although there is an ISO standard for SQL, most of the implementations

slightly vary in syntax. So we may encounter queries that work in SQL

Server but do not work in MySQL.

What is Relational Database?


Relational database means the data is stored as well as retrieved in the form of
relations (tables). Table 1 shows the relational database with only one relation
called STUDENT which stores ROLL_NO, NAME, ADDRESS, PHONE and AGE of
students.
STUDENT

ROLL_NO NAME ADDRESS PHONE AGE

P a g e 58 | 74
ROLL_NO
1 Bekele Adis Abeba 945512345 18
1
2 Chala Adis Abeba 9652431543 18
2
3 Kena Adama 9156253131 20
3
4 Kiya Adama 9156768971 18
4
 TABLE 1

These are some important terminologies that are used in terms of relation.

Attribute: Attributes are the properties that define a relation.

e.g.; ROLL_NO, NAME etc.

Tuple: Each row in the relation is known as tuple. The above relation contains 4

tuples, one of which is shown as:

1 RAM DELHI 9455123451 18

Degree: The number of attributes in the relation is known as degree of the

relation. The STUDENT relation defined above has degree 5.

Cardinality: The number of tuples in a relation is known as cardinality.

The STUDENT relation defined above has cardinality 4.

Column: Column represents the set of values for a particular attribute. The

column ROLL_NO is extracted from relation STUDENT.

P a g e 59 | 74
The queries to deal with relational database can be categories as:

Data Definition Language: It is used to define the structure of the database. e.g;

CREATE TABLE, ADD COLUMN, DROP COLUMN and so on.

Java Database Connectivity

There are 5 steps to connect any java application with the database using JDBC.

These steps are as follows:

 Register the Driver class

 Create connection

 Create statement

 Execute queries

 Close connection

1. Register the driver class


The forName() method of Class class is used to register the driver class. This method is used
the driver class.

Syntax of forName() method


public static void forName(String className)throws ClassNotFoundException

Example to register the OracleDriver class

Here, Java program is loading oracle driver to esteblish database connection.

1. Class.forName("oracle.jdbc.driver.OracleDriver");

P a g e 60 | 74
Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the d

Syntax of getConnection() method

1. public static Connection getConnection(String url)throws SQLException  
2. 2) public static Connection getConnection(String url,String name,String passwo
rd)  
3. throws SQLException 
Example to establish connection with the Oracle database
1. Connection con=DriverManager.getConnection(  
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object of s
responsible to execute queries with the database.

Syntax of createStatement() method

1. public Statement createStatement()throws SQLException  

Example to create the statement object

1. Statement stmt=con.createStatement();  

4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database. This
object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

1. public ResultSet executeQuery(String sql)throws SQLException  

P a g e 61 | 74
Example to execute query

1. ResultSet rs=stmt.executeQuery("select * from emp");  
2.   
3. while(rs.next()){  
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));  
5. }  

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close() meth
interface is used to close the connection.

Syntax of close() method

1. public void close()throws SQLException  

Example to close connection

1. con.close();  

Chapter seven

Servlet

P a g e 62 | 74
What are Servlets?

Java Servlets are programs that run on a Web or Application server and act as a

middle layer between a requests coming from a Web browser or other HTTP client

and databases or applications on the HTTP server.

Using Servlets, you can collect input from users through web page forms, present

records from a database or another source, and create web pages dynamically.

Java Servlets often serve the same purpose as programs implemented using the

Common Gateway Interface (CGI). But Servlets offer several advantages in

comparison with the CGI.

 Performance is significantly better.

 Servlets execute within the address space of a Web server. It is not

necessary to create a separate process to handle each client request.

 Servlets are platform-independent because they are written in Java.

 Java security manager on the server enforces a set of restrictions to

protect the resources on a server machine. So servlets are trusted.

 The full functionality of the Java class libraries is available to a servlet. It

can communicate with applets, databases, or other software via the sockets

and RMI mechanisms that you have seen already.

Servlets Architecture

P a g e 63 | 74
The following diagram shows the position of Servlets in a Web Application.

Servlets Tasks

Servlets perform the following major tasks −

 Read the explicit data sent by the clients (browsers). This includes an HTML

form on a Web page or it could also come from an applet or a custom HTTP

client program.

 Read the implicit HTTP request data sent by the clients (browsers). This

includes cookies, media types and compression schemes the browser

understands, and so forth.

 Process the data and generate the results. This process may require talking

to a database, executing an RMI or CORBA call, invoking a Web service, or

computing the response directly.

 Send the explicit data (i.e., the document) to the clients (browsers). This

document can be sent in a variety of formats, including text (HTML or XML),

binary (GIF images), Excel, etc.

 Send the implicit HTTP response to the clients (browsers). This includes

telling the browsers or other clients what type of document is being

P a g e 64 | 74
returned (e.g., HTML), setting cookies and caching parameters, and other

such tasks.

Servlets Packages

Java Servlets are Java classes run by a web server that has an interpreter that

supports the Java Servlet specification.

Servlets can be created using the javax.servlet and javax.servlet.http packages,

which are a standard part of the Java's enterprise edition, an expanded version of

the Java class library that supports large-scale development projects.

These classes implement the Java Servlet and JSP specifications. At the time of

writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.

Java servlets have been created and compiled just like any other Java class. After

you install the servlet packages and add them to your computer's Classpath, you

can compile servlets with the JDK's Java compiler or any other current compiler.

HTTP Requests

The request sent by the computer to a web server, contains all sorts of potentially

interesting information; it is known as HTTP requests.

The HTTP client sends the request to the server in the form of request message

which includes following information:

o The Request-line

o The analysis of source IP address, proxy and port

o The analysis of destination IP address, protocol, port and host

o The Requested URI (Uniform Resource Identifier)

o The Request method and Content

o The User-Agent header

o The Connection control header

P a g e 65 | 74
o The Cache control header

The HTTP request method indicates the method to be performed on the resource

identified by the Requested URI (Uniform Resource Identifier). This method is

case-sensitive and should be used in uppercase.

The HTTP request methods are:

HTTP Description

Request

GET Asks to get the resource at the requested URL.

POST Asks the server to accept the body info attached. It is like GET request with

with the request.

HEAD Asks for only the header part of whatever a GET would return. Just like GET b

TRACE Asks for the loopback of the request message, for testing or troubleshooting.

PUT Says to put the enclosed info (the body) at the requested URL.

DELETE Says to delete the resource at the requested URL.

OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can
Handling HTTP GET Requests

HTML forms provide a user interface to collect data from the user and submit the

data to a servlet or other server-side program for processing.

For example look at the following form that shows a simple form with two text

fields:

P a g e 66 | 74
HTML code for the above form is:

<html>
<head>
<title>Add Two numbers</title>
</head>
<body>
<h3>Add Two Numbers</h3>
<form action='add'>
<p>Enter First Number: <input type="text"
name='first'></p>
<p>Enter Second Number: <input type="text"
name='second'></p>
<p><input type='submit' value='submit'></p>
</form>
</body>
</html>

In above code observe the line <form action = 'add'>. The action attribute defines

where the data gets sent. On submitting this form, form-data will be sent to a

servlet whose url is mapped with it. Also note that one text field has a name of

first and the other has a name of second.

Now, suppose that we enter 10 in the first textfield and 15 in the second

textfield, and click the "Submit" button, we will get a "404 page not found" error

(because we have yet to write the servlet). BUT observe the destination URL:

P a g e 67 | 74
http://localhost:8080/chapter2/add?first=10&second=15

Observe that:

 The URL http://localhost:8080/chapter2/add is retrieved from the


attribute action="add" of the <form> start-tag.
 A '?' follows the URL, which separates the URL and called query
string.Notice the "query string" ?first=10&second=15. This part contains two
parameters with parameter values:

first=10
second=15
You can access these parameters from the HttpRequest object using
getParameter method as shown in following code:

String a = request.getParameter("first");
String b = request.getParameter("second");

Writing a Servlet to Process Form Data

When user submits an HTML form that does not specify method parameter for the

form tag or explicitly specifies the GET method, the doGet() method is invoked. To

process HTTP GET requests that are sent to the servlet, override the doGet( )

method.

Look at the following servlet code:

package testPackage;

P a g e 68 | 74
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

@WebServlet("/add")
public class AddNumber extends HttpServlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String a = request.getParameter("first");
String b = request.getParameter("second");

int sum = Integer.parseInt(a) + Integer.parseInt(b);

response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println("<html><head><title>Add</title></head><body>");

out.println("<p>The sum of " + a + " and " + b


+ " is " + sum + ".</p>");

out.println("</body></html>");
}
}

Now start the server and open HTML form in the browser, type data in textfields
for example 50 and 14 and click on submit button. The form-data will be sent to
the servelet and output will look like this:

Checking null or empty string

P a g e 69 | 74
It might be possible that user does not supply data in text fields and click on
submit button or user enters an empty string " ". In this case, our servlet
should open HTML form again. We can do this by the following code:

if( a == null || a.trim().length() == 0 || b == null


|| b.trim().length() == 0 )
{
response.sendRedirect( "addform.html" );
return;
}

The sendRedirect() method transfers control and open the URL specified. Now
here is the complete program after adding validation codes:

package testPackage;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

@WebServlet("/add")
public class AddNumber extends HttpServlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String a = request.getParameter("first");
String b = request.getParameter("second");
if( a == null || a.trim().length() == 0 || b == null
|| b.trim().length() == 0 )
{
response.sendRedirect( "addform.html" );
return;
}

int sum = Integer.parseInt(a) + Integer.parseInt(b);

response.setContentType("text/html");
PrintWriter out = response.getWriter();

P a g e 70 | 74
out.println("<html><head><title>Add</title></head><body>");

out.println("<p>The sum of " + a + " and " + b


+ " is " + sum + ".</p>");

out.println("</body></html>");
}
}

Handling HTTP POST Requests


In previous sections, we have seen servlets handle get request by overriding
doGet method. The browser generates GET request :

 when the user enters a URL on the address line


 follows a link from a webpage
 submits an HTML form that does not specifie method parameter for the
form tag or explicitly specifies the GET method.
You've also seen that the query string is sent in the URL of a GET request.

If you need to send a password (or any sensitive piece of data), never
use the GET method or you risk displaying it in the URL bar.
IF you can send data using POST request by explicitly specifying method
parameter for the form tag like this :

<form method="POST" action="">

 Query string will not be dispalyed on URL bar with a POST request.


 If a form is sent using POST method, the data is appended to the body of
the HTTP request.
 If you need to send a large amount of data, the POST method is preferred
because some browsers limit the sizes of URLs. In addition, many servers
limit the length of URLs they accept.
In the following example, we will create a html form that will sent data to
servlet with POST request.

P a g e 71 | 74
Html code of above form is:

<html>
<head>
<title>User Entry Form</title>
</head>
<body>
<form method="post" action="entry">
<h3>User Entry Form</h3>
<p>
Username: <input type="text" name="username"> <br><br>
Password: <input type="password" name="user-password"> <br><br>

Gender: <input type="radio" name="sex" value="male">Male


<input type="radio" name="sex" value="female"> Female <br><br>

Hobbies:
<input type="checkbox" name="soccer"> Soccer
<input type="checkbox" name="cricket"> Cricket
<input type="checkbox" name="baseball"> Baseball<br><br>

Address: <textarea rows="3" cols="30"></textarea><br><br>

Select Your City:

P a g e 72 | 74
<select name="city">
<option value="sydney">Sydney</option>
<option value="melbourne">Melbourne</option>
<option value="cromwell">Cromwell</option>
</select><br><br>

<input type="submit" value="Submit">


<input type="reset" value="Reset">
</p>
</form>
</body>
</html>

Form data is sent using METHOD="POST" request. To handle post requst we


override the doPost method in servlet.

package com.beginwithjava.servlet;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

@WebServlet("/entry")
public class EntryForm extends HttpServlet
{
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Add</title></head><body>");

out.println("<p>Username: "
+ request.getParameter("username") + "</p>");
out.println("<p>Password: "
+ request.getParameter("user-password")
+ "</p>");
out.println("<p>Gender: "
+ request.getParameter("sex") + "</p>");

P a g e 73 | 74
out.println("<p>Hobbies:</p>");
String[] sports = request
.getParameterValues("sports");
out.println("<ul>");
for (String sport : sports)
{
out.println("<li>" + sport + "</li>");
}
out.println("</ul>");

out.println("<p>Address: "
+ request.getParameter("address") + "</p>");
out.println("<p>City: "
+ request.getParameter("city") + "</p>");
out.println("</body></html>");
}
}

Notice that no query string is displayed on address bar.

P a g e 74 | 74

You might also like