You are on page 1of 44

Course Module on Advanced Programming

DEBRE TABOR UNIVERSITY

Faculty of Technology
Department of computer science
Course Module on Advanced programming

Debre Tabor

1|Page
Course Module on Advanced Programming

Course Description
This course covers topics on Java which includes: AWT and Swing, I/O Streams, Multithreading,
Network Programming, Java database connectivity (JDBC), RMI, and Introduction to Servlets. To
cover this content, we will use the active learning/student centered method of teaching will
practice and the progress of the students will be assessed by both formative and Summative way
of evaluation. Hence active learning/student cantered method of teaching has been practiced and
the progress of the students is assessed by both formative and Summative way of evaluation.
Learning outcomes: At the end of the course, students will be able to: -
1. Define AWT and Swing Components K, L1
2. Identify components of AWT and SWING K, L1
3. Carry out design and development of complex elements, such as user interfaces, multiprocessing, and fault-
tolerant components; S, L3
4. Clearly understand File A, L3
5. Clearly understand thread and process A, L3
6. Develop web app using java S, L3
7. Write TCP/IP Client Server application using Sockets in java

Note: - The objectives, contents, methods, and assessment of the course are aligned with the
hierarchy of learning and domains of education as follows.
 Domain of education
 Knowledge (k)  Attitude
(A)
 Skill (S)
 Hierarchy of learning – simple to complex 1. Cognitive
Domain (Knowledge-K):
Level 1 (knowledge): define, describe, label, list ….
Level 2 (comprehension): convert, defend distinguish, estimate, explain … Level 3
(application): change, compute, demonstrate …
Level 4 (analysis): break down, relate, infer …. Level 5
(synthesis): compose, create …
Level 6 (evaluate): appraise, conclude … 2.
Affective Domain (Attitude-A):
Level 1 (receiving): Asks, describes …
Level 2 (responding): Answer, assist, complies …
Level 3 (valuing): completes, describes, differentiates … Level 4
(organization): Adheres, alters, arranges, identifies … Level 5
(characterization): Acts, discriminates, displays ….
3. Psychomotor Domain (Skill-S):
Level 1 (perception): choose, describes, detects Level 2
(set): begins, displays, explains
Level 3 (guided Response): Assembles, builds, calibrated

2|Page
Course Module on Advanced Programming

UNIT ONE:
1. AWT AND SWING
Unit description:
This unit deals with the general descriptions of java AWT and Swing components, the general
difference between AWT and Swing components and how to create applications in java using GUI
(graphical user interface). These contents will be delivered to the students through brain
storming, group discussion, observation/demonstration, and mini lecture. And students assessed
with lab exercise, group work and individual lab assignment.
Objectives: At the end of this unit, the students will be able to:
 Define AWT and Swing K L,1
 Identify components of AWT and SWING A L,1
 Distinguish the difference between AWT and Swing Components K L,2
 Define event listeners and handlers’ K L,1
 Construct a certain java application using AWT and SWING components A L,4
 Contents:
1.1 Definition and concept of AWT and SWING
1.2 Difference between AWT and SWING
1.3 Components of AWT and SWING
1.4 Event handlers and listeners
Method of teaching: Brain storming, gap lecture, group discussion

Introduction:
Brain storming: What are the Objects or class you know so far in java?
1.1 AWT and SWING
Abstract Windows Toolkit (AWT) is JAVA’s original platform dependent windowing, graphics, and user-
interface widget toolkit preceding swing. The AWT is part of Java Foundation Classes (JFC)- the standard
API for providing a graphical user interface (GUI) for java program.

Swing API is a set of extensible GUI Components to ease the developer's life to create JAVA based Front
End/GUI Applications. It is also part of Java Foundation Classes. It is built on top of AWT API and acts as a
replacement of AWT API, since it has almost every control corresponding to AWT controls.

Swing Features

Light Weight- Swing components are independent of native Operating System's API as
Swing API controls are rendered mostly using pure JAVA code instead of underlying
operating system calls.
Rich Control- Swing provides a rich set of advanced controls like Tree, TabbedPane, slider,
colorpicker, and table controls.
Highly Customizable - Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
Pluggable look-and-feel - SWING based GUI Application look and feel can be changed at
run-time, based on available values.

3|Page
Course Module on Advanced Programming

1.2 Difference between AWT and Swing components


Since swing components are built on the top of AWT components they provide much
functionality than the awt components. The swing components have all the functionality of the
awt components in addition to their own new and powerful functionalities. Since the main
feather of java is platform independent swing components are platform independent. Some of
the main differences between swing and awt are listed in the bellow table.

AWT Swing
AWT components are called heavyweight Swing components are called light weight
components components because these components sit on
the top of AWT components and do their
work
AWT components are platform dependent Swing components are made in purely in java
and they are platform independent
AWT components require java.awt package Swing components require java. swing
package
There are no different look and feel in AWT There are different look and feel in Swing
AWT is a thin layer of code on top of the OS Swing is much larger and has very much richer
functionality
Swing has many advanced features such as
JTabel, JTabbedPane ……

1.2 Components of AWT and Swing


Every user interface considers the following three main aspects:

UI Elements: These are the core visual elements the user eventually sees and interacts with. GWT
provides a huge list of widely used and common elements varying from basic to complex, which we will
cover in this tutorial.

Layouts: They define how UI elements should be organized on the screen and provide a final look and feel
to the GUI (Graphical User Interface).

Behavior: These are the events which occur when the user interacts with UI elements. This part will be
covered in the Event Handling chapter.

Every SWING controls inherits properties from the following Component class hierarchy.

Component: A Component is the abstract base class for the non-menu user-interface controls of SWING.
Component represents an object with graphical representation
Container: A Container is a component that can contain other SWING components.
JComponent: A JComponent is a base class for all SWING UI components. In order to use a SWING
component that inherits from JComponent, the component must be in a containment hierarchy whose
root is a top-level SWING container
4|Page
Course Module on Advanced Programming

1.2.1 Containers
Containers are an integral part of SWING GUI components. A container provides a space where a
component can be located. A Container in AWT is a component itself and it provides the capability to add
a component to itself. Following are certain noticeable points to be considered.
Sub classes of Container are called as Container. For example, JPanel, JFrame and JWindow.
Container can add only a Component to itself.
A default layout is present in each container which can be overridden using setLayout method.
Following is the list of commonly used containers while designed GUI using SWING.

Container Name Container description

JFrame A JFrame is a top-level window with a title and a border.


JPanel JPanel is the simplest container. It provides space in which any other
component can be placed, including other panels.
A JWindow object is a top-level window with no borders and no menu
JWindow
bar.
JFrame
Each program that uses Swing components has at least one top-level container, which is the root of the
containment hierarchy. As a rule, a standalone application with a Swing-based GUI has at least one
containment hierarchy with a JFrame as its root. When we are dealing with JFrame it’s a common way to
create your own class that extends JFrame and do your task inside the constructor of your class.
Class Constructors
Sr.No. Constructor & Description

1 JFrame ()
Constructs a new frame that is initially invisible.
JFrame (GraphicsConfiguration gc)
2 Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank
title.
JFrame (String title)
3
Creates a new, initially invisible Frame with the specified title.
JFrame (String title, GraphicsConfiguration gc)
4 Creates a new JFrame with the specified title GraphicsConfiguration of a screen device.

This class inherits methods from the following classes:


java.awt. Frame
java.awt. Window
java.awt. Container
java.awt. Component
java.lang. Object
5|Page
Course Module on Advanced Programming

Commonly used JFrame class methods


Sr.No. Constructor & Description

1 void setVisible (Boolean visible)


sets the visibility of the frame. By default, its false means it’s not visible
void setLayout (LayoutManager manager)
2
Sets the LayoutManager. By default, layout of JFrame is Flow Layout
void setDefaultCloseOperation (int operation)
3
Sets the operation that will happen by default when the user initiates a "close" on this frame.
void add (Component comp)
4
Adds the specified component to the frame
void remove (Component comp)
5
Removes the specified component from the container.
void removeAll ()
6
Removes every component from the container.
void setJMenuBar (JMenuBar menubar)
7
Sets the menubar for this frame.
void setAlwaysOnTop (Boolean top)
8
sets whether the frame should be displayed always on top of other applications frame
void setTitle (String title)
9
Sets the title of the frame
String getTitle ()
10
Returns the title of the frame

Example 1. The following java program creates and displays JFrame to the user.

import javax.swing.JFrame;//this is a must in order to use JFrame class


class MyFrame extends JFrame{
public MyFrame()//default constructor
{
setSize (500, 500);//set the size of the frame
setVisible(true);
//this will display the frame or make it visible
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//When the close button is clicked close the frame
}
}
public class JFrameDemo extends JFrame{
public static void main(String[] args){
MyFrame frame=new MyFrame();
//creates object of our MyFrame class
}
}

6|Page
Course Module on Advanced Programming

JPanel
Panels are implemented as objects of the JPanel class. Each JPanel object has a layout manager, which
you can specify either when you construct the panel or by calling its setLayout method. By creating several
panels with different layout managers, you can control how different groups of components will be laid
out. You can then add these panels to the overall frame so that they will appear on the screen. So, the
main advantage of JPanel is to group multiple components together.

Example 2. The following java program create and adds the JPanel component into JFrame.

import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
class MyFrame extends JFrame
{
JPanel jPanel;// declaration for JPanel object
public MyFrame()
{
jPanel=new JPanel();// create JPanel object
jPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
//setting a border line to the JPanel object so that
//it will be differentiable from the JFrame
add(jPanel);// adding the JPanel to the frame
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class JFrameDemo extends JFrame
{
public static void main(String[] args)
{
MyFrame frame=new MyFrame();
}
}

7|Page
Course Module on Advanced Programming

1.2.2 Controls
Components are the basic building block of an application. Swing and AWT have a wide range of various
components or controls including buttons, check boxes, sliders and list boxes. The following table shows
the basic controls of swing.

Following is the list of commonly used controls while designing GUI using SWING.

Control Name Control Description


JLabel A JLabel object is a component for placing text in a container.
JButton This class creates a labeled button.
JColorChooser A JColorChooser provides a pane of controls designed to allow a user to
manipulate and select a color.

JCheckBox A JCheckBox is a graphical component that can be in either an on(true) or off


(false) state.
JRadioButton The JRadioButton class is a graphical component that can be in either an on
(true) or off (false) state. in a group.
JList A JList component presents the user with a scrolling list of text items.
JComboBox A JComboBox component presents the user with a to show up menu of
choices.
JTextField A JTextField object is a text component that allows editing of a single line of
text.
JPasswordField A JPasswordField object is a text component specialized for password entry.
JTextArea A JTextArea object is a text component that allows editing of a multiple lines of
text.
JScrollbar A Scrollbar control represents a scroll bar component in order to enable the
user to select from a range of values.
JOptionPane JOptionPane provides a set of standard dialog boxes that prompt the users for
a value or informs them of something.
JFileChooser A JFileChooser control represents a dialog window from which the user can
select a file.
JProgressBar As the task progresses towards completion, the progress bar displays the task's
percentage of completion.
1.2.3 Layout Managers
When building a GUI, each GUI component must be attached to a container, such as a window created
with a JFrame. We typically must decide where to position each GUI component. This is known as
specifying the layout of the GUI components. Java provides several layout managers that can help us
position components. Method setLayout is used and is inherited from Container. The argument to the
method must be an object of a class that implements the LayoutManager interface

The layout manager automatically positions all the components within the container. Even if you do not
use the layout manager, the components are still positioned by the default layout manager. It is possible
to lay out the controls by hand, however, it becomes very difficult because it becomes tedious to handle

8|Page
Course Module on Advanced Programming

a large number of controls within the container. Usually, the width and height information of a component
is not given when we need to arrange them

Following is the list of commonly used control layout managers while designing GUI using AWT.

Sr. No. LayoutManager & Description

1 BorderLayout :The borderlayout arranges the components to fit in the five regions: east,
west, north, south, and center.
2 FlowLayout :The FlowLayout is the default layout. It lays out the components in a
directional flow.
3 GridLayout :The GridLayout manages the components in the form of a rectangular grid.
4 GridBagLayout :This is the most flexible layout manager class. The object of
GridBagLayout aligns the component vertically, horizontally, or along their baseline
without requiring the components of the same size.
5 GroupLayout :The GroupLayout hierarchically groups the components in order to
position them in a Container.
Example 6: Border and GridLayout managers
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class LayoutExamples
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Layout Examples");
frame.add(new JLabel("Label"), BorderLayout.EAST);
frame.add(new JButton("Button"), BorderLayout.NORTH);
frame.add(new JLabel("Label2"), BorderLayout.WEST);
frame.add(new JButton("Button2"), BorderLayout.SOUTH);
JPanel panel = new JPanel();
JButton b[] = new JButton[100];
for (int i = 0; i < 100; i++) {
b[i] = new JButton("Button " + i);
panel.add(b[i]);//adding every new button to the panel
}
panel.setLayout(new GridLayout(0, 10));
frame.add(panel, BorderLayout.CENTER);
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//GridLayout example it accepts row count and column count
//0 row count means unlimited number of rows
}
}
9|Page
Course Module on Advanced Programming

Example 3. The following java program shows how to create and display any kinds of controls to JFrame

import java.awt.GridLayout;
import javax.swing.*;
class MyFrame extends JFrame
{
JButton jButton;
JLabel jLabel;
JTextArea jTextArea;
JTextField jTextField;
JRadioButton jRadioButton;
JCheckBox jCheckBox;
public MyFrame()
{
jButton=new JButton("Am Button");
jLabel=new JLabel("Am Label");
jTextArea=new JTextArea("Text on text area");
jTextField=new JTextField("Text on text field");
jRadioButton=new JRadioButton("Am radio button");
jCheckBox=new JCheckBox("Am checkbox");
/* Creating the controls objects*/
add(jButton);
add(jLabel);
add(jTextArea);
add(jTextField);
add(jRadioButton);
add(jCheckBox);
/* adding each controls into the frame */
setLayout(new GridLayout(0,1));
/* setting the layout of the frame */
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class JFrameDemo extends JFrame
{
public static void main(String[] args)
{
MyFrame frame=new MyFrame();
}
}

10 | P a g e
Course Module on Advanced Programming

1.3 Event Handlers and Listeners


When the user interacts with a GUI component, the interaction—known as an event—drives the program
to perform a task. Some common events (user interactions) that might cause an application to perform
a task include clicking a button, typing in a text field, selecting an item from a menu, closing a window and
moving the mouse. The code that performs a task in response to an event is called an event handler and
the overall process of responding to events is known as event handling. Event handling can be
accomplished using two ways by using anonymous inner class and by creating event handler class that
implements the appropriate interface. Example 4 and 5 shows event handling using Anonymous Inner
class and inner class that implements the appropriate Event Listener interface respectively.

Steps Required to Set Up Event Handling for a GUI Component

Before an application can respond to an event for a particular GUI component, we must perform
several coding steps:
1. Create a class that represents the event handler.
2. Implement an appropriate interface, known as an event-listener interface, in the class from Step 1.
3. Indicate that an object of the class from Steps 1 and 2 should be notified when the event
occurs. This is known as registering the event handler.
Non-static nested classes are called inner classes and are frequently used for event handling.
When the user presses Enter in a JTextField or JPasswordField, the GUI component generates an
ActionEvent (package java.awt.event).
Such an event is processed by an object that implements the interface ActionListener (package
java.awt.event).
Every control should be registered in order to generate event for the control.
Example 4. The following java program creates and simple program that can add two numbers

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class MyFrame extends JFrame
{
JTextField field1;
JTextField field2;
JLabel answer;
JButton addButton;
public MyFrame(){
add=new JButton("Add");
field1=new JTextField();
field2=new JTextField();
answer=new JLabel("Answer=");
add(field1);
add(field2);
add(answer);
add(addButton);

11 | P a g e
Course Module on Advanced Programming

//The bellow code will register the addButton object to


//action listener event using Anonymous Inner class
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
actionEventPerformed();
//this function will be called when Click event is
//generated by the user
}
});
field2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
actionEventPerformed();
/*this function will be called when the user presses
Enter key from the field2 control since field2 is
JTextField the default event will be entering key*/
}
});
setLayout(new GridLayout(0,1));
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void actionEventPerformed()
{
try
{
double num1 = Integer.parseInt(field1.getText());
double num2 = Integer.parseInt(field2.getText());
double sum = num1 + num2;
answer.setText("Answer=" + sum);
}
catch (NumberFormatException exception)
{
System.out.println(exception.getMessage());
}
}
}
public class JFrameDemo extends JFrame
{
public static void main(String[] args)
{
MyFrame frame=new MyFrame();
}
}

12 | P a g e
Course Module on Advanced Programming

Example 5. The following java program displays a message when the button is clicked by user

import java.awt.GridLayout;
import java.awt.event.*;// this import is required to deal with events
import javax.swing.*;
class MyFrame extends JFrame{
JButton button;
public MyFrame(){
button=new JButton("Add");
add(button);
button.addActionListener(new AddButtnEventHandler());
setLayout(new GridLayout(0,1));
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class AddButtnEventHandler implements ActionListener{
@Override
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(MyFrame.this, "Hello");
}
}
}
public class JFrameDemo extends JFrame{
public static void main(String[] args){
MyFrame frame=new MyFrame();
}
}
Following is the list of commonly used Event classes.

No Event Class Name


1 KeyEvent
On entering the character, the Key event is generated.
2 MouseEvent
This event indicates a mouse action occurred in a component.
3 WindowEvent
The object of this class represents the change in the state of a window.
4 AWTEvent It is the root event class for all SWING events. This class and its subclasses
replace the original java.awt.Event class.
5 ComponentEvent
The object of this class represents the change in the state of a window.
6 ContainerEvent
The object of this class represents the change in the state of a window.
7 MouseMotionEvent
The object of this class represents the change in the state of a window.

13 | P a g e
Course Module on Advanced Programming

UNIT TWO:
2. Streams and Files (I/O)
Unit description:
This unit deals with the general descriptions of files and streams in java, the various stream and
file classes and objects found in java and define file management briefly and clearly. These
contents will be delivered to the students through brain storming, group discussion,
observation/demonstration, and interactive lecture. And students assessed with lab exercise,
group work and individual lab assignment.
Objectives: At the end of this unit, the students will be able to:
 Define streams and files K L,1
 Identify the common stream classes A L,1
 Define file management and ways of file management K L,1
 Construct a certain java application using files and stream concepts A L,4
 Contents:
2.1 Define streams and files
2.2 Identify stream object
2.3 Define file management
Method of teaching: Brain storming, interactive lecture, group discussion

Introduction:
Brain storming: What are files and streams from your C++ knowledge
2.1 Streams and Files
A file is a collection of related records placed in a particular area on the disk. A record is composed of
several fields and a field is a group of characters. Characters in java are Unicode characters composed of
two bytes, each byte containing eight binary digits, 1 or 0. Storing and managing data using files is known
as file processing which includes tasks such as creating files, updating files and manipulation of data.

A stream in java is a path along which data flows (like a rive or a pipe along which water flows). It has a
source of data and a destination for that data. Both the source and the destination may be physical devices
or programs or other streams in the same programs. A stream also can be defined as a sequence of data.
There are two kinds of Streams:

 InPutStream: The InPutStream is used to read data from a source.


 OutPutStream: The OutPutStream is used for writing data to a destination.

14 | P a g e
Course Module on Advanced Programming

2.2 Streams objects and classes


As described earlier, a stream can be defined as a sequence of data. The InputStream is used to read data
from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

The two important streams are FileInputStream and FileOutputStream, which would be discussed in this
chapter.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the keyword new and
there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file:
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First, we create
a file object using File () method as follows:
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be used to
read to stream or to do other operations on the stream.

15 | P a g e
Course Module on Advanced Programming

List of commonly used methods found in InputStream

Sr. No. Methods with Description


1 public void close () throws IOException {}
This method closes the file output stream. Releases any system resources associated with
the file. Throws an IOException.
protected void finalize () throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this file
2
output stream is called when there are no more references to this stream. Throws an
IOException.
public int read (int r) throws IOException {}
3 This method reads the specified byte of data from the InputStream. Returns an int. Returns
the next byte of data and -1 will be returned if it's the end of the file.
public int read (byte [] r) throws IOException {}
4 This method reads r. length bytes from the input stream into an array. Returns the total
number of bytes read. If it is the end of the file, -1 will be returned.
public int available () throws IOException {}
5 Gives the number of bytes that can be read from this file input stream. Returns an
int.

DataInputStream
Following is the constructor to create an InputStream:
InputStream in = DataInputStream (InputStream in);
Once you have DataInputStream object in hand, then there is a list of helper methods, which can be
used to read the stream or to do other operations on the stream.
Sr. No. Methods with Description
1 public final int read (byte [] r, int off, int len)throws IOException Reads up to len bytes of data
from the input stream into an array of bytes. Returns the total number of bytes read into the
buffer otherwise -1 if it is end of file.
public final int read (byte [] b) throws IOException
2 Reads some bytes from the InputStream and stores in to the byte array. Returns the total
number of bytes read into the buffer otherwise -1 if it is end of file.
(a) public final Boolean readBooolean () throws IOException
(b) public final byte readByte () throws IOException
(c) public final short readShort () throws IOException
3
(d) (d) public final Int readInt () throws IOException
These methods will read the bytes from the contained InputStream. Returns the next two bytes
of the InputStream as the specific primitive type.
public String readLine () throws IOException
Reads the next line of text from the input stream. It reads successive bytes, converting each
4
byte separately into a character, until it encounters a line terminator or end of file; the
characters read are then returned as a String.

16 | P a g e
Course Module on Advanced Programming

Example 6: Following is an example to demonstrate DataInputStream and DataOutputStream. This


example reads 5 lines given in a file test.txt and converts those lines into capital letters and finally copies
them into another file test1.txt.

import java.io. *;
public class FilesInJava
{
public static void main (String args []) throws IOException
{
//writing string to a file encoded as modified UTF-8
DataOutputStream dataOut=new DataOutputStream (new FileOutputStream(“E:\\file.txt”));
dataOut.writeUTF("hello");
//Reading data from the same file
DataInputStream dataIn = new DataInputStream (new FileInputStream("E:\\file.txt"));
while (dataIn.available() > 0)
{
String k = dataIn.readUTF();
System.out.println(k + " ");
}
}
}

FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't
already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the file:
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file. First, we create
a file object using File () method as follows:
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can be used to
write to stream or to do other operations on the stream.
Sr. Methods with Description
No.
1 public void close () throws IOException {}: This method closes the file output stream. Releases any
system resources associated with the file. Throws an IOException.
protected void finalize () throws IOException {}: This method cleans up the connection to the file.
2 Ensures that the close method of this file output stream is called when there are no more references to
this stream. Throws an IOException.
public void write (int w) throws IOException {}: This method writes the specified byte to the output
3
stream.
4 public void write (byte [] w): Writes w. length bytes from the mentioned byte array to the OutputStream.

17 | P a g e
Course Module on Advanced Programming

The DataOutputStream stream lets you write the primitives to an output source. Following is the
constructor to create a DataOutputStream.
DataOutputStream out = DataOutputStream (OutputStream out);
Once you have DataOutputStream object in hand, then there is a list of helper methods, which can be
used to write the stream or to do other operations on the stream.
Sr. No. Methods with Description
1 public final void write (byte [] w, int off, int len) throws IOException: Writes len bytes from the
specified byte array starting at point off, to the underlying stream.
Public final int write (byte [] b) throws IOException: Writes the current number of bytes written to
2
this data output stream. Returns the total number of bytes written into the buffer.
(a) public final void writeBooolean () throws IOException,
(b) public final void writeByte () throws IOException,
3 (c) public final void writeShort () throws IOException
(d) (d) public final void writeInt () throws IOException
These methods will write the specific primitive type data into the output stream as bytes.
4 Public void flush () throws IOException Flushes the data output stream.
public final void writeBytes (String s) throws IOException: Writes out the string to the underlying
5 output stream as a sequence of bytes. Each character in the string is written out, in sequence, by
discarding its high eight bits.

Example 7: Following is the example to demonstrate InputStream and OutputStream:

import java.io.*;
public class FilesInJava
{
public static void main(String args[])
{
try
{
byte bWrite[] = {11, 21, 3, 40, 5};
OutputStream os = new FileOutputStream("test.txt");
for (int x = 0; x < bWrite.length; x++)
{
os.write(bWrite[x]); // writes the bytes
}
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for (int i = 0; i < size; i++)
{
System.out.println((char) is.read() + " ");
}
is.close();
}
catch (IOException e) {
System.out.println("Exception");
}
}
}

18 | P a g e
Course Module on Advanced Programming

2.3 File management

File handling has always seemed a little more difficult in Java than in many other programming languages.
Java SE 7 certainly improves Java's file handling capabilities dramatically with NIO.2, but not every project
can make use of Java SE 7. For those projects, not able to use Java SE 7, Guava's Files class is a nice
intermediate solution for easier file handling. It is important to note here that Java SE 7 introduces a Files
class of its own, so any use of Guava's Files class in Java SE 7 must be fully scoped if the Java version of
Files is used in the same code. For now we are going to see how to create
Creating Directories: There are two useful File utility methods, which can be used to create directories:
The mkdir () method creates a directory, returning true on success and false on failure. Failure
indicates that the path specified in the File object already exists, or that the directory cannot be
created because the entire path does not exist yet.
The mkdirs () method creates both a directory and all the parents of the directory.

Example 7: Following example creates "/tmp/user/java/bin" directory:

import java.io.File;
public class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
d.mkdirs();
d.delete();//if you need to delete a specific directory you can use this
}
}

Listing Directories: You can use list () method provided by File object to list down all the files and
directories available in a directory as follows:
Example 7: Following example shows how to list all the directories in a specific folder
import java.io.File;
public class ReadDir {
public static void main(String[] args) {
File file = null;
String[] paths;
try {
// create new file object
file = new File("/tmp");
// array of files and directory
paths = file.list();
// for each name in the path array
for (String path : paths) {
// prints filename and directory name
System.out.println(path);
}
} catch (Exception e) {
System.out.println("Error "+e.getMessage());
}
}
}

19 | P a g e
Course Module on Advanced Programming

UNIT THREE:
3. Multithreading
Unit description:
This unit deals with the general descriptions of threads and processes in java, thread priorities and scheduling. These
contents will be delivered to the students through brain storming, group discussion, observation/demonstration,
and mini lecture. And students assessed with lab exercise, group work and individual lab assignment.
Objectives: At the end of this unit, the students will be able to:
Define threads and processes K L,1
Define multithreading and thread priorities K L,1
Differentiate b/n synchronization and un synchronization in thread K L,1
Construct a certain java application using threads A L,4
 Contents:
3.1
Define Multithreading and processes
3.2
Handling Multithreading in java
3.3
Thread priorities and scheduling
3.4
Synchronizations and un synchronization in threads
Method of teaching: Brain storming, mini lecture, group discussion, lab work

Introduction:
Brain storming: What are processes and what does it mean by scheduling?
3.1Multithreading and processes
Java is a multi-threaded programming language which means we can develop multithreaded program using Java. A
multi-threaded program contains two or more parts that can run concurrently and each part can handle a different
task at the same time making optimal use of the available resources specially when your computer has multiple
CPUs. By definition, multitasking is when multiple processes share common processing resources such as a CPU.
Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations
within a single application into individual threads. Each of the threads can run in parallel. Multithreading allows you
to do multiple tasks at the same time.

A process is a program at execution including the current values of program counter, registers and variables
processes have their own resources. Threads are also called light weight process a single process could have a
multiple thread which are sharing the same resources but they are being executed individually one another. Threads
are called light weight processes because the doesn’t have their own resource since they share the processes
recourse. A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then
dies. The following diagram shows the complete life cycle of a thread.

20 | P a g e
Course Module on Advanced Programming

3.2 Multithreading in java


If your class is intended to be executed as a thread, then you can achieve this in two ways first
implementing a Runnable interface and second by extending a thread class we are going to see both ways
in this chapter step by step.

Create a Thread by Implementing a Runnable Interface


You will need to follow three basic steps:

Step 1: As a first step, you need to implement a run () method provided by a Runnable interface. This
method provides an entry point for the thread and you will put your complete business logic inside this
method. Following is a simple syntax of the run () method:
public void run ()
Step 2: As a second step, you will instantiate a Thread object using the following constructor:
Thread (Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and threadName is
the name given to the new thread.
Step 3: Once a Thread object is created, you can start it by calling start () method, which executes a call
to run () method. Following is a simple syntax of start () method:
void start ();
Example 8: Following is the example to demonstrate threads using runnable interface

class MyThread implements Runnable


{
String threadName;
public MyThread (String threadName) {
this.threadName = threadName;
System.out.println("Thread created");
}
@Override
public void run () {
for (int i = 0; i < 10; i++) {
System.out.println(threadName + i);
try {
Thread.sleep (1000);
}
catch (InterruptedException ex) {
System.out.println("Error "+ex.getMessage());
}
}
}
}
public class JavaThread {
public static void main (String [] args) {
Thread t = new Thread (new MyThread ("Thread one"));
t.start ();
Thread t2 = new Thread (new MyThread ("Thread two"));
t2.start ();
}
}

21 | P a g e
Course Module on Advanced Programming

Create a Thread by Extending a Thread Class

The second way to create a thread is to create a new class that extends Thread class using the following
two simple steps. This approach provides more flexibility in handling multiple threads created using
available methods in Thread class.
Step 1: You will need to override run () method available in Thread class. This method provides an entry
point for the thread and you will put your complete business logic inside this method. Following is a simple
syntax of run () method:
public void run ()
Step 2: Once Thread object is created, you can start it by calling start () method, which executes a call to
run () method. Following is a simple syntax of start () method:
void start ();

Example 9: Following is the example to demonstrate threads using Thread class

class MyThread extends Thread


{
String threadName;
public MyThread (String threadName) {
this.threadName = threadName;
System.out.println("Thread created");
}
@Override
public void run()
{
for (int i = 0; i < 10; i++)
{
System.out.println(threadName + i);
try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
System.out.println("Error "+ex.getMessage());
}
}
}
}
public class JavaThread
{
public static void main(String[] args) {
MyThread myThread1=new MyThread("Thread one");
myThread1.start();
MyThread myThread2=new MyThread("Thread two");
myThread2.start();
}
}

22 | P a g e
Course Module on Advanced Programming

3.3 Thread priorities


Every Java thread has a priority that helps the operating system determine the order in which threads are
scheduled. Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant
of 5). Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads. However, thread priorities cannot guarantee the order in which
threads execute and are very much platform dependent. We can set the priorities of threads using
setPriority () method.

public final void setPriority (int i)


The above tables show the structure of setPriority method. The following example shows how to set a
priority of thread.

myThread2.setPriority(Thread.MIN_PRIORITY);
myThread2.setPriority(Thread.NORM_PRIORITY);
myThread2.setPriority(Thread.MAX_PRIORITY);

3.4 Synchronized and Unsynchronized threads


When we start two or more threads within a program, there may be a situation when multiple threads try
to access the same resource and finally they can produce unforeseen result due to concurrency issues.
For example, if multiple threads try to write within a same file then they may corrupt the data because
one of the threads can override data or while one thread is opening the same file at the same time another
thread might be closing the same file.

So, there is a need to synchronize the action of multiple threads and make sure that only one thread can
access the resource at a given point in time. This is implemented using a concept called monitors. Each
object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time
may hold a lock on a monitor.

Java programming language provides a very handy way of creating threads and synchronizing their task
by using synchronized blocks. You keep shared resources within this block. Following is the general form
of the synchronized statement:

synchronized(objectidentifier) {
// Access shared variables and other shared resources
}

Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the
synchronized statement represents.

23 | P a g e
Course Module on Advanced Programming

UNIT FOUR:
4. Networking in java
Unit description:
This unit deals with the general descriptions networking and socket programming in java, URL manipulation,
differentiate between server, port, URL and socket. These contents will be delivered to the students through brain
storming, group discussion, observation/demonstration, and mini lecture. And students assessed with lab exercise,
group work and individual lab assignment.
Objectives: At the end of this unit, the students will be able to:
Define networking and socket programming in java K L,1
Differentiate b/n server and client K L,1
Construct a certain java application using socket programming A L,4
 Contents:
4.1 Define Networking in java
4.2 URL manipulation
4.3 Socket, Port, ServerSocket Client and server in java
Method of teaching: Brain storming, mini lecture, group discussion, lab work

Introduction:
Brain storming: What do you know about networking, server, client?
4.1 Networking and Socket programming
This chapter presents key concepts of intercommunication between programs running on different
computers in the network. It introduces elements of network programming and concepts involved in
creating network applications using sockets. The chapter introduces the java.net package containing
various classes required for creating sockets and message communication using two different protocols.
At a basic level, network-based systems consist of a server, client, and a media for communication. A
computer running a program that makes a request for services is called client machine. A computer
running a program that offers requested services from one or more clients is called server machine. The
media for communication can be wired or wireless network. Java has a huge library to perform networking
Tasks.
Sockets provide an interface for programming networks at the transport layer. Network communication
using Sockets is very much similar to performing fi le I/O. In fact, socket handle is treated like fi le handle.
The streams used in fi le I/O operation are also applicable to socket-based I/O. Socket-based
communication is independent of a programming language used for implementing it. That means, a socket
program written in Java language can communicate to a program written in non-Java (say C or C++) socket
program.

24 | P a g e
Course Module on Advanced Programming

4.2 URL manipulation


URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a
Web page or FTP directory. This section shows you how to write Java programs that communicate with a
URL. A URL can be broken down into parts, as follows:

protocol://host:port/path?query#ref

Examples of protocols include HTTP, HTTPS, FTP, and File. The path is also referred to as the filename, and
the host is also called the authority. The following is a URL to a web page whose protocol is HTTP:
http://www.amrood.com/index.htm?language=en#j2se
Notice that this URL does not specify a port, in which case the default port for the protocol is used. With
HTTP, the default port is 80.
The java.net.URL class represents a URL and has a complete set of methods to manipulate URL in Java.
The URL class has several constructors for creating URLs, including the following:

Sr. No. Methods with Description


1 public URL (String protocol, String host, int port, String file) throws MalformedURLException
Creates a URL by putting together the given parts.
2 public URL (String protocol, String host, String file) throws MalformedURLException Identical to
the previous constructor, except that the default port for the given protocol is used.
3 public URL (String url) throws MalformedURLException
Creates a URL from the given String.
4 public URL (URL context, String url) throws MalformedURLException
Creates a URL by parsing together the URL and String arguments.

The URL class contains many methods for accessing the various parts of the URL being represented. Some
of the methods in the URL class include the following:
Sr. No. Methods with Description
1 public String getPath (): Returns the path of the URL.
2 public String getQuery (): Returns the query part of the URL.
3 public String getAuthority (): Returns the authority of the URL.
4 public int getPort (): Returns the port of the URL.
5 public int getDefaultPort (): Returns the default port for the protocol of the URL.
6 public String getProtocol (): Returns the protocol of the URL.
7 public String getHost (): Returns the host of the URL.
8 public String getHost (): Returns the host of the URL.
9 public String getFile (): Returns the filename of the URL.
10 public String getRef (): Returns the reference part of the URL.
11 public URLConnection openConnection () throws IOException: Opens a connection to the URL,
allowing a client to communicate with the resource.

25 | P a g e
Course Module on Advanced Programming

4.3 Socket, Port, ServerSocket and Client server communication


Sockets provide the communication mechanism between two computers using TCP. A client program
creates a socket on its end of the communication and attempts to connect that socket to a server. When
the connection is made, the server creates a socket object on its end of the communication. The client
and the server can now communicate by writing to and reading from the socket. The java.net.Socket class
represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to
listen for clients and establish connections with them. The following steps occur when establishing a TCP
connection between two computers using sockets:
• The server instantiates a ServerSocket object, denoting which port number communication is to occur on.
• The server invokes the accept () method of the ServerSocket class. This method waits until a client
connects to the server on the given port.
• After the server is waiting, a client instantiates a Socket object, specifying the server name and
the port number to connect to.
• The constructor of the Socket class attempts to connect the client to the specified server and the
port number. If communication is established, the client now has a Socket object capable of
communicating with the server.
• On the server side, the accept () method returns a reference to a new socket on the server that is
connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket has both
an OutputStream and an InputStream. The client's OutputStream is connected to the server's
InputStream, and the client's InputStream is connected to the server's OutputStream. TCP is a two-way
communication protocol; hence data can be sent across both streams at the same time. The following
Greeting Client is a client program that connects to a server by using a socket and sends a greeting, and
then waits for a response.

import java.io.*
import java.net.Socket;
public class GreetingClient {
public static void main(String [] args) {
String serverName = "localhost";
final int port = 1245;
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket (serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}
catch (IOException e) {
System.out.println("Error " + e.getMessage());
}
}
}

26 | P a g e
Course Module on Advanced Programming

The following GreetingServer program is an example of a server application that uses the Socket class to
listen for clients on a port number specified by a command-line argument: This example uses some thread
concept so, beware of that.
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private static ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
@Override
public void run()
{
while (true)
{
try
{
System.out.println("Waiting " + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Connected to "+ server.getRemoteSocketAddress());
DataInputStream in= new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out= new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank "+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}
catch (SocketTimeoutException s){
System.out.println("Socket timed out!");
break;
}
catch (IOException e) {
System.out.println("Error "+e.getMessage());
break;
}
}
}
public static void main(String[] args)
{
int port = 1245;
try
{
Thread t = new GreetingServer(port);
t.start();
}
catch (IOException e) {
System.out.println("Error "+e.getMessage());
}
}
}

27 | P a g e
Course Module on Advanced Programming

UNIT FIVE:
5. Java Database Connectivity
Unit description:
This unit deals with the general descriptions of database system, SQL and JDBC (java database
connectivity). These contents will be delivered to the students through brain storming, group discussion,
observation/demonstration, and mini lecture. And students assessed with lab exercise, group work and
individual lab assignment.
Objectives: At the end of this unit, the students will be able to:
Define database and SQL K L,1
Explain concepts of JDBC K L,1
Construct a certain java application using JDBC A L,4
 Contents:
5.1 Define database and SQL
5.2 Concepts of JDBC programming
5.3 Installation and setting of JDBC
5.4 Executing database quires
5.5 Explain the RowSet interface
Method of teaching: Brain storming, mini lecture, group discussion, lab work

Introduction:
Brain storming: What is database, what are the best ways to store data permanently
5.1 Database and SQL
A database provides various functions like data security, data integrity, data sharing, data concurrence,
data independence, data recovery etc. However, all database management systems that are now available
in the market like Sybase, Oracle, and MS-Access do not provide the same set of functions, though all are
meant for data management. Almost all relational database management systems use SQL (Structured
Query Language) for data manipulation and retrieval. SQL is the standard language for relational database
systems. SQL is a non-procedural language, where you need to concentrate on what you want, not on
how you get it. Put it in other way, you need not be concerned with procedural details. SQL Commands
are divided into four categories, depending upon what they do.

DDL (Data Definition Language)


DML (Data Manipulation Language)
DCL (Data Control Language)
Query (Retrieving data)
DDL commands are used to define the data. For example, CREATE TABLE.
DML commands such as, INSERT and DELETE are used to manipulate data.
DCL commands are used to control access to data. For example, GRANT.
Query is used to retrieve data using SELECT.
DML and Query are also collectively called as DML. And DDL and DCL are called as DDL.

28 | P a g e
Course Module on Advanced Programming

5.2 JDBC programming


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 Server Pages (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. JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code.

5.2.1 JDBC components


DriverManager: This class manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication subprotocol. The first
driver that recognizes a certain subprotocol under JDBC will be used to establish a database
Connection.
Driver: This interface handles the communications with the database server. You will interact
directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages
objects of this type. It also abstracts the details associated with working with Driver objects.
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.

29 | P a g e
Course Module on Advanced Programming

5.2.2 The JDBC packages


The java.sql and javax.sql are the primary packages for JDBC. It offers the main classes for interacting with
your data sources. These packages have the following common features.

 Automatic database driver loading.


 Exception handling improvements.
 Enhanced BLOB/CLOB functionality.
 Connection and statement interface enhancements.
 National character set support.
 SQL ROWID access.
 SQL 2003 XML data type support.
 Annotations.

5.3 Installation and setting of JDBC


To start developing with JDBC, you should setup your JDBC environment by following 4 steps shown
below. Assume that you are working on a Windows platform.

Step 1: Install J2SE Development Kit 5.0 (JDK 5.0) from Java Official Site. Make sure following
environment variables are set as described below:

JAVA_HOME: This environment variable should point to the directory where you installed the
JDK, e.g. C:\Program Files\Java\jdk1.5.0.
CLASSPATH: This environment variable should have appropriate paths set, e.g. C:\Program
Files\Java\jdk1.5.0_20\jre\lib.
PATH: This environment variable should point to appropriate JRE bin, e.g. C:\Program
Files\Java\jre1.5.0_20\bin.

Step 2: Install database: The most important thing you will need, of course is an actual running database
with a table that you can query and modify. Install a database that is most suitable for you. You can have
plenty of choices but, for now we are going to use MySQL database.

Step 3: Install Database Drivers: The latest JDK includes a JDBC-ODBC Bridge driver that makes most Open
Database Connectivity (ODBC) drivers available to programmers using the JDBC API. Now-a-days, most of
the Database vendors are supplying appropriate JDBC drivers along with Database installation. So, you
should not worry about this part.

Step 4: Set Database Credential: Since, we are going to use MySQL database. When you install any of the
database including MySQL, its administrator ID is set to root and gives provision to set a password of your
choice. Using root ID and password you can either create another user ID and password, or you can use
root ID and password for your JDBC application. There are various database operations like database
creation and deletion, which would need administrator ID and password.

30 | P a g e
Course Module on Advanced Programming

5.4 Executing Database Quires


5.4.1 Creating database

package jframedemo;
import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "username";
static final String PASS = "password";
public static void main(String [] args)
{
Connection conn;
Statement stmt;
try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 4: Execute a query
System.out.println("Creating database...");
stmt = conn.createStatement();
String sql = "CREATE DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
} catch (SQLException | ClassNotFoundException se) {
System.out.println("Error "+se.getMessage());
}
}
}

5.4.2 Creating table

import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn;
Statement stmt;
try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();

31 | P a g e
Course Module on Advanced Programming

String sql = "CREATE TABLE REGISTRATION (id INTEGER not NULL, "
+ " first VARCHAR(255),last VARCHAR(255),age INTEGER, "
+ " PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException | ClassNotFoundException se) {
}
}
}

5.4.3 Inserting, deleting and updating data to and from the table

import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username";
static final String PASS = "password";
public static void main (String [] args) {
Connection conn;
Statement stmt;
String sql;
try {
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a insertion query
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
sql = "INSERT INTO Registration VALUES (100, 'Zara', 'Ali',18)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
//STEP 4: Execute a update query
sql = "UPDATE Registration SET age = 30 WHERE id in (100, 101)";
stmt.executeUpdate(sql);
System.out.println("Update records from the table...");
//STEP 4: Execute a delete query
sql = "DELETE FROM Registration WHERE id = 100";
stmt.executeUpdate(sql);
System.out.println("Delete records from the table...");
} catch (SQLException | ClassNotFoundException se) {
System.out.println("Error "+se.getMessage());
}
}
}

32 | P a g e
Course Module on Advanced Programming

5.4.4 Selecting and extracting data from table


import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn;
Statement stmt;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
//Extract data from result set
while (rs.next()) {
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.println("ID: " + id);
System.out.println(", Age: " + age);
System.out.println(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
} catch (SQLException | ClassNotFoundException se) {
System.out.println("Error "+se.getMessage());
}
}
}

5.5 RowSet Interface


There are two types of RowSet objects—connected and disconnected. A connected RowSet object
connects to the database once and remains connected until the application terminates. A disconnected
RowSet object connects to the database, executes a query to retrieve the data from the database and
then closes the connection. A program may change the data in a disconnected RowSet while it is
disconnected. Modified data can be updated in the database after a disconnected RowSet reestablishes
the connection with the database. The instance of RowSet is the java bean component because it has
properties and java bean notification mechanism. It is introduced since JDK 5. It is the wrapper of
ResultSet. It holds tabular data like ResultSet but it is easy and flexible to use. The java standard edition
package javax.sql. RowSet contains two sub interfaces of RowSet—JdbcRowSet and CachedRowSet.
JdbcRowSet, a connected RowSet, acts as a wrapper around a ResultSet object, and allows programmers
to scroll through and update the rows in the ResultSet

33 | P a g e
Course Module on Advanced Programming

5.5.1 RowSet interface example


import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
public class RowSetExample {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
//Creating and Executing RowSet
JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
rowSet.setUrl("jdbc:mysql://localhost/STUDENTS");
rowSet.setUsername("root");
rowSet.setPassword("");
rowSet.setCommand("select * from Registration");
rowSet.execute();
while (rowSet.next()) {
System.out.println("Id: " + rowSet.getInt(1));
System.out.println("Age: " + rowSet.getInt(2));
System.out.println("First: " + rowSet.getString(3));
System.out.println("Last: " + rowSet.getString(4));
}
}
}

5.5.1 RowSet interface example


import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
public class RowSetExample {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
rowSet.setUrl("jdbc:mysql://localhost/STUDENTS");
rowSet.setUsername("system");
rowSet.setPassword("oracle");
rowSet.setCommand("select * from Registration");
rowSet.execute();
rowSet.addRowSetListener(new MyListener());
while (rowSet.next()) {
System.out.println("Id: " + rowSet.getInt(1));
System.out.println("Age: " + rowSet.getInt(2));
System.out.println("First: " + rowSet.getString(3));
System.out.println("Last: " + rowSet.getString(4));
}
}
}
class MyListener implements RowSetListener {
public void cursorMoved(RowSetEvent event) {
System.out.println("Cursor Moved...");
}
public void rowChanged(RowSetEvent event) {
System.out.println("Cursor Changed...");
}
public void rowSetChanged(RowSetEvent event) {
System.out.println("RowSet changed...");
}
}

34 | P a g e
Course Module on Advanced Programming

UNIT SIX:
6. Remote Method Invocation(RMI)
Unit description:
This unit deals with the general descriptions of remote message invocation, registry of RMI and
implementation of REMI.These contents will be delivered to the students through brain storming, group
discussion, observation/demonstration, and mini lecture. And students assessed with lab exercise, group
work and individual lab assignment.
Objectives: At the end of this unit, the students will be able to:
Define remote message invocation K L,1
Describe the remote interface of java library K L,1
Construct a certain java application using RMI A L,4
 Contents:
6.1 Define RMI
6.2 Registry of RMI
6.3 Remote Interface and Implementation of RMI
Method of teaching: Mini lecture, group discussion, lab work

Introduction:
6.1 Remote Message Invocation (RMI)
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. A remote object is an object
whose method can be invoked from another JVM. Let's understand the stub and skeleton objects:

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

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


 It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
 It waits for the result
 It reads (unmarshals) the return value or exception, and
 It finally, returns the value to the caller.

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

 It reads the parameter for the remote method


 It invokes the method on the actual remote object, and
 It writes and transmits (marshals) the result to the caller.

35 | P a g e
Course Module on Advanced Programming

6.2 Register of RMI


The RMI registry is implemented as an RMI server. Underlying Naming’s static methods is an interface
that extends Remote and an implementation of that interface. In Java 2, these are:
The java.rmi.registry.Registry interface This extends Remote and defines the methods an
implementation of Registry must implement.
The sun.rmi.registry.RegistryImpl implementation class This is an actual RMI server that
implements the Registry interface.
The Registry interface is straightforward. It defines five methods, each of which maps directly to one of
the static methods defined in Naming:
public interface Registry extends Remote {

public static final int REGISTRY_PORT = 1099;

public Remote lookup(String name) throws RemoteException, NotBoundException, AccessException;

public void bind(String name, Remote obj) throws RemoteException, AlreadyBoundException, AccessException;

public void unbind(String name) throws RemoteException, NotBoundException, AccessException;

public void rebind(String name, Remote obj) throws RemoteException, AccessException;

public String[] list( ) throws RemoteException, AccessException;


}

Lookup (): It returns the reference of the remote object.


Bing (): It binds the remote object with the given name.
Unbind (): It destroys the remote object which is bound with the given name.
Rebind (): It binds the remote object to the new name.
List (): It returns an array of the names of the remote objects bound in the registry.
6.3 Remote interface and implementation of RMI
The Remote Interface represents the type of an object handle and tells clients how to invoke remote
methods. The remote class defines those objects. The interface definition must be public, must extend
the interface java.rmi.Remote and every method in the interface must declare that it throws
java.rmi.RemoteException (but other exceptions may be thrown as well)

Now let’s see a sample program in which a client program invokes a remote method with string as a
parameter then the sever returns a string containing the reversed input string and a message. We define
an interface for a remote class that includes one remote method: say accepts a String as an input
parameter and returns a String as a result. Note that the interface extends Remote and that each method
36 | P a g e
Course Module on Advanced Programming

(there’s only one here) throws Remote Exception. These classes are defined in the java.rmi package, so
we import it.

The remote class defines two methods: Hello is our constructor and will be used by the server to set define
the standard message that will always be sent back to the client. say is a method that takes a string as the
input. It returns a string containing the input with the characters reversed followed by a newline followed
by our standard message (set in the constructor). the class extends UnicastRemoteObject this will allow
the methods to be invoked remotely the class implements the interface we defined each method must
throw RemoteException because remote procedure calls might fail the say method accepts a String and
returns a String. String is defined to be Serializable. If you were to accept or return an object you defined,
it would have to be defined to implement Serializable.

The server is a plain program that is responsible for two things: 1, creating and installing a security
manager. We do this with: System.setSecurityManager (new RMISecurityManager ()); The security
manager makes sure that classes that get loaded do not perform operations that they are not allowed
to perform. 2, Registering at least one remote object with the object registry. We do this with:
Naming.rebind (object_name, object); where object name is a String that names the remote object
and object is the remote object that we are registering. All that our server does is: set the security
manager create the remote object register it print a message saying “Server is running…”.
37 | P a g e
Course Module on Advanced Programming

The client invokes the remote method. To do this, the client must have a handle (reference) to the
remote object. The object registry allows the client to get this reference to a remote object. To get
the reference to the remote object, we need to know three things: 1, Internet name (or address) of
machine that is running the object registry for which the remote object is registered (can omit if
localhost). 2, Port on which the object registry is running (can omit if it is 1099 - default). 3, Name of
the object within the object registry. The Naming.lookup method obtains an object handle from the
object registry running on localhost on the default port (we could have just looked up “Hello” in this
case). The result of Naming.lookup must be cast to the type of the Remote Interface. The remote
invocation of the object is the call to hello.say(“abc”). It returns a String which we print. Remember
again, that we can get a String only because String is a Serializable class.

38 | P a g e
Course Module on Advanced Programming

UNIT SEVEN:
7. Introduction Servlets
Unit description:
This unit deals with the general descriptions of java servlets, architecture of servlet, HTTP requests and
applications of servlet. These contents will be delivered to the students through group discussion,
observation/demonstration, and mini lecture.
Objectives: At the end of this unit, the students will be able to:
Define servlets and their architectures K L,1
Differentiate the HTTP request A L,1
Define the applications of servlet K,1
Construct a certain java application using servlets A L,4
 Contents:
7.1 Define servlet and its architecture
7.2 The different HTTP requests
7.3 Servlet Programming Examples
Method of teaching: Mini lecture, group discussion, lab work.

Introduction:
7.1 Servlets and Architecture of servlets
Java Servlets are programs that run on a Web or Application server and act as a middle layer between a
request 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. Servlets offer several advantages some
of them are listed below.

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 and will see soon.

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.

39 | P a g e
Course Module on Advanced Programming

 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 returned (e.g., HTML), setting cookies and caching
parameters, and other such tasks.
The following diagram shows the position or architecture of Servlets in a Web Application

7.2 HTTP Requests


One of the keys to creating effective servlets is understanding how to manipulate the Hypertext Transfer
Protocol (HTTP). Thoroughly understanding this protocol is not an esoteric, theoretical concept, but rather
a practical issue that can have an immediate impact on the performance and usability of your servlets.
This section discusses the HTTP information that is sent from the browser to the server in the form of
request headers. It explains the most important HTTP 1.1 request headers, summarizing how and why
they would be used in a servlet. Reading headers is straightforward; just call the getHeader method of
HttpServletRequest with the name of the header. This call returns a String if the specified header was
supplied in the current request, null otherwise. In HTTP 1.0, all request headers are optional; in HTTP 1.1,
only Host is required. So, always check for null before using a request header. Header names are not case
sensitive. So, for example, request.getHeader ("Connection") is interchangeable with
request.getHeader("connection"). Although getHeader is the general-purpose way to read incoming
headers, a few headers are so commonly used that they have special access methods in
HttpServletRequest. Following is a summary.

Sr. No. Methods with Description


1 getCookies () The getCookies method returns the contents of the Cookie header, parsed and stored in
an array of Cookie objects. This method is discussed in more detail in Chapter 8 (Handling Cookies).
2 getAuthType () and getRemoteUser () The getAuthType and getRemoteUser methods break the
Authorization header into its component pieces.
3 getContentLength () The getContentLength method returns the value of the Content-Length header (as
an int).
4 getContentType () The getContentType method returns the value of the Content-Type header (as a
String).
5 getDateHeader () and getIntHeader () The getDateHeader and getIntHeader methods read the specified
headers and then convert them to Date and int values, respectively.

40 | P a g e
Course Module on Advanced Programming

6 getHeaderNames () Rather than looking up one particular header, you can use the getHeaderNames
method to get an Enumeration of all header names received on this particular request. This capability is
illustrated in Section 5.2 (Making a Table of All Request Headers).
7 getHeaders () In most cases, each header name appears only once in the request. Occasionally, however,
a header can appear multiple times, with each occurrence listing a separate value. Accept-Language is
one such example. You can use getHeaders to obtain an Enumeration of the values of all occurrences of
the header.
8 getMethod () The getMethod method returns the main request method (normally, GET or POST, but
methods like HEAD, PUT, and DELETE are possible).
9 getRequestURI the getRequestURI method returns the part of the URL that comes after the host and
port but before the form data. For example, for a URL of
http://randomhost.com/servlet/search.BookSearch?subject=jsp, getRequestURI would return
"/servlet/search.BookSearch".
The following java code shows all the request headers sent on the current request

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ShowRequestHeaders extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Servlet Example: Showing Request Headers";
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=\"#FDF5E6\">\n"
+ "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n"
+ "<B>Request Method: </B>" + request.getMethod()
+ "<BR>\n" + "<B>Request URI: </B>"
+ request.getRequestURI() + "<BR>\n"
+ "<B>Request Protocol: </B>"
+ request.getProtocol() + "<BR><BR>\n"
+ "<TABLE BORDER=1 ALIGN=\"CENTER\">\n"
+ "<TR BGCOLOR=\"#FFAD00\">\n"
+ "<TH>Header Name<TH>Header Value");
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
out.println("<TR><TD>" + headerName);
out.println(" <TD>" + request.getHeader(headerName));
}
out.println("</TABLE>\n</BODY></HTML>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

41 | P a g e
Course Module on Advanced Programming

7.3 Servlet Programming Example


Following is the sample source code structure of a servlet example to show Hello World: Note the
message will be displayed on the web.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}
}

Reading Form Data using Servlet: Servlets handles form data parsing automatically using the following
methods depending on the situation:

getParameter (): You call request.getParameter() method to get the value of a form parameter
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.

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:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = 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"

42 | P a g e
Course Module on Advanced Programming

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

Here is a simple example which passes two values using HTML FORM and submit button. We are going to
use same Servlet HelloForm to handle this input.

<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

here is the actual output of the above form.

First Name: Last Name: Submit

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.

43 | P a g e
Course Module on Advanced Programming

Methods of course delivery


• 75% of active learning (Brain storming, Group discussion, presentation…) with 25% of mini
lecture.

Assessment methods
The assessment methods are listed below by considering both domains of education and
hierarch of learning. Formative Assessments:

•Quiz………………………….………...... 5 %
•Group assignment ………….……...........5 %
•Individual assignment ……………..........5 %
• Project... ...................... …………….........25 % •
Test………...……………………............. …………………10%
Sub Total…………………......................50 %

Summative Assessment:
• Final Exam …… ……………….............50 %
Total ……………………..................... 100 %

References:
S. Horstmann and Gary Cornell, Core Java 2 – Volume II- Advanced Features
Sun Microsystems Press
Harvey M. Deitel and Paul J. Deitel, Java How to Program
Deitel & Associates Inc, java.sun.com/docs/books/tutorial
E Balagurusamy, programming with java
For more information, you can visit the tutorials point website www.tutorialspoint.com

44 | P a g e

You might also like