Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

1

UNIT 01. MULTI-THREADED PROGRAMMING


4

UNIT 4
4.1. Multithreading in java
4.1.1. Thread life cycle and methods
4.1.2. Runnable interface
4.1.3. Thread Synchronisation
4.1.4. Exception handling with try-catch-finally
4.1.5. Collections in Java
4.1.6. Introduction to Java and network
programming
2

Thread
It is a light weight of process. Process means the execution of the program.

Multithreading
Two or more number of threads is executed during the same time known as
multithreading.

 The multithreading is used to perform the operations on multitasking.


 Multitasking means two or more programs that are executed at the same
time.

This concept is basically performing in two ways.


1. Process based multitasking.
2. Thread based multitasking.

1. Process based multitasking: It is running two or more programs concurrently.


2. Thread based multitasking: It is a single program performing more than
one task at the same time.

Thread-based multitasking has several advantages over process based multitasking.


 Threads are light weight compare to processes.
 Threads are stored in same address place.
 Contact switching between the threads is usually less expensive.
 The cost of thread inter communication is very less.
 Threads allow different task to be performed concurrently.

Types of Threads
1. Daemon thread
2. User thread

1. Daemon thread
They are usually designed to run the background for the purpose of servicing the
user thread.
Example: Garbage collection.

2. User thread
The user creates his own threads in the java program.

Different types of creating threads.


1. By extending the java.lang.Thread class
2. By implementing the java.lang.Runnable interface
3

1. By extending the java.lang.Thread class

class MyThread extends Thread


{
public void run()
{
System.out.println(“My thread is running”);
}
}

The run() method is a core part of threads in java. This method is entry point and
exit point for any thread recreate.

2. By implementing the java.lang.Runnable interface

public interface Runnable()


{
public void run();
}
class MyRunnable implements Runnable
{
public void run()
{
System.out.println(“Thread will execute the code”);
}
}

Creating thread by extending thread class

Step 1: Create a class that extends thread class like

class MyThread extends Thread


{
}

Step 2: Override public void run() method inside the class.

class MyThread extends Thread


{
public void run()
{
}
}
4

Step 3: Inside of run() method we have to print the value.

class MyThread extends Thread


{
public void run()
{
System.out.println(“run() started”);
for(int i=1;i<=10;i++)
{
System.out.println(“The value is :”+i);
}
System.out.println(“run() completed”);
}
}

Step 4: Write another class to create thread

class ThreadDemo
{
public static void main(String args[])
{
}
}

Step 5: Create an object inside the main thread.

MyThread obj=new MyThread();

Step 6: Built in thread

Thread t1=new Thread(obj);

Step 7: t1.start();

Step 8: Execute till end of the thread.


5

Creating multiple threads

Used to execute two or more thread simultaneously.

//Program to show the use of Multithread

class ThreadA extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
System.out.println(Thread.currentThread().getName()+"="+i);
System.out.println("End of thread one");
}
}

class ThreadB extends Thread


{
public void run()
{
for(int i=6;i<=10;i++)
System.out.println(Thread.currentThread().getName()+"="+i);
System.out.println("End of thread two");
}
}

class ThreadC extends Thread


{
public void run()
{
for(int i=11;i<=15;i++)
System.out.println(Thread.currentThread().getName()+"="+i);
System.out.println("End of thread three");
}
}

class MultipleThreads
{
public static void main(String args[])
{
ThreadA ta=new ThreadA();
ThreadB tb=new ThreadB();
ThreadC tc=new ThreadC();
Thread t1=new Thread(ta,"Thread one");
6

Thread t2=new Thread(tb,"Thread two");


Thread t3=new Thread(tc,"Thread three");
t1.start();
t2.start();
t3.start();
for(int i=16;i<=20;i++)
System.out.println(Thread.currentThread().getName()+"="+i);
System.out.println("End of main");
}
}

Life cycle of Thread

The life cycle of the thread is basically starts from start() method this thread is used to
execute the main thread and complete it. After this picked up the threads execution
from the run() method one by one until the completion of all the threads.
Ready to run state: A thread is ready to run state and it is eligible for execution which
ever thread comes first the start() method is execute that thread. If the thread state is
not ready to run it should be blocked or waiting or it is sleeped.
Not ready to run: If thread is not ready to execute and it is not running, that should be
following another 3 states.
1. Sleeping
2. Waiting
3. Blocked
7

1. Sleeping: Incase thread is not ready that particular thread will be sleeped for the
some period of time that must be declared as Thread.sleep();

2. Waiting: If thread is not ready to execute it must be execute after some time we
should use the method wait().

3. Blocked: If thread is not execute and not running properly or problems in network
resources or not interested to execute the particular thread these times thread will
be blocked. After getting all the resources we will call isAlive() method.

Methods of thread
I. current thread():
It shows the current running thread.
II. getName()
It returns the name of the thread.

//Program to show the use of currentThread() and getName ()

class CurrThread
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println(t.getName());
}
}

III. setName()
It Set’s the name of the thread.

//Program to show the use of setName() methods


import java.lang.Thread;
class ThreadA extends Thread
{
public void run()
{
System.out.println("this is thread A class");
}
8

}
class CurrThread
{
public static void main(String args[])
{
System.out.println(Thread.currentThread().getName());
ThreadA ta = new ThreadA();
ta.setName("Thread one");
Thread t = new Thread(ta);
System.out.println(t.getName());
}
}

IV. Sleep()
It is used to sleep for the specified amount of time in a current thread.

//Program to show the use of sleep()

class ThreadSleep
{
public static void main(String args[])
{
Thread t= Thread.currentThread();
System.out.println("Before sleep");
try
{
Thread.sleep(10000);
}
catch(InterruptedException e)
{
System.out.println("I slept for 10 seconds");
}
}
}

V. setPriority()
It Set’s the priority of the thread.

VI. getPriority()
By default the getPriority is 5, if we want to set more than 5 we should use
setPriority.
9

//Program to show the use of setPriority() and getPriority()

class ThreadPriority
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Main thread Priority :"+t.getPriority());
t.setPriority(10);
System.out.println("Main Thread Priority :"+t.getPriority());
}
}

VII. stop()
It is used to kill the thread.

VIII. start()
It is used to execute the beginning of the thread execution and calls in the run()
method.

IX. wait()
It is used to wait the next Thread execution until the current thread is executed.

X. suspend()
Suspend the thread or it is completely blocked in a thread.

XI. resume()
Pausing the current thread.

SYNCHRONIZATION
When using multiple threads it is sometimes necessary to co-ordinate the activities
of two or more. This process by which this is achieved is called as synchronization.
Example
Assume that a husband and wife use an ATM card that does'nt incorporate
synchronization. The husband goes to ATM system to withdraw Rs: 1000 from the joint
a/c. the wife does the same thing in another part of the town. The account has only 1200
10

rupees in it the husband check the account has at least 1200 in it. The ATM shows that
the money is there while the husband is preparing to withdraw the money. The wife
checks the same a/c on the ATM across town. The ATM shows the A/C has 1200 in it. So
she also decides to withdraw 1000 rupees from the account at the extra same time. They
both select the withdraw option. Since the ATM has not synchronization the two ATM
they both check to see that at least 1200. rupees is in the A/C and since its the perform
withdrawal. The result that the couple has now overdraws their A/C or only one person
has successed. The other one will in confusing state. This type of situation is handled by
the technique of synchronization. Synchronization is a keyword that is used to execute
the multi-threading concept with co-ordination b/w two threads and execute smoothly
otherwise it’s locked or blocked.
General Syntax:
synchronization void withdraw()
{
}

When we want to block the multiple thread we want to use the following.
synchronization(object)
{
}

//Program to show the use of synchronization in java


class Parentheses
{
synchronized void display(String s)
{
System.out.print("("+s);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.print(")");
}
}
11

class MyThread extends Thread


{
String s1;
Parentheses p1;
Thread t;
public MyThread(Parentheses p2, String s2)
{
p1=p2;
s1=s2;
}
public void run()
{
p1.display (s1);
}
}

class Nonsynchronized
{
public static void main(String args[])
{
Parentheses P3 = new Parentheses();
MyThread ta1 = new MyThread(P3, "Srikanth");
Thread t1 = new Thread(ta1);
MyThread ta2 = new MyThread(P3, "Srigdha");
Thread t2 = new Thread(ta2);
t1.start();
t2.start();
}
}

DEFINITION OF SYNCHRONIZATION

Synchronization is the process of avoiding the multiple thread to act on the


same data or method.

Creating thread by implementing runnable interface.


Runnable is an interface it’s on alternative to extend the thread class and Define the
run() method instead of runnable interface then expand inside the class.
12

Step 1: class Mythread implements Runnable


{
}

Step 2: class My thread implements Runnable


{
public void run()
{
}
}

Step 3: class My thread implements Runnable


{
public void run()
{
for(i=1;i<=10;i++)
{
System.out.println("The val of i="+i);
}
System.out.println("run() completed");
}
}

Step 4: class Thread Runnable


{
public Static void main(String args[])
{
}
}

Step 5: Create an object as follows;


My thread obj = new My thread();

Step 6: Create the thread class object as follows


Threads t1 = new Thread(obj);

Step 7: Start the thread for execution.


t1.Start();

Step 8: Execution completed


13

//Program to show the use of creating thread by implementing runnable


interface
class Mythread implements Runnable
{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("the val of i="+i);
}
System.out.println("run() completed");
}
}

class ThreadRunnable
{
public static void main(String args[])
{
System.out.println("Main thread started");
Mythread obj=new Mythread();
Thread t1 = new Thread(obj);
t1.start();
System.out.println("Main thread completed");
}
}

JAVA COLLECTION

Java Collection Frame word definition

It is a collection of inter faces and classes to represent a group of object as


a single unit known as java collection frame work.

The collection of java objects that is used to perform the operation such as searching,
sorting, insertion, manipulation and deletion etc.

The structure of JCF (Java Collection Frame) is used to collect different variety of object
as shown by following figure.
14

Composition of java collection frame work:


There are 3 elements of java collection frame work.
1. Interface
2. Implementation or classes.
3. Algorithm

1. Interface
Interface is a collection of abstract data type that is used to represent java
collection frame work.
Example: List is an interface in collection frame work.

2. Implementation or classes
The several numbers of interfaces having several numbers of abstract method, then
implementing of this method inside the class only and also implement several
number of classes such as
1. Array list
2. linked list
3. Hash map
4. Tree map
5. Hash set
6. Tree set……etc.
Example: the array list and linked are implementation classes of list interfaces
3. Algorithms
The algorithms are used is perform the different types of methods and its
computation such as searching and sorting objects can implement in java
collection.
15

Example:
add (object o)
remove (object o)
are the methods of array list and linked list

Need for collection frame work


It is a collection of data items that share a common name with same data type so that
the programmer needs to create the array variables and assign the values as shown by
the following.
int[] a = new int[10];
a [0] = 10;
a [1] = 20;
a [2] = 30;
a [3] = 40;
a [4] = 50;
a [5] = 60;
a [6] = 70;
a [7] = 80;
a [8] = 90;
a [9] = 100;

Array is a fixed size of memory allocation do not increase during at rum time and if we
take less member of items the remaining memory is wastage the array of objects is the
best concept for taking the number of recodes stored in a memory allocation.
object[] obj = new object[10];
obj [0] = new customer();
obj [1] = new customer():
obj [2] = new string(“Manoj”);

Arrays is a fixed size of memory allocation do not increase during at rum time and if we
take less number of items the remaining memory is wastage.
The arrays of objects are the best concept for taking the number of records sorted in a
memory allocation.
object[] obj = new object[10];
obj [0] = new customer();
obj [1] = new customer():
obj [2] = new string(“Manoj”);
Here this object is used to take several items with several number of categories so that
we need the collection frame work in java
16

Goals of java collection frame work


1. To increase the efficiency of fundamental collection
2. All the collection work in an identical
3. Easily extending or adopting the collection
4. Use efficiency of coding for frame work
5. Unique set of datatype providing in as interface
6. Organizing the data with data key and mapping an inter face

Difference between arrays and collection

arrays collection
 Arrays is a fixed size  Collection is used to increase or
decrease the size
 Arrays can hold both primitive as well  Collection can hold only object but not
as object primitive
 The performance of an arrays is faster  The performance of a collection is
than collection slower than arrays.
 Arrays can hold only homogeneous  Collection can hold both homogeneous
and heterogeneous
 The memory allocation of arrays are  The memory allocation of an collection
not recommended to use are recommended to collection
 Readymade methods are not available  Readymade methods are available in
in array collection

Hierarchy of Collection Frame Work in Java


17

Iterator interface

It an object that can be used to loop through collections. As the suggestions,


it is used to iterate over the elements. It is used to modify and iterate over
the elements in a collection.
There are 3 methods in the iterators interface:
 public object next()
It returns the next elements in the collection. It throws the exception of
NosuchElementsException if there is no next element.

 public void remove()


It removes the current elements from the collection.

 public boolean hasnext()


It returns true if there are more elements in the collection. Else, returns false.

Syntax: Iterator <E>

iterator()
It returns an iterator of type E for the collection. It can be used to iterator over the
elements of the collection.

Collection Interface
• The collection Interface is the foundation on which the collection framework is built.
• Collection interface provides all general purpose methods which all collections
classes must supports.
• Collection interface extends iterable interface which adds support for iterating
over collection elements using the “for-each loop” statement.

Important Methods in Collection Interface

Methods Description
add(object o) To insert an element in the collection
addAll(collection c) To insert another collection in the present collection
remove(object o) To remove an element in the collection
removeAll(collection c) To remove another collection from the present
collection of another is inserted
18

retain(collection c) To remove all the collection elements that are not


contained in the specified collection.
clear() It removes all the elements from the collection.
isempty() It checks collection is empty or not and provides true
or false.
size() It gives the total number of elements present in
collection in form of a numeric value.
equals(collection c) It is used to check if the two collections are the same or
not.
toarray(collection c) It converts collect into an array.
contains(object o) It is used o searching .If an element is present in the
collection it returns true or false.
contains(collection c) It is used for searching. If element of another collection
are present in the collection or note. If present returns
true or false.

List Interface

List interface is a child interface of the collection interface.


List interface implementations classes:
• ArrayList
• LinkedList
• Vector
• Stack

It is used for searching. If element of another collection are present in the collection or
note. If present returns true or false. The subclasses implement the list interface, so the
list object can be instantiated using subclasses. Below is the syntax to instantiate the
subclasses mentioned here:

List <datatype> obj1= new Arraylist();


List <datatype> obj2= new LinkedList();
List <datatype> obj3= new Vector();
List <datatype> obj4= new Stack();
19

Important Methods of list Interface

Methods Description
add() Adds an elements to a list
addAll() Adds all elements of one list to another
get() Help to randomly access elements from list
iterator() Returns iterator object that can be used to Sequentially access
elements of lists.
set() Changes elements of list
remove() Remove an elements from the list
removeAll() Removes all the elements from the list
clear() Removes all the elements from the list(more efficient than
removeAll())
size() Returns the length of list
toArray() Converts a list into an array
contains() Returns true if a list contains specified element

Set Interface

Set is child interface of collection. It doesn’t have methods. All methods are
inherited from collection.
Below is the syntax to instantiate the classes that implement the set interface:
Set <datatype> obj1=new HashSet <data type>();
Set <datatype> obj2=new LinkedList <data type>();
Set <datatype> obj3=new TreeSet <data type>();

Here, Data type refers to the data type of the instances obj1, obj2, obj3.

Queue Interface

Queue is the child interface of collection. The queue interface of the java
collections framework provides the functionally of the queue data structure.

Below is the syntax to instantiate the classes that implements the queue interface:
Queue<datatype> q1= new priorityQueue<>();
Queue<datatype> q2= new ArrayDequeue<>();
20

Methods Description
add() Inserts the specified element into the queue .If the task is successful,
add() returns true, if not it throws an exception.
offer() Insert the specified elements into the queue. It the task is successful,
offer() returns true, if not it returns false.
elements() Returns the head of the queue. Throws an exception if the queue is
empty.
peek() Returns the head pf the queue. Return null if the queue is empty.
remove() Returns and remove the head of the queue. Throws an exception if the
queue is empty.
poll() Returns and removes the head of the queue. Returns null if the queue is
empty.

Deque Interface
• Deque is the child interface of the queue.
• Deque also known as a double-ended queue.
• Deque allow us to add and remove the elements from both the ends of the queue
• Deque interface implemented by class ArrayDeque.
• We can instantiate the Deque object with any of its implemented classes as follow:

Deque<data-type> q2= new ArrayDeque<>();


Deque<data-type> q2=new ArrayDeque<>();

Map Interface
 All the above interfaces (collection, list, set, sortedset, NavigableSet and Queue) can
be used to represent group of individual objects.
 If we want represent a group of object as key value pairs then we should go for Map
interface.
 We can instantiate the map object with any of its implemented classes as follows.

Map<Data_type> map1=new HashMap<>();


Map<Data_type> map2=new LinkedHashMap<>();
Map<Data_type> map3=new TreeMap<>();
21

Important Methods of Map Interface

Methods Description
put(k,v) Insert the association of a key k and a value v into
the map. If the key is already present, the new
valuereplaces the old value.

putAll() Inserts all the entries from the specified map to


this map.

putIfAbsent(k,v) Insert the assoication if the key k is not already


associated with the value v.

get(k) Returns the value addociated with specified key


k. If the key is not found, it returns null.

getOrDefault(k,defaultValue) Returns tha value associated with specified key k.


If the key is not found, it returns the defaultValue.

containsKey(k) Checks if the specified key k is present in the map


or not.

containsValue(v) Checks if the specified value V is present in the


map or not.

replace(k,v) Replace the value of the key k with the new


specified value V.

replace(k,oldvalue,newValue) Replaces the value of the key k with the new value
newValue only if the key k is associated with the
value oldValue.

remove(k) Removes the entry from the map represented by


the key k.

remove(k,V) Removes the entry from the map that has key K
associated with value V.

keySet() Returns a set of all the keys present in a map.


values() Returns a set of all the values present in a map.
entrySet() Returns a set of all the key/value mapping
present in a map.
22

ArrayList
In java, we use the ArrayList class to implement the functionality of resizable-arrays. It
implements the list interface of the collections framework.

Java ArrayList v/s Array


To handle this issue we can use the ArrayList class. It allows us to create resizable arrays.
Unlike arrays, ArrayList can automatically adjust their Capacity when we add or remove
elements from them. Hence, ArrayList are also known as Dynamic arrays.

Java ArrayList Implementation

Creating an ArrayList
Before using ArrayList, we need to import the java.util.ArrayList package first.
Here is how we can create arraylists in java:
ArrayList<type> arrayList =new ArrayList<>();
Here, <type> indicates the type of an arraylist.
For Example:

// create Integer type arraylist


ArrayList<Integer> arraylist=new ArrayList<>();

//create String type arraylist


ArrayList<String> arraylist=new ArrayList<>();
23

Basic Operations on ArrayList


• Add Elements
• Changes Elements
• Access Elements
• Remove Elements

• Add Elements to an ArrayList


To add a single element to the arraylist, we use the add() method of the ArrayList
class.

Example:
ArrayList<String> langList=new ArrayList<>();
langList.add("Java");
langList.add("c");
langList.add("Python");

In the above example, we have created an ArrayList named langList. Here, we have
used the add() method to add elements to langList.

• Access ArrayList Elements


To access an element from the arraylist, we use the get() method of the ArrayList
class.

Example:
String str=langList.get(0);
//Getting the other element and storing it in str
System.out.println("Element at index 0:"+str);
//prints java
System.out.println("Element at index 1:" +langList.get(1));
//prints C
System.out.println("Elements at index 2:" +langList.get(2));
// prints Python
24

In the above code, we have used the get() method with parameter 0. Here, the method
returns the elements of the ArrayList using the iterator() method. We will discuss
about iterator later.

• Change ArrayList Elements


To change elements of the arraylist, we use the set() method of the ArrayList class.

Example:
ArrayList<String> langlist=new ArrayList<>();
langList.add("Java");
langList.add("C");
langList.add("Python");
// change the element of the array list language.set(2,"JavaScript");

• Remove ArrayList Elements


To remove an element from the arraylist, we can use the remove() method of the
ArrayList calss.

Example:
ArrayList<String> langList=new ArrayList<>();
langList.add("java");
langList.add("C");
langList.add("Python");
//remove element from index 2 String str=langList.remove(2);

Here, the remove() method takes the index number as the parameter. And, removes
the element specified by the index number.

We can also remove all the elements from the arraylist at once by using removeAll()
and clear() methods of ArrayList class.

Methods of ArrayList class


Besides the basic methods of arraylist like add(), get(), set() and remove() , here
are some more ArrayList methods that are commonly used.
25

Methods Description
size() Returns the length of the arraylist.
sort() Sort the arraylist the elements.
clone() Create a new arraylist with the same element, size, and capacity.
contain() Searches the arraylist for the specified element and returns a
boolean result.
ensurecapacity() Specifies the total element the arraylist can contain.
isempty() Checks if the arraylist is empty
indexof() Searches a specified element in an arraylist and returns the index
of the element.

// ArrayList Demo
import java.util.ArrayList;
class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList<String> langList=new ArrayList<>();
langList.add("Java");
langList.add("C");
langList.add("Python");
System.out.println("ArrayList :"+langList);
System.out.println("Accessing indidvidual element:");
for(String language : langList)
{
System.out.println(language);
}
}
}

LinkedList
The linkedList class of the java collections framework provides the functionality
of the linked list data structure (doubly linkedlist).
26

Each element in a linked list is known as a node. It consists of 3 fields:


• Prev- stores an address of the previous element in the list. It is null for the first
element.
• Next- stores an address of the next element in the list. It is null for the last element.
• Data- stores the actual data.

Creating a Java LinkedList


We can create linked lists in Java as shown below:
LinkedList<type> linkedlist= new LinkedList<>();

Methods of java LinkedList


LinkedList provides various methods that allow us to perform different operations in
linked lists. We will look at four commonly used LinkedList operators in this section.
1. Add elements to a LinkedList
We can use the add() method to add an element(node) at the end of the LinkedList.

//Add elements to a LinkedList

import java.util.LinkedList;
class LinkedListDemo
{
public static void main(String args[])
{
LinkedList<String> animals=new LinkedList<>();
animals.add("dog");
animals.add("Cat");
animals.add("Cow");
27

System.out.println("LinkedList :"+animals);
animals.add(1,"Horse");
System.out.println("Update LinkedList:"+animals);
}
}

2. Access LinkedList elements


The get() method of the LinkedList class is used to access an element from the
LinkedList.

Example:
LinkedList<String> langList=new LinkedList<>();
langList.add("Python");
langList.add("Java");
langList.add("c");
String str=langList.get(0);
System.out.println("Element at index 0:"+str);
System.out.println("Element at index 1:"+langList.get(1));
System.out.println("Element at index 2:"+langList.get(2));

3. Change Elements of a LinkedList


The set() method of LinkedList class is used to change elements of the linkedList.

Example:
LinkedList<String> langList = new LinkedList<>();
langList.add("Java");
langList.add("C");
langList.add("Python");
langList.set(2,"JavaScript");

4. Remove element from a LinkedList


The remove() method of the LinkedList class is used to remove an element from the
LinkedList.

Example:
LinkedList<String> langList=new LinkedList<>();
langList.add("java");
28

langList.add("C");
langList.add("Javascript"); String str=langList.remove(1);
System.out.println("Removed Element :"+str);
langList.removeAll();

Iterating Through LinkedList


We can use the java for-each loop to iterate through LinkedList.

// Iterating through linkedList


import java.util.LinkedList;
class LinkedListIteration
{
public static void main(String args[])
{
LinkedList<String> langList=new LinkedList<>();
langList.add("Java");
langList.add("C");
langList.add("Python");
System.out.println("LinkedList:"+langList);
System.out.println("Accessing linked list Elements:");
for(String language:langList)
{
System.out.println(language);
}
}
}

Difference between LinkedList and ArrayList

LinkedList ArrayList
1. Implements List and Deque interfaces. 1. Implements List interface.
LinkedList class can act as a list and An ArrayList class can act as a list only
queue both because it implements List because it implements List interface
and Deque interfaces. only.
29

2. Stores 3 values (previous address, 2. Stores a single value in a single


data, and next address) in a single position.
position.
3. LinkedList internally uses a doubly 3. ArrayList internally uses a dynamic
linked list to store the elements. array to store the elements.
4. Whenever an element is added, prev 4. Whenever an elements id added, all
and next address are changed. elements after that position are
shifted.
5. To access an element, we need to 5. Can randomly access elements using
iterate from the beginning to the indexes.
element.
6. Manipulation with LinkedList is faster 6. Manipulation with ArrayList is slow
than ArrayList because it uses a doubly because it internally uses an array. If
linked list, so no bit shifting is required any element is removed from the
in memory. array, all the other elements are
shifted in memory.
7. LinkedList is better for manipulating 7. ArrayList is better for storing and
data. accessing data.
8. The location for the elements of a 8. The memory location for the elements
linked list is not contagious. of an ArrayList is contiguous.
30

What is JavaBean?
JavaBeans are basically POJOS (Plain Old Java Object), defined according to the
norms based on the software component model. JavaBeans is a portable, platform-
independent model written in Java Programming Language. Its components are
referred to as beans.
In simple terms, JavaBeans are classes which encapsulate several objects into a single
object. It helps in accessing these object from multiple places. JavaBeans contains several
elements like Constructors, Getter/Setter Methods and much more.

JavaBean Conventions
JavaBeans has several conventions that should be followed:
• Beans should have a default constructor(no arguments)
• It should provide methods to set and get the values of the properties, known as getter
and setter methods.
• A getter method is used to read the value of a readable property
• To update the value a setter method should be called.
• It should be Serializable Beans should implement java.io.serializable, as it
allows to save, store und restore the state of a JavaBean.

JavaBean Properties
1. getPropertyName()
This is called getter method.

For example, if the employee name is empName, the method name would be
getEmpName() to read that employee name. This method is known as an accessor.

Properties of getter methods are as follows:


• Must be public in nature.
• Return-type should not be void.
• The getter method should be prefixed with the word get.
• It should not take any argument
31

2. setPropertyName()
This method is known as a mutator.

For example if the employee name is empName, the method name would be
setEmpName() to write that employee name.

Properties of setter methods:


• Must be public in nature.
• Return-type should be void.
• The setter method has to be prefixed with the word set.
• It should take some argument.

Simple JavaBean Program

//program to show the JavaBean Example public


class Person
{
String firstName;
String lastName; int age;
public String getFirstName ()
{
return firstName;
}
public void setFirstName (String firstName)
{
this.firstName = firstName;
}
public String getLastName ()
{
return lastName;
}
public void setLastName (String lastName)
{
this.lastName =lastName;
}
public int getAge ()
32

{
return age;
}
public void setAge (int age)
{
this.age =age;
}
}

//program to Instantiating JavaBean Example public class CreateAJavaBean


public class CreateAJavaBean
{
public static void main (String[] args)
{
Person p = new Person(); p.setAge (20);
p.setFirstName ("Srikanth"); p.setLastName ("S");
System.out.println("Age=”+p.getAge());
System.out.println("First Name =” +p.getFirstName ());
System.out.println("Last Name=”+ p getLastName());
}
}

Advantages of JavaBean
 A Bean obtains all of the benefits of Java's "write once run anywhere" paradigm.
 The JavaBean properties and methods can be exposed to another application.
 The configuration settings of a Bean can be saved in a persistent storage and can be
restored at a later time.
 It provides an easiness to reuse the software components. A Bean may register to
receive events from other objects and can generate events that are sent to it.

Disadvantages of JavaBean
• JavaBeans are mutable. So, it can't take advantages of immutable objects.
• Having to create a getter for every property and a setter for many, most or all of
them, creates an immense amount of boilerplate code.
33

Introduction to Network Programming


The term network programming refers to writing programs that execute across multiple
devices (computers), in which the devices are all connected to each other using a
network.
The java.net package of the j2SE APIs contains a collection of classes and interfaces that
provide the low- level communication details, allowing us to write programs that focus
on solving the problem at hand.
The java.net package provides support for the two common Network Protocols:
1. TCP -TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications .TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.

2. UDP - UDP stands for User Datagram Protocol, a connection-less protocol that allows
for packets of data to be transmitted between applications.

Network programming is Client Server Programming: The process initiating the


communication is a client, and the process waiting for the communication to be initiated
is a server.

Network programming is Socket Programming


• The endpoint in an inter-process communication is called a socket or a network
socket.
• Since most communication between computers is based on the Internet Protocol, an
almost equivalent term is Internet socket.
• Application programs write to and read from these sockets. Therefore, network
programming is essentially Socket Programming.

Java Networking Basics Java TCP Networking Basics:


Typically a client opens a TCP/IP connection to a server. The client then starts to
communicate with the server. When the client is finished it closes the connection again.
Here is an illustration of that:
34

A client may send more than one request through an open connection. In fact, a client
can send as much data as the server is ready to receive. The server can also close the
connection if it wants to.
Java Networking Terminology
The widely used java networking terminologies are given below:
• IP Address
• Protocol
• Port Number
• MAC Address
• Connection-oriented and connection-less protocol
• Socket

Socket Programming
• Socket Programming refers to communication between two nodes or applications
running on different JRE (Java Runtime Environment). We use the socket
programming in Java to connect the client program with the server program, or
simply, connect a client and a server.
• Socket programming in Java can be either connection- oriented or connectionless.
The package java.net is used for socket programming in Java. There are two classes
in this package which are Socket class and ServerSocket class.
• When a client wants to open a TCP/IP connection to a server, it does so using a Java
Socket. The socket is told what IP address and TCP port to connect to and the rest is
done by java.
• The java Socket Programming has two sections.
(a) Java Server Socket Program
(b) Java Client Socket Program.
35

Methods in Socket Class

Methods Description
public void connect(SocketAddress This method connects the socket to
host, int timeout) throws the given input host.
IOException
public int getPort() This method returns the port through
which the socket is bound on the
remote machine.
public int getLocalPort() This method returns the port through
which the socket is bound on the local
machine.
public SocketAddress This method gives the address of the
getRemoteSocketAddress() remote socket.
public InputStream getInputStream() This method returns the input stream
throws IOException of the socket
Public void close() throws This method closes the socket. Closing
IOException the socket makes it no longer
available to connect it to any server.

Methods in ServerSocket Class

Methods Description
public int getLocalPort() This method returns the port on which
the server socket is listening to.
public Socket accept() throws It returns the socket and establishes a
IOException connection between the server and the
client.
public void setSoTimeout(int This method sets the time- out value for
timeout) how long the server socket has to wait for
a client during the accept() method.
public void bind (SocketAddress This method binds the socket to the
host, int backlog) specified server and port in the
SocketAddress object.
public synchronized void close() This method closes the object of the
ServerSocket class.
36

Client-Side Socket Programming


1. Creating a Socket
To create a Socket, we use the Socket class and create its object. We pass the IP
address and port number of the Server inside the Socket.
Here, we are using "localhost" because our server and the client applications are
present on the same machine.
For example:
Socket clientSocket =new Socket("localhost",6666);
We can also mention the IP address of the server if client and server are in different
machines.

2. Writing to a Socket
To write to a Java Socket we must obtain its OutputStream. Here is how that is done:
Socket clientSocket = new Socket("127.0.0.1", 5000);
OutputStream out= socket.getOutputStream();
Printwriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
out.println("Hello Server");

3. Reading from a Socket


To read from a Java Socket, we will need to obtains its InputStream. Here is how that
is done:
Socket clientSocket = new Socket("127.0.0.1”,5000);
BufferedReader in =new BufferedReader(new
InputStreamReader(clientSocket. getInputStream()));
String response = in.read();

4. Closing a Socket, InputStream and OutputStream


When we are done using a Java Socket, we must close it to close the connection to the
server. This is done by calling the Socket.close() method, like this:
clientSocket.close();
in.close();
out.close();
37

Server-Side Socket Programming


1. Creating a ServerSocket
Here is a simple code example that creates a ServerSocket that listens on port 6666;

ServerSocket serverSocket = new ServerSocket(6666);

2. Listening For Incoming Connections


In order to accept incoming connections we must call the ServerSocket.accept()
method. The accept() method returns a Socket which behaves like an ordinary Java
Socket. Here is how that looks:

ServerSocket serverSocket = new ServerSocket(6666);


boolean isStopped = false;
while(!isStopped)
{
Socket clientSocket = serverSocket.accept(); //do something
with clientSocket
}
Only one incoming connection is opened for each call to the accept() method.

3. Closing Client Sockets


Once a client request is finished, and no further requests will be received from that
client, we must close that Socket. This is done by calling:

clientSocket.close();

4. Closing Server Sockets:


Once the server is to shut down we need to close the ServerSocket. This is done by
calling:
serverSocket.close();

//Program Socket Side Code import java.io.*;


import java.net.*;
public class GreetServer
{
private ServerSocket serverSocket;
private Socket clientSocket;
38

private PrintWriter out;


private BufferedReader in;
public void start(int port)
{
try
{
serverSocket = new ServerSocket(port);
System out.println(" waiting for Client Message ");
clientSocket =serverSocket.accept();
System.out.println(" Connected with Client");
out = new PrintWriter(clientSocket.getOutputStream(),
true);
in = new BufferedReader(new InputStreamReader
(clientSocket.getInputStream()));
String clientName = in.readLine();
out.println("Hello Mr.”+ clientName + " .Thank you for
connecting.");
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
GreetServer server = new GreetServer();
server.start(6666);
}
}

//Program Client Side Code


import java.io.*;
import java.net.*;
public class GreetClient
{
39

private Socket clientSocket;


private Printwriter out;
private BufferedReader in;
public void startConnection(String ip, int port, String msg)
{
try
{
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(),
true);
in = new BufferedReader(newInputStreamReader
(clientSocket.getInputStream()));
out.println(msg);
String resp in.readLine();
System.out.println( “Server Response=”+resp);
in.close();
out.close();
clientSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
GreetClient client = new GreetClient();
client.startConnection("127.0.0.1", 6666, "Srikanth");
}
}

You might also like