UNIT-4 OOP Lecture Notes
UNIT-4 OOP Lecture Notes
Multi Threading in Java Types of tasking Two types of tasking 1.Single Tasking 2.Multi
Thread Tasking
➢Thread is a lightweight process. Single Tasking
➢A thread is a single flow of statements which are Performing single task at a time.
under execution. Multi Tasking
➢A thread is part of the It is the concurrent execution of multiple tasks over a
certain period of time.
program which can
perform a specific task. Multi Threading in Java
Multithreading in Java is a
process of executing multiple threads
simultaneously.
Java Multithreading is mostly used
in games,
animation, etc.
Advantages of Java Multithreading
1)It doesn't block the user because threads are independent,
and we can perform multiple operations at the same time.
2)We can perform many operations together, so it
saves time.
Program A well defined set of instructions 3)Threads are independent, so it doesn't affect other threads if
an exception occurs in a single thread.
Process Program under execution
Difference between Multi Threading and Multi Tasking
Syntax
Creation of Thread class A extends Thread
Threads can be created by using two {
public void run()
mechanisms :
{
1. Extending the Thread class …
2. Implementing the Runnable Interface ..
}
1.Thread creation by extends Thread class }
Steps
3.Write main class with main()
1.Write one class that extends Thread class
4.Create object to the class in step 1
Syntax Syntax
class keyword classname extends keyword Classname object=new operator Classname()
thread class
Ex: class A extends Thread 5.Using the created object in step 4 call the start method
Syntax
classobject.start()
Example for Creation of the Thread using extends Thread class
import java.io.*;
//Creation of Thread1
class A extends Thread
{
public void run()
{
for(int i=0;i<10;i++) Output
{
System.out.println("A Thread="+i); A Thread=0 A Thread=1 A Thread=2 A Thread=3 A Thread=4
} A Thread=5 A Thread=6 A Thread=7 A Thread=8 A Thread=9
}
}
//main class
class crthr
{
public static void main(String args[])
{
//create object to the class
A a1=new A();
//call the start method using created object a1.start();
}
}
Example for Creation of Multiple Threads using extends Thread class
import java.io.*; //main class
//Creation of Thread1
class A extends Thread class multhr
{ {
public void run() public static void main(String args[])
{
{
//create object to the classes
for(int i=0;i<10;i++)
A a1=new A(); B b1=new B();
{ //call the start method using created object
System.out.println("A Thread="+i); a1.start();
} b1.start();
} }
} }
//Creation of Thread2
class B extends Thread
{
public void run()
{
for(int j=0;j<10;j++)
{
System.out.println("B Thread="+j);
}
}
}
Output
B Thread=0 A Thread=0 B Thread=1 A Thread=1 B
Thread=2 A Thread=2 B Thread=3 A Thread=3 B
Thread=4 A Thread=4 B Thread=5 A Thread=5 B
Thread=6 A Thread=6 B Thread=7 A Thread=7 B
Thread=8 A Thread=8 B Thread=9 A Thread=9
2.Thread creation by using implements
Runnable interface
Steps 3.Write main class with main()
1.Write one class that implements Runnable interface 4.Create object to the class in step 1
Syntax
Syntax Classname object=new operator Classname()
Class keyword classname implements Runnable Ex: Class A
implements Runnable 5.Create object to the Thread class and attach class object in
step4
2.Inside the class it have one method name as public void Thread class object=new operator Thread class(class
run() object);
Syntax
Class A implements Runnable
{ 6.Using the created object in step 5 call the start
public void run() method
{
… Syntax
.. threadobject.start()
}
}
Example for Creation of the Thread using implements Runnable interface
import java.io.*;
class A implements Runnable
{
public void run()
{
for(int i=0;i<10;i++)
{ Output
System.out.println("A Thread="+i);
} A Thread=0 A Thread=1 A Thread=2 A Thread=3 A Thread=4
} A Thread=5 A Thread=6 A Thread=7 A Thread=8 A Thread=9
}
class crthr1
{
public static void main(String args[])
{
}
}
Example for Creation of Multiple Threads using implements Runnable interface
import java.io.*;
//Creation of Thread1 //main class
class A extends Thread
{ class multhr1
public void run() {
{ public static void main(String args[])
for(int i=0;i<10;i++) {
{ //create object to the classes
System.out.println("A Thread="+i); A a1=new A();
} B b1=new B();
} //create objects to Thread class Thread t1=new Thread(a1);
} Thread t2=new Thread(b1);
//Creation of Thread2 //call the start method using created thread objects
t1.start();
class B extends Thread
t2.start();
{
}
public void run()
}
{
for(int j=0;j<10;j++)
{
System.out.println("B Thread="+j);
}
}
}
Output
B Thread=0 A Thread=0 B Thread=1 A Thread=1 B
Thread=2 A Thread=2 B Thread=3 A Thread=3 B
Thread=4 A Thread=4 B Thread=5 A Thread=5 B
Thread=6 A Thread=6 B Thread=7 A Thread=7 B
Thread=8 A Thread=8 B Thread=9 A Thread=9
Thread Life Cycle
.getName());
J a v a Thread Method
.getPriority());
J a v a Thread Method – Naming a thread
J a v a Thread Method
J a v a Thread Method
J a v a Thread Method
11. public final boolean isAlive()
public class JavaIsAliveExp extends Thread
{
public void run()
{
try
{
Thread.sleep(300);
System.out.println("is run() method isAlive "+Thread.currentThread().isAlive());
}
catch (InterruptedException ie) {
}
}
public static void main(String[] args)
{
JavaIsAliveExp thread1 = new JavaIsAliveExp(); System.out.println("before starting
thread isAlive: "+thread1.isAlive()); thread1.start();
System.out.println("after starting thread isAlive: "+thread1.isAlive());
}
}
J a v a Thread Method
E x amples
1.Creates three threads in which First thread displays “Good Morning” every one second,
the Second thread displays “Hello” every two seconds and the third thread displays
“Welcome” every three seconds.
2.Develop a java program that implements a multi-threaded program, which has three
threads. First thread generates a random integer for every 1 second, if the generated
integer is even the second thread computes the square of the number and print it. If the
generated integer is odd the third thread will print the value of cube of the number.
Daemon Thread
➢ Daemon thread in J av a is also a service provider thread that provides services to the user thread.
when all the user threads die, J V M terminates this thread automatically.
➢ Daemon thread in J av a is a low-priority thread that runs in the background to perform tasks
➢ If J V M finds a running daemon thread, it terminates the thread an d, after that, shutdown it.
➢ They can not prevent the J V M from exiting when all the user threads finish their execution.
Note: Whenever the last non-daemon thread terminates, all the daemon threads will be terminated
automatically.
Methods of Daemon Thread
1. void setDaemon(boolean status):
This method marks the current thread as a daemon thread or user thread.
For example, if I have a user thread tU then tU.setDaemon(true) would make it a Daemon thread.
O n the other hand, if I have a Daemon thread tD then calling tD.setDaemon(false) would make it
a user thread.
2. boolean isDaemon():
This method is used to check that the current thread is a daemon. It returns true if the thread is Daemon. Else, it
returns false.
public class DaemonThread extends Thread public static void main(String[] args)
{ {
➢ Create an object under ExecutorService and pass the parameter as the number of threads created in a pool
➢ Pass the Task objects to the pool to execute. ( use execute() method)
2. newCachedThreadPool(): Creates a thread pool that creates new threads as needed but will
Note: In case of a fixed thread pool, if all threads are being currently run by the executor, then the
pending tasks are placed in a queue and are executed when a thread becomes idle.
Example - Thread Pool
Date d = new Date();
SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss");
import java.text.SimpleDateFormat; import
java.util.Date; System.out.println("Initialization Time for - " + name + " = "
import java.util.concurrent.ExecutorService; +ft.format(d));
import java.util.concurrent.Executors; //prints the initialization time for every task
}
class Task implements Runnable else
/ / Task class to be executed (Step 1) {
{ Date d = new Date();
String name; SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss");
Task(String s)
{ S ystem .out . println("Executing Time for - "+ name +" = "
name = s; +ft.format(d));
} / / prints the execution time for every task
public void run() }
{ Thread.sleep(1000);
try }
{ System.out.println(name+" complete");
for (int i = 0; i<=3; i++) }
{ catch(InterruptedException e)
if (i==0) {
{ e.printStackTrace();
}
} }
Example - Thread Pool
public class Test_pool
{
static final int MAX_T = 3; / / Maximum number of threads in thread pool
/ / creates a thread pool with MAX_T no. of threads as the fixed pool size (Step 2)
are trying to use the object at the same time. to get to the same resource.
➢ To achieve this Thread Synchronization, we must use 2. It can even create an unexpected outcome because of
Mutual Exclusive :
1. Synchronized Method
2. Synchronized Block
3. Static Synchronization
Understanding the problem without synchronization
public class Sync_exam implements Runnable
public void run ()
{
{
int tickets = 3;
String name= Thread.currentThread().getName ();
public void bookticket (String name, int
if (name.equals ("t1"))
wantedtickets)
{
{
bookticket (name, 1);
if (wantedtickets <= tickets)
}
{
System.out.println (wantedtickets + "
booked to " + name); else if (name.equals ("t2"))
tickets = tickets - wantedtickets; {
} bookticket (name, 2);
}
else
{ else
System.out.println ("No tickets to book {
for" + name); bookticket (name, 3);
} }
} }
Understanding the problem without synchronization
t1.setName ("t1");
t2.setName ("t2");
t3.setName ("t3");
t1.start ();
t2.start (); In above, objects of class Sync_exam is shared by all the three running
t3.start ();
threads(t1, t2, and t3) to call the shared method(void bookticket).
}
} Hence the result is non-synchronized and such a situation is called a “Race
condition”.
I . Synchronized Method
II. Synchronized Block
➢ In simple words, a static synchronized method will lock the class instead of the
object, and it will lock the class because the keyword static means: “class instead
of instance”.
➢ The keyword synchronized means that only one thread can access the method
at a time.
➢ And static synchronized mean: Only one thread can access the class at one
time.
Example with Static Synchronization
➢ It is a mechanism of communication between two threads or multiple threads that acts on the
➢ For example, online video player, audio player, etc. In both types of players generally, there are two
➢ Buffer Thread is responsible to download content from the server into a buffer memory and
whereas playing thread is responsible to play content and these actions will be done based on
1. wait(): This method is used to make the Thread wait until it gets a notification. This method pauses the current thread to the
waiting room dynamically.
2. notify(): This method is used to send the notification to one of the waiting thread so that thread enters running state and
execute the remaining task.
This method wakeup a single thread into the active state (that acts on the common object).
3. notifyAll(): This method is used to send the notification to all the waiting threads so that all thread enters running state and
execute simultaneously.
This method wakes up all the waiting threads that act on the common objects.
Note:
➢ We must call wait(), notify() and notifyAll() methods inside the synchronized blocks or synchronized methods, otherwise it
will throw a Runtime Exception called IllegalMonitorStateException.
➢ By using these methods, we can resolve problems like Producer-Consumer Problem.
Process of Inter Thread Communication
notify(); }
} }
Producer-Consumer solution using threads
class Producer extends Thread{ class Consumer extends Thread{
Buffer b; Buffer b;
public Producer(Buffer b){ public Consumer(Buffer b){
this.b = b; this.b = b;
} }
//starting threads.
p.start();
c.start();
}
}
Unit- 4 – Collection Framework
Java Collection :
➢ Java collections refer to a collection of
▪ Interfaces: Interfaces are the reference
individual objects that are represented as a
types which are like classes but contains
single unit.
only abstract methods.
➢ Can perform all operations such as searching,
▪ They allow Java collections to be manipulated
sorting, insertion, manipulation, deletion, etc.,
independently from the details of their
on Java collections just like doing it on data.
representation. Also, they form a hierarchy in
What is a Java Collection Framework?
OOPs languages.
➢ A Java collection framework provides an
architecture to store and manipulate a group
▪ Classes: Classes in Java are the
of objects.
implementation of the collection interface.
➢ A Java collection framework includes the
▪ It basically refers to the data structures
following:
that are used again and again.
▪ Interfaces
▪ Classes
▪ Algorithm 1
Why use Java collection?
There are several benefits of using Java
collections such as:
▪ Algorithm: Algorithm refers to the methods
▪ Reducing the effort required to write the code
which are used to perform operations such as
by providing useful data structures and
searching and sorting, on objects that
algorithms.
implement collection interfaces.
▪ Java collections provide high-performance and
high-quality data structures and algorithms
▪ Algorithms are polymorphic in nature as the
thereby increasing the speed and quality.
same method can be used to take many
▪ Unrelated APIs can pass collection interfaces
forms or you can say perform different
back and forth.
implementations of the Java collection
▪ Decreases extra effort required to learn, use,
interface.
and design new API’s.
▪ Supports reusability of standard data
structures and algorithms.
2
Collection Framework Hierarchy
Java collection framework includes interfaces and classes.
3
Java Collection : Interface
4
Java Collection : Interface
Iterator interface :
▪ Iterator is an interface that iterates the elements.
▪ It is used to traverse the list and modify the elements.
▪ Iterator interface has three methods which are mentioned below:
1. public boolean hasNext() – This method returns true if the iterator has
more elements.
2. public object next() – It returns the element and moves the cursor
pointer to the next element.
3. public void remove() – This method removes the last elements returned
by the iterator.
5
Java Collection : List
There are three components that extend the Collection interface i.e List, Queue and
Sets.
6
ArrayList
➢ ArrayList is the implementation of List Interface where the elements can be dynamically added or
removed from the list.
➢ Also, the size of the list is increased dynamically if the elements are added more than the initial
size.
➢ Syntax: ArrayList object = new ArrayList ();
ArrayList Vs Array
➢ In Java, we need to declare the size of an array before we can use it. Once the size of an array is
declared, it's hard to change it.
➢ To handle this issue, we can use the ArrayList class.
➢ It allows us to create resizable arrays.
➢ Unlike arrays, ArrayList can automatically adjust
its capacity when we add or remove elements from it.
7
ArrayList
8
ArrayList
Create ArrayList in Java:
➢ ArrayList<Type> arrayList= new ArrayList<>();
Here, Type indicates the type of an arraylist. For Basic Operations on ArrayList
example, The ArrayList class provides various methods to
// create Integer type arraylist perform different operations on ArrayList.
ArrayList<Integer> arrayList = new ArrayList<>();
12
LinkedList
➢ Linked List is a sequence of links which contains items. Each link contains a connection to
another link. Java Linked List class uses two types of Linked list to store the elements:
Syntax: Linkedlist object = new Linkedlist();
Singly Linked List: In a singly Linked list each Doubly Linked List: In a doubly Linked list, it
node in this list stores the data of the node and has two references, one to the next node and
a pointer or reference to the next node in the another to previous node.
list.
13
LinkedList
boolean contains(Object o) Returns true if this list contains the specified element.
boolean remove(Object o) Removes the first occurrence of the specified element from this list.
import java.util.*;
public class LinkedlistExample{
public static void main(String args[]){
LinkedList<String>al=new
LinkedList<String>();// creating linked list
The output of the above program would be:
al.add("Rachit"); // adding elements
al.add("Rahul");
Rachit
al.add("Rajat");
Rahul
Iterator<String> itr = al.iterator();
Rajat
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
16
Vector
➢ Vectors are similar to arrays, where the elements of the vector object can be accessed via an index
into the vector.
➢ Vector implements a dynamic array. Also, the vector is not limited to a specific size, it can shrink
or grow automatically whenever required.
➢ It is similar to ArrayList, but with two differences :
▪ Vector is synchronized.
▪ Vector contains many legacy methods that are not part of the collection's framework.
▪ Syntax: Vector object = new Vector(size,increment);
17
Vector
Note: It is recommended to use ArrayList in place of Vector because vectors less efficient.
18
Vector
19
Methods of Vector
20
Methods of Vector
21
Methods of Vector
22
9b. Develop a java program to perform all the operations in Collection interface.
import java.util.*;
public class CollectionOperationsExample { public
// Check if the collection is empty
static void main(String[] args) {
System.out.println("Is Collection empty? " +
// Create a collection (ArrayList in this case)
myCollection.isEmpty());
Collection<String> myCollection = new
// Removing an element
ArrayList<>();
myCollection.remove("C++");
// Adding elements to the collection
System.out.println("Collection after removing
myCollection.add("Java");
'C++': " + myCollection);
myCollection.add("Python");
// Checking if the collection contains an element
myCollection.add("C++");
System.out.println("Does Collection contain
myCollection.add("JavaScript");
'Java'? " + myCollection.contains("Java"));
// Displaying the elements in the collection
// Clearing the collection
System.out.println("Original Collection: " +
myCollection.clear();
myCollection);
System.out.println("Collection after clearing:
// Size of the collection
" + myCollection);
System.out.println("Size of Collection: " +
myCollection.size()); 23
9b. Develop a java program to perform all the operations in Collection interface.
// Add elements to the cleared collection
myCollection.add("HTML");
myCollection.add("CSS");
System.out.println("Collection after adding new elements: " + myCollection);
// Convert the collection to an array
String[] array = myCollection.toArray(new String[0]);
System.out.println("Array from Collection: " + Arrays.toString(array));
}
}
24
Stack Class
import java.util.Stack;
public class StackEmptyMethodExample
{
//prints elements of the stack
public static void main(String[] args)
System.out.println("Elements in Stack: " + stk);
{
result = stk.empty();
//creating an instance of Stack class
System.out.println("Is the stack empty? " + result);
Stack<Integer> stk= new Stack<>();
}
// checking stack is empty or not
}
boolean result = stk.empty();
Output:
System.out.println("Is the stack empty? " + result);
Is the stack empty? true
// pushing elements into stack
Elements in Stack: [78, 113, 90, 120]
stk.push(78);
Is the stack empty? false
stk.push(113);
stk.push(90);
stk.push(120);
26
Stack Class – Example-2
Output:
stack: []
push -> 20
//performing pop operation
stack: [20]
static void popelmnt(Stack stk) push -> 13
stack: [20, 13]
{
push -> 89
System.out.print("pop -> "); stack: [20, 13, 89]
push -> 90
//invoking pop() method
stack: [20, 13, 89, 90]
Integer x = (Integer) stk.pop(); push -> 11
stack: [20, 13, 89, 90, 11]
System.out.println(x);
push -> 45
//prints modified stack stack: [20, 13, 89, 90, 11, 45]
push -> 18
System.out.println("stack: " + stk);
stack: [20, 13, 89, 90, 11, 45, 18]
} pop -> 18
stack: [20, 13, 89, 90, 11, 45]
}
pop -> 45
stack: [20, 13, 89, 90, 11]
pop -> 11
stack: [20, 13, 89, 90]
28
Queue Interface
➢ The Queue interface of the Java collections framework provides the functionality of the queue
data structure. It extends the Collection interface.
➢ Since the Queue is an interface, we cannot provide the direct implementation of it.
➢ To use the functionalities of Queue, we need to use classes that implement it:
How to use Queue?
➢ We must import java.util.Queue
29
Queue Interface
30
Queue Interface Example
31
Set Interface
▪ Set also extends Collection, but it prohibits duplicate items (this is what
defines a Set).
▪ No new methods are introduced; specifically, none for index-based
operations (elements of Sets are not ordered).
▪ More formally, sets contain no pair of elements e1 and e2 such that
e1.equals(e2), and at most one null element.
▪ Java has two implementations:
➢ HashSet
➢ TreeSet
32
Using Sets to find duplicate elements
import java.util.*;
public class FindDups
{
public static void main(String[] args)
{
Set<String> s = new HashSet<String>();
for (String a : args)
if (!s.add(a))
System.out.println("Duplicate detected: " + a);
System.out.println(s.size() + " distinct words: " + s);
}}
33
HashSets and hash tables
▪ Lists allow for ordered elements but searching them is very slow.
▪ Hash tables let you do this. Drawback is that you have no control over how elements are ordered.
HashSet Class
▪ Hashing can be used to implement several important data structures.
37
Map methods
▪ Here is a list of the Map methods:
Method Description
To remove all the elements or mappings from a specified Map
void clear()
collection.
- boolean To check whether a particular key is being mapped into the
containsKey(Object) Map or not
boolean To check whether a particular value is being mapped by a
containsValue(Object) single or more than one key in the Map
To create a set out of the same elements contained in the map.
Set entrySet() It basically returns a set view of the map, or we can create a
new set and store the map elements into them.
This method is used to retrieve or fetch the value mapped by a
boolean get(Object)
particular key mentioned in the parameter.
This method is used to check if a map is having any entry for
boolean isEmpty()
key and value pairs.
This method is used in Map Interface to return a Set view of
Set keySet()
the keys contained in this map.
38
Map methods (Cont..)
Method Description
Object put(Object, This method is used to associate the specified value with the
Object) specified key in this map.
void putall(Map) To copy all the mappings from the specified map to this map.
Used to remove the mapping for a key from this map if it is
Object remove(Object)
present in the map.
This method is used to return the number of key/value pairs
int size()
available in the map.
39
Prog. 10b. Develop a java program to implement and perform all the operations in
Map interface.
import java.util.HashMap;
import java.util.Map; // Accessing values using keys
public class MapExample { System.out.println("Value for key '" + key + "': " +
Map<String, Integer> myMap = new HashMap<>(); System.out.println("Does map contain key 'Five'?
// Iterating through the key-value pairs Map after removing key 'Three': {One=1, Four=4,
myMap.entrySet()) { One
entry.getValue()); Two
41
THANK YOU
42