Professional Documents
Culture Documents
Concepts of AWT
AWT stands for Abstract Window Toolkit. It is a platform dependent API for
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
kinds of calls or requests that can be made, how to make them, the data formats
Why AWT is platform dependent? Java AWT calls native platform (Operating
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
Container
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
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
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.
Dialog – It is like a pop up window but not fully functional like the frame
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.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and
feel.
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.
P a g e 11 | 74
JComboBox
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
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.
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
public abstract void actionPerformed(ActionEvent e);
P a g e 13 | 74
1) Implement the ActionListener interface in the class:
public class ActionListenerExample Implements ActionListener
component.addActionListener(instanceOfListenerclass);
public void actionPerformed(ActionEvent e){
//Write the code here
}
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
Stream does not hold any data. This is very important to keep that in mind and
understand.
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
P a g e 16 | 74
Source - Streams take a collection, array, or I/O resources as a source for
their data.
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.
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.
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.
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.
DataOutputStream An output stream that contain method for writing java standard data
These classes define several key methods. Two most important are
These two abstract classes have several concrete classes that handle unicode
character.
P a g e 20 | 74
Reader Abstract class that define character stream input
File Handling
1. Create file
2. Delete file
3. Read file
4. Write file
Create File
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);
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;
P a g e 25 | 74
File Obj = new File("FileDemo.txt");
if (Obj.delete()) {
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.
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.
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
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
parts of a program for maximum utilization of CPU. Each part of such program is
program contains two or more parts that can run concurrently. Each such part of a
2. Threads are lightweight sub-processes, they share the common memory space.
utilize the maximum CPU time so that the idle time can be kept to minimum.
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
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.
Creating a thread
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
A Simple Example
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
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.
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.
Multithreading
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.
An instance of Thread class.
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
Multitasking
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.
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.
class MainThread
{
public static void main(String[] args)
{
Thread t = Thread.currentThread();
t.setName("MainThread");
System.out.println("Name of thread is "+t);
}
}
Output
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.
It is the default priority that is given to a thread if it is not defined. The value for
this is 0.
It is the maximum priority that can be given to a thread. The value for this is 10.
P a g e 38 | 74
Chapter Four
Introduction to Java Networking
The java.net package provides support for two protocols. They are as follows:
two applications. TCP is typically used over the Internet Protocol, which is
referred to as TCP/IP.
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
6. Socket
1) IP Address
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
address).
identification and local addressing. It’s role has been characterized as follows : “A
2) Protocol
example:
o TCP
network. It is the most common protocol in networks that use the Internet
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
complete.
P a g e 40 | 74
o FTP
FTP is a widely used network protocol for transferring files between computers
and applications exchange and share data within their offices and across the
Internet.
o Telnet
using a telnet client. For example, typing telnet hostname would connect a user to a
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
purpose is to send, receive, and/or relay outgoing mail between email senders and
receivers.
o POP
3) Port Number
The port number is associated with the IP address for communication between two
applications.
P a g e 41 | 74
4) MAC Address
Interface Controller). A network node can have multiple NIC but each with unique
MAC.
6) Socket
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
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
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
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
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
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
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
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
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
This starts our Server listening for client requests coming in for port 5000.
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
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.
Open two windows one for Server and another for Client
Server started
$ 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
Over
Hello
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
JVM.
for the client to invoke method on it. A Client program make request for remote
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:
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:
At the server side, the packed parameters are unbundled and then the required
method is invoked. This process is known as unmarshalling.
that object is made available for the client (using the registry).
The client program requests the remote objects on the server and tries to
P a g e 50 | 74
The following diagram shows the architecture of an RMI application
Transport Layer − This layer connects the client and the server. It manages
resides in the client system; it acts as a gateway for the client program.
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).
P a g e 52 | 74
Goals of RMI
Minimize the difference between working with local and remote objects.
Remote interface
Declare all the business methods that can be invoked by the client in this
interface.
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:
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.
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.
P a g e 56 | 74
Chapter 6 –
Java Database Connectivity
What is Database?
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.
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
Relational Database:
A relational database is made up of a set of tables with data that fits into a
predefined category.
Distributed Database:
P a g e 57 | 74
Cloud Database:
Database service provides access to the database. Database services make the
create, maintain and retrieve the relational database. Following are some
(like SELECT, UPDATE, CREATE, etc) in capital letters and use user defined
We can write comments in SQL using “–” (double hyphen) at the beginning of
any line.
like MySQL, Oracle, Sybase, SQL Server, Postgre, etc. Other non-relational
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.
e.g.; ROLL_NO, NAME etc.
Tuple: Each row in the relation is known as tuple. The above relation contains 4
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;
There are 5 steps to connect any java application with the database using JDBC.
Create connection
Create statement
Execute queries
Close 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
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");
The createStatement() method of Connection interface is used to create statement. The object of s
responsible to execute queries with the database.
1. public Statement createStatement()throws SQLException
1. Statement stmt=con.createStatement();
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.
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. }
By closing connection object statement and ResultSet will be closed automatically. The close() meth
interface is used to close the connection.
1. public void close()throws SQLException
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
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
can communicate with applets, databases, or other software via the sockets
Servlets Architecture
P a g e 63 | 74
The following diagram shows the position of Servlets in a Web Application.
Servlets 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
Process the data and generate the results. This process may require talking
Send the explicit data (i.e., the document) to the clients (browsers). This
Send the implicit HTTP response to the clients (browsers). This includes
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
which are a standard part of the Java's enterprise edition, an expanded version of
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
The HTTP client sends the request to the server in the form of request message
o The Request-line
P a g e 65 | 74
o The Cache control header
The HTTP request method indicates the method to be performed on the resource
HTTP Description
Request
POST Asks the server to accept the body info attached. It is like GET request with
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.
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
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
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:
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");
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.
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");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Add</title></head><body>");
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:
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:
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;
}
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("</body></html>");
}
}
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 :
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>
Hobbies:
<input type="checkbox" name="soccer"> Soccer
<input type="checkbox" name="cricket"> Cricket
<input type="checkbox" name="baseball"> Baseball<br><br>
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>
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>");
}
}
P a g e 74 | 74