Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views59 pages

TY BCA Advanced Java Notes

Uploaded by

priyankadeore222
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views59 pages

TY BCA Advanced Java Notes

Uploaded by

priyankadeore222
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

B.C.A.: 2024-2025 Autonomous T.Y. B.C.A.

(Science)

INDEX

Unit Unit Name Page No.

1. Collection 2-35

2. Multithreading 36-51

3. Database Programming 52-

4. Servlet and JSP

5. Applet

6. Spring Framework

7. Java Networking

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 1


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Unit 1: Collections

Introducing to Collections framework


 The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.
 Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
 Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java?


 It provides readymade architecture.
 It represents a set of classes and interfaces.
 It is optional.

What is Collection framework


The Collection framework represents a unified architecture for storing and manipulating a group of
objects. It has:
 Interfaces: These are abstract data types that represent collections. Interfaces allow collections to
be manipulated independently of the details of their representation. In object-oriented languages,
interfaces generally form a hierarchy.
 Implementations: These are the concrete implementations of the collection interfaces. In essence,
they are reusable data structures.
 Algorithms: These are the methods that perform useful computations, such as searching and
sorting, on objects that implement collection interfaces. The algorithms are said to
be polymorphic: that is, the same method can be used on many different implementations of the
appropriate collection interface. In essence, algorithms are reusable functionality.

Collection Interface
 The Collection interface is the interface which is implemented by all the classes in the collection
framework. It declares the methods that every collection will have. In other words, we can say that
the Collection interface builds the foundation on which the collection framework depends.

Collections Framework Vs. Collection Interface


 The Collection interface is the root interface of the collections framework. The framework
includes other interfaces as well: Map and Iterator. These interfaces may also have sub interfaces

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 2


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Benefits of the Java Collections Framework


 Reusability: Java Collections Framework provides common classes and utility methods than can
be used with different types of collections. This promotes the reusability of the code. A developer
does not have to re-invent the wheel by writing the same method again.
 Quality: Using Java Collection Framework improves the program quality, since the code is
already tested and used by thousands of developers.
 Speed: Most of programmer’s report that their development speed increased since they can focus
on core logic and use the generic collections provided by Java framework.
 Maintenance: Since most of the Java Collections framework code is open source and API
documents is widely available, it is easy to maintain the code written with the help of Java
Collections framework. One developer can easily pick the code of previous developer.
 Reduces effort to design new APIs: This is the flip side of the previous advantage. Designers
and implementers don't have to reinvent the wheel each time they create an API that relies on
collections; instead, they can use standard collection interfaces.
 Fosters software reuse: New data structures that conform to the standard collection interfaces are
by nature reusable. The same goes for new algorithms that operate on objects that implement these
interfaces.

Hierarchy of Collection Framework


The java.util package contains all the classes and interfaces for the Collection framework.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 3


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Methods of Collection interface

Method Description

public boolean add(E e) It is used to insert an element in this collection.

public boolean addAll(Collection<? It is used to insert the specified collection elements in the
extends E> c) invoking collection.

public boolean remove(Object element) It is used to delete an element from the collection.

public boolean removeAll(Collection<?> It is used to delete all the elements of the specified
c) collection from the invoking collection.

default boolean removeIf(Predicate<? It is used to delete all the elements of the collection that
super E> filter) satisfy the specified predicate.

public boolean retainAll(Collection<?> It is used to delete all the elements of invoking collection
c) except the specified collection.

public int size() It returns the total number of elements in the collection.

public void clear() It removes the total number of elements from the
collection.

public boolean contains(Object element) It is used to search an element.

Public boolean It is used to search the specified collection in the collection.


containsAll(Collection<?> c)

public Iterator iterator() It returns an iterator.

public Object[] toArray() It converts collection into array.

public <T> T[] toArray(T[] a) It converts collection into array.

public boolean isEmpty() It checks if collection is empty.

default Stream<E> parallelStream() It returns a possibly parallel Stream with the collection as
its source.

default Stream<E> stream() It returns a sequential Stream with the collection as its
source.

default Spliterator<E> spliterator() It generates a Spliterator over the specified elements in the
collection.

public boolean equals(Object element) It matches two collections.

public int hashCode() It returns the hash code number of the collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 4


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Methods of Iterator interface - There are only three methods in the Iterator interface

Method Description

Public boolean hasNext() It returns true if the iterator has more elements otherwise it returns false.

public Object next() It returns the element and moves the cursor pointer to the next element.

public void remove() It removes the last elements returned by the iterator. It is less used.

Iterable Interface
 The Iterable interface is the root interface for all the collection classes.
 The Collection interface extends the Iterable interface and therefore all the subclasses of
Collection interface also implement the Iterable interface.
 It contains only one abstract method. i.e., Iterator<T> iterator()
 It returns the iterator over the elements of type T.

Ways to iterate the elements of the collection in Java


There are various ways to traverse the collection elements:
1. By Iterator interface, ListIterator interface.
2. By for-each loop, for loop
3. By forEach() method, forEachRemaining() method.

Java List Interface


 List interface is the child interface of Collection interface.
 It inhibits a list type data structure in which we can store the ordered collection of objects. It can
have duplicate values.
 List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

Java ArrayList Class


 Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there
is no size limit. We can add or remove elements anytime. So, it is much more flexible than the
traditional array. It is found in the java.util package. It is like the Vector in C++.
 The ArrayList in Java can have the duplicate elements also. It implements the List interface so we
can use all the methods of the List interface here. The ArrayList maintains the insertion order
internally.
 It inherits the AbstractList class and implements List interface.
 It maintains insertion order and it is non synchronized.
 It allows random access because the array works on an index basis.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 5


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

 In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot of shifting
needs to occur if any element is removed from the array list.
 We cannot create an array list of the primitive types, such as int, float, char, etc. It is required to
use the required wrapper class in such cases. For example:
 ArrayList<int> al = ArrayList<int>(); // does not work
 ArrayList<Integer> al = new ArrayList<Integer>(); // works fine

 It gets initialized by the size. The size is dynamic in the array list, which varies according to the
elements getting added or removed from the list.

Constructors of ArrayList

Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection<? extends It is used to build an array list that is initialized with the
E> c) elements of the collection c.

ArrayList(int capacity) It is used to build an array list that has the specified initial
capacity.

Methods of ArrayList

Method Description

void add(int index, E element) It is used to insert the element at the specified position in a list.

boolean add(E e) It is used to append the specified element at the end of a list.

boolean addAll(Collection<? It is used to append all of the elements in the specified collection
extends E> c) to the end of this list, in the order that they are returned by the
specified collection's iterator.

boolean addAll(int index, It is used to append all the elements in the specified collection,
Collection<? extends E> c) starting at the specified position of the list.

void clear() It is used to remove all of the elements from this list.

void ensureCapacity(int rc) It is used to enhance the capacity of an ArrayList instance.

E get(int index) Used to fetch the element from the particular position of the list.

boolean isEmpty() It returns true if the list is empty, otherwise false.

int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of
the specified element, or -1 if the list does not contain this
element.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 6


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Object[] toArray() It is used to return an array containing all of the elements in this
list in the correct order.

<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in this
list in the correct order.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean contains(Object o) It returns true if the list contains the specified element.

int indexOf(Object o) It is used to return the index in this list of the first occurrence of
the specified element, or -1 if the List does not contain this
element.

E remove(int index) used to remove element present at the specified position in the
list.

boolean remove(Object o) It is used to remove the first occurrence of the specified element.

boolean removeAll(Collection<?> It is used to remove all the elements from the list.
c)

boolean removeIf(Predicate<? It is used to remove all the elements from the list that satisfies
super E> filter) the given predicate.

protected void removeRange(int It is used to remove all the elements lies within the given range.
fromIndex, int toIndex)

void replaceAll It is used to replace all the elements from the list with the
(UnaryOperator<E> operator) specified element.

void retainAll(Collection<?> c) Used to retain all elements in the list that are present in the
specified collection.

E set(int index, E element) It is used to replace the specified element in the list, present at
the specified position.

void sort(Comparator<? super E> It is used to sort the elements of the list on the basis of the
c) specified comparator.

Spliterator<E> spliterator() It is used to create a spliterator over the elements in a list.

List<E> subList(int from, int to) It is used to fetch all the elements that lies within the given range.

int size() It is used to return the number of elements present in the list.

void trimToSize() It is used to trim the capacity of this ArrayList instance to be the
list's current size.

Example of ArrayList:
import java.util.*;
public class ArrayList1{
public static void main(String args[]){

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 7


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

ArrayList<String> list=new ArrayList<String>();//Creating arraylist


list.add("Mango"); //Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing element & move next
} } }

Java LinkedList Class


 Java LinkedList class uses a doubly linked list to store the elements.
 It provides a linked-list data structure. It inherits the AbstractList class and implements List and
Deque interfaces. It can be used as a list, stack or queue.
 It can contain duplicate elements, maintain insertion order and it is non synchronized.
 Its manipulation is fast because no shifting needs to occur.
Constructors of Java LinkedList

Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collection<? It is used to construct a list containing the elements of the specified


extends E> c) collection, in the order, they are returned by the collection's iterator.

Methods of Java LinkedList

Method Description

boolean add(E e) It is used to append the specified element to the end of a list.

void add(int index, E element) It is used to insert the specified element at the specified position
index in a list.

Object clone() It is used to return a shallow copy of an ArrayList.

void clear() It is used to remove all the elements from a list.

boolean addAll(Collection<? It is used to append all of the elements in the specified collection to
extends E> c) the end of this list, in the order that they are returned by the specified
collection's iterator.

boolean addAll(Collection<? It is used to append all of the elements in the specified collection to
extends E> c) the end of this list, in the order that they are returned by the specified
collection's iterator.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 8


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

boolean addAll(int index, It is used to append all the elements in the specified collection,
Collection<? extends E> c) starting at the specified position of the list.

void addFirst(E e) It is used to insert the given element at the beginning of a list.

void addLast(E e) It is used to append the given element to the end of a list.

boolean contains(Object o) It is used to return true if a list contains a specified element.

Iterator<E> It is used to return an iterator over the elements in a deque in reverse


descendingIterator() sequential order.

E element() It is used to retrieve the first element of a list.

E get(int index) It is used to return the element at the specified position in a list.

E getFirst() It is used to return the first element in a list.

E getLast() It is used to return the last element in a list.

int indexOf(Object o) It is used to return the index in a list of the first occurrence of the
specified element, or -1 if the list does not contain any element.

int lastIndexOf(Object o) It is used to return the index in a list of the last occurrence of the
specified element, or -1 if the list does not contain any element.

ListIterator<E> listIterator(int It is used to return a list-iterator of the elements in proper sequence,


index) starting at the specified position in the list.

boolean offer(E e) It adds the specified element as the last element of a list.

boolean offerFirst(E e) It inserts the specified element at the front of a list.

boolean offerLast(E e) It inserts the specified element at the end of a list.

E peek() It retrieves the first element of a list

E peekFirst() It retrieves the first element of a list or returns null if a list is empty.

E peekLast() It retrieves the last element of a list or returns null if a list is empty.

E poll() It retrieves and removes the first element of a list.

E pollFirst() It retrieves and removes the first element of a list, or returns null if
a list is empty.

E pollLast() It retrieves and removes the last element of a list, or returns null if
a list is empty.

E pop() It pops an element from the stack represented by a list.

void push(E e) It pushes an element onto the stack represented by a list.

E remove() It is used to retrieve and removes the first element of a list.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 9


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

E remove(int index) It is used to remove the element at the specified position in a list.

boolean remove(Object o) It is used to remove the first occurrence of the specified element in
a list.

E removeFirst() It removes and returns the first element from a list.

boolean It is used to remove the first occurrence of the specified element in


removeFirstOccurrence(Object a list (when traversing the list from head to tail).
o)

E removeLast() It removes and returns the last element from a list.

boolean It removes the last occurrence of the specified element in a list


removeLastOccurrence(Object (when traversing the list from head to tail).
o)

E set(int index, E element) It replaces the element at the specified position in a list with the
specified element.

Object[] toArray() It is used to return an array containing all the elements in a list in
proper sequence (from first to the last element).

<T> T[] toArray(T[] a) It returns an array containing all the elements in the proper sequence
(from first to the last element); the runtime type of the returned
array is that of the specified array.

int size() It is used to return the number of elements in a list.

Example of LinkedList:
import java.util.*;
public class LinkedList1{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("TY");
al.add("SY");
al.add("TY");
al.add("FY");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }

Difference Between ArrayList and LinkedList


ArrayList and LinkedList both implement the List interface and maintain insertion order. Both are non-
synchronized classes.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 10


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

ArrayList LinkedList

1) ArrayList internally uses a dynamic array to LinkedList internally uses a doubly linked list to
store the elements. store the elements.

2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than
internally uses an array. If any element is ArrayList because it uses a doubly linked list, so
removed from the array, all the other elements are no bit shifting is required in memory.
shifted in memory.

3) An ArrayList class can act as a list only LinkedList class can act as a list and queue both
because it implements List only. because it implements List and Deque interfaces.

4) ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.

5) The memory location for the elements of an The location for the elements of a linked list is
ArrayList is contiguous. not contagious.

6) Generally, when an ArrayList is initialized, a There is no case of default capacity in a


default capacity of 10 is assigned to the LinkedList. In LinkedList, an empty list is
ArrayList. created when a LinkedList is initialized.

Java List vs ArrayList/LinkedList


List is an interface whereas ArrayList/LinkedList is the implementation class of List.

How to create List


The ArrayList and LinkedList classes provide the implementation of List interface.
import java.util.*;
public class ListExample1{
public static void main(String args[]){
List<String> list=new ArrayList<String>();
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
for(String fruit:list)
System.out.println(fruit);
} }
How to convert Array to List
We can convert the Array to List by traversing the array and adding the element in list one by one using
list.add() method.
import java.util.*;
public class ArrayToListExample{

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 11


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

public static void main(String args[]){


String[] array={"Java","Python","PHP","C++"};
System.out.println("Printing Array: "+Arrays.toString(array));
List<String> list=new ArrayList<String>();
for(String lang:array){
list.add(lang);
} System.out.println("Printing List: "+list);
}}

Java Vector Class


 Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-
number of elements in it as there is no size limit. It is a part of Java Collection framework since
Java 1.2. It is found in the java.util package and implements the List interface, so we can use all
the methods of List interface here.
 It is recommended to use the Vector class in the thread-safe implementation only. If you don't
need to use the thread-safe implementation, you should use the ArrayList, the ArrayList will
perform better in such case.
 The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it fails
and throws the ConcurrentModificationException.
 It is similar to the ArrayList, but with two differences-
o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a collections framework.

Java Vector Constructors

Constructor Description

vector() It constructs an empty vector with the default size as 10.

vector(int initialCapacity) It constructs an empty vector with the specified initial


capacity and with its capacity increment equal to zero.

vector(int initialCapacity, int It constructs an empty vector with the specified initial
capacityIncrement) capacity and capacity increment.

Vector(Collection<? Extends E> It constructs a vector that contains the elements of a


c) collection c.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 12


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Java Vector Methods

Method Description

add() It is used to append the specified element in the given vector.

addAll() It is used to append all of the elements in the specified collection to the end of
this Vector.

addElement() It is used to append the specified component to the end of this vector. It
increases the vector size by one.

capacity() It is used to get the current capacity of this vector.

clear() It is used to delete all of the elements from this vector.

clone() It returns a clone of this vector.

contains() It returns true if the vector contains the specified element.

containsAll() It returns true if the vector contains all of the elements in the specified
collection.

copyInto() It is used to copy the components of the vector into the specified array.

elementAt() It is used to get the component at the specified index.

elements() It returns an enumeration of the components of a vector.

trimToSize() It is used to trim the capacity of the vector to the vector's current size.

equals() It is used to compare the specified object with the vector for equality.

firstElement() It is used to get the first component of the vector.

forEach() It is used to perform the given action for each element of the Iterable until all
elements have been processed or the action throws an exception.

get() It is used to get an element at the specified position in the vector.

hashCode() It is used to get the hash code value of a vector.

indexOf() It is used to get the index of the first occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.

insertElementAt() It is used to insert the specified object as a component in the given vector at
the specified index.

isEmpty() It is used to check if this vector has no components.

iterator() It is used to get an iterator over the elements in the list in proper sequence.

lastElement() It is used to get the last component of the vector.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 13


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

lastIndexOf() It is used to get the index of the last occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.

listIterator() It is used to get a list iterator over the elements in the list in proper sequence.

remove() It is used to remove the specified element from the vector. If the vector does
not contain the element, it is unchanged.

removeAll() It is used to delete all the elements from the vector that are present in the
specified collection.

removeAllElements() It is used to remove all elements from the vector and set the size of the vector
to zero.

removeElement() It is used to remove the first (lowest-indexed) occurrence of the argument from
the vector.

removeElementAt() It is used to delete the component at the specified index.

removeIf() It is used to remove all of the elements of the collection that satisfy the given
predicate.

removeRange() It is used to delete all of the elements from the vector whose index is between
fromIndex, inclusive and toIndex, exclusive.

replaceAll() It is used to replace each element of the list with the result of applying the
operator to that element.

retainAll() It is used to retain only that element in the vector which is contained in the
specified collection.

set() It is used to replace the element at the specified position in the vector with the
specified element.

setElementAt() It is used to set the component at the specified index of the vector to the
specified object.

setSize() It is used to set the size of the given vector.

size() It is used to get the number of components in the given vector.

sort() It is used to sort the list according to the order induced by the specified
Comparator.

spliterator() used to create a late-binding and fail-fast Spliterator over the elements in the
list.

subList() It is used to get a view of the portion of the list between fromIndex, inclusive,
and toIndex, exclusive.

toArray() used to get an array containing all of the elements in this vector in correct order.

toString() It is used to get a string representation of the vector.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 14


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Example

import java.util.*;
public class VectorExample {
public static void main(String args[]) {
Vector<String> vec = new Vector<String>();
vec.add("Tiger");
vec.add("Lion");
vec.addElement("Rat"); //Adding elem using addElement() method of Vector
vec.addElement("Cat");
System.out.println("Elements are: "+vec);
} }

Java Stack Class


 The stack is a linear data structure that is used to store the collection of objects. It is based on Last-
In-First-Out (LIFO). Java collection framework provides many interfaces and classes to store the
collection of objects. One of them is the Stack class that provides different operations such as
push, pop, search, etc.
 In this section, we will discuss the Java Stack class, its methods, and implement the stack data
structure in a Java program. But before moving to the Java Stack class have a quick view of how
the stack works.
 The stack data structure has the two most important operations that are push and pop. The push
operation inserts an element into the stack and pop operation removes an element from the top of
the stack. Let's see how they work on stack.
 In Java, Stack is a class that falls under the Collection framework that extends the Vector class.
It also implements interfaces List, Collection, Iterable, Cloneable, Serializable. It represents the
LIFO stack of objects. Before using the Stack class, we must import the java.util package.

Stack Class Constructor


 The Stack class contains only the default constructor that creates an empty stack
 public Stack()

Methods of the Stack Class

Method Method Description

empty() The method checks the stack is empty or not.

push(E item) The method pushes (insert) an element onto the top of the stack.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 15


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

pop() The method removes an element from the top of the stack and returns the same
element as the value of that function.

peek() The method looks at the top element of the stack without removing it.

search(Object o) The method searches the specified object and returns the position of the object.

Example
import java.util.Stack;
public class StackEmptyMethodExample {
public static void main(String[] args) {
Stack<Integer> stk= new Stack<>();
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
System.out.println("Elements in Stack: " + stk);
result = stk.empty();
System.out.println("Is the stack empty? " + result);
} }

ListIterator Interface
ListIterator Interface is used to traverse the element in a backward and forward direction.

ListIterator Interface declaration


public interface ListIterator<E> extends Iterator<E>

Methods of Java ListIterator Interface

Method Description

void add(E e) This method inserts the specified element into the list.

boolean This method returns true if the list iterator has more elements while traversing the
hasNext() list in the forward direction.

E next() This method returns the next element in the list and advances the cursor position.

int nextIndex() This method returns the index of the element that would be returned by a
subsequent call to next()

boolean This method returns true if this list iterator has more elements while traversing the
hasPrevious() list in the reverse direction.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 16


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

E previous() This method returns the previous element in the list and moves the cursor position
backward.

E This method returns the index of the element that would be returned by a
previousIndex() subsequent call to previous().

void remove() This method removes the last element from the list that was returned by next() or
previous() methods

void set(E e) This method replaces the last element returned by next() or previous() methods with
the specified element.

Example
import java.util.*;
public class ListIteratorExample1{
public static void main(String args[]){
List<String> al=new ArrayList<String>();
al.add("FY");
al.add("SY");
al.add("TY");
al.add(1,"FY BCA");
ListIterator<String> itr=al.listIterator();
System.out.println("Traversing elements in forward direction");
while(itr.hasNext()){
System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
}System.out.println("Traversing elements in backward direction");
while(itr.hasPrevious()){
System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
} } }

Java Set Interface


 Set Interface in Java is present in java.util package and extends the Collection interface.
 It represents the unordered set of elements which doesn't allow us to store the duplicate items. We
can store at most one null value in Set.
 Set is implemented by HashSet, LinkedHashSet, and TreeSet.

Set can be instantiated as


1. Set<data-type> s1 = new HashSet<data-type>();
2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 17


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

HashSet
 Java HashSet class is used to create a collection that uses a hash table for storage.
 It inherits the AbstractSet class and implements Set interface.
 HashSet stores the elements by using a mechanism called hashing.
 HashSet contains unique elements only and it allows null value.
 HashSet class is non synchronized, it doesn't maintain the insertion order. Here, elements are
inserted on the basis of their hashcode.
 HashSet is the best approach for search operations.
 The initial default capacity of HashSet is 16, and the load factor is 0.75.

Constructors of Java HashSet class

Constructor Description

HashSet() It is used to construct a default HashSet.

HashSet(int capacity) It is used to initialize the capacity of the hash set to the given integer value
capacity. The capacity grows automatically as elements are added to the
HashSet.

HashSet(int capacity, It is used to initialize the capacity of the hash set to the given integer value
float loadFactor) capacity and the specified load factor.

HashSet(Collection<? It is used to initialize the hash set by using the elements of the collection
extends E> c) c.

Methods of Java HashSet class

Method Description

boolean add(E e) It is used to add the specified element to this set if it is not already present.

Void clear() It is used to remove all of the elements from the set.

Object clone() It is used to return a shallow copy of this HashSet instance: the elements
themselves are not cloned.

boolean contains(Obj o) It is used to return true if this set contains the specified element.

boolean isEmpty() It is used to return true if this set contains no elements.

Iterator<E>iterator() It is used to return an iterator over the elements in this set.

boolean remove(Obj o) It is used to remove the specified element from this set if it is present.

Int size() It is used to return the number of elements in the set.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 18


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Spliterator It is used to create a late-binding and fail-fast Spliterator over the


<E>spliterator() elements in the set.

Example
import java.util.*;
class HashSet1{
public static void main(String args[]){
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
Iterator<String> i=set.iterator();
while(i.hasNext()) {
System.out.println(i.next());
} } }

Java LinkedHashSet Class


 Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface. It
inherits the HashSet class and implements the Set interface.
 Java LinkedHashSet class contains unique elements only like HashSet.
 Java LinkedHashSet class provides all optional set operations and permits null elements. It is non-
synchronized and it maintains insertion order.

Constructors of Java LinkedHashSet Class

Constructor Description

HashSet() It is used to construct a default HashSet.

HashSet(Collection c) Used to initialize the hash set by using the elements of the collection c.

LinkedHashSet(int It is used to initialize the capacity of the linked hash set to the given
capacity) integer value capacity.

LinkedHashSet(int It is used to initialize both the capacity and the fill ratio (also called load
capacity, float fillRatio) capacity) of the hash set from its argument

Example
import java.util.*;
public class LinkedHashSet1{
public static void main(String args[]) {

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 19


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

LinkedHashSet<String> lhs = new LinkedHashSet<String>();


lhs.add("Java");
lhs.add("Programming");
lhs.add("is");
lhs.add("easy");
lhs.add("to learn");
System.out.println("The hash set is: " + lhs);
System.out.println(lhs.remove("is "));
System.out.println("After removing the element, the hash set is: " + lhs);
} }

Java TreeSet Class


 Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet
class and implements the NavigableSet interface.
 The objects of the TreeSet class are stored in ascending order.
 It contains unique elements only and its access and retrieval times are quiet fast.
 It doesn't allow null element and it is non synchronized.
 It maintains ascending order and contains unique elements only
 It can only allow those generic types that are comparable. For example The Comparable interface
is being implemented by the StringBuffer class.

Internal Working of the TreeSet Class


 TreeSet is being implemented using a binary search tree, which is self-balancing just like a Red-
Black Tree. Therefore, operations such as a search, remove, and add consume O(log(N)) time.
 The reason behind this is there in the self-balancing tree. It is there to ensure that the tree height
never exceeds O(log(N)) for all of the mentioned operations. Therefore, it is one of the efficient
data structures in order to keep the large data that is sorted and also to do operations on it.

Constructors of Java TreeSet Class

Constructor Description

TreeSet() It is used to construct an empty tree set that will be sorted in ascending
order according to the natural order of the tree set.

TreeSet(Collection<? It is used to build a new tree set that contains the elements of the
extends E> c) collection c.

TreeSet(Comparator<? It is used to construct an empty tree set that will be sorted according to
super E> comparator) given comparator.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 20


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

TreeSet(SortedSet<E> s) It is used to build a TreeSet that contains the elements of the given
SortedSet.

Methods of Java TreeSet Class

method Description

boolean add(E e) Used to add the specified element to this set.

boolean addAll(Collection<? It is used to add all of the elements in the specified collection
extends E> c) to this set.

E ceiling(E e) It returns the equal or closest greatest element of the specified


element from the set, or null there is no such element.

Comparator<? super E> It returns a comparator that arranges elements in order.


comparator()

Iterator descendingIterator() It is used to iterate the elements in descending order.

NavigableSet descendingSet() It returns the elements in reverse order.

E floor(E e) It returns the equal or closest least element of the specified


element from the set, or null there is no such element.

SortedSet headSet(E toElement) It returns the group of elements that are less than the specified
element.

NavigableSet headSet(E It returns the group of elements that are less than or equal to(if,
toElement, boolean inclusive) inclusive is true) the specified element.

E higher(E e) It returns the closest greatest element of the specified element


from the set, or null there is no such element.

Iterator iterator() It is used to iterate the elements in ascending order.

E lower(E e) It returns the closest least element of the specified element from
the set, or null there is no such element.

E pollFirst() It is used to retrieve and remove the lowest(first) element.

E pollLast() It is used to retrieve and remove the highest(last) element.

Spliterator spliterator() It is used to create a late-binding and fail-fast spliterator over


the elements.

SortedSet subSet(E fromElement, It returns a set of elements that lie between the given range
E toElement)) which includes fromElement and excludes toElement.

SortedSet tailSet(E fromElement) It returns a set of elements that are greater than or equal to the
specified element.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 21


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

NavigableSet tailSet(E It returns a set of elements that are greater than or equal to (if,
fromElement, boolean inclusive) inclusive is true) the specified element.

boolean contains(Object o) It returns true if this set contains the specified element.

boolean isEmpty() It returns true if this set contains no elements.

boolean remove(Object o) Used to remove specified element from this set if it is present.

void clear() It is used to remove all of the elements from this set.

Object clone() It returns a shallow copy of this TreeSet instance.

E first() It returns the first (lowest) element currently in this sorted set.

E last() It returns the last (highest) element currently in this sorted set.

int size() It returns the number of elements in this set.

Example
import java.util.*;
class TreeSet1{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add("FY");
set.add("SY");
set.add("TY");
System.out.println("Lowest Value: "+set.pollFirst());
System.out.println("Highest Value: "+set.pollLast());
System.out.println("Traversing element through Iterator in descending order");
Iterator i=set.descendingIterator();
while(i.hasNext()) {
System.out.println(i.next());
} } }

Map Interface
 A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is
known as an entry. A Map contains unique keys.
 A Map is useful if you have to search, update or delete elements on the basis of a key.
 A Map doesn't allow duplicate keys, but you can have duplicate values.
 HashMap and LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null
key or value.
 A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 22


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

class Description

HashMap HashMap is the implementation of Map, but it doesn't maintain any order.

LinkedHashMap LinkedHashMap is the implementation of Map. It inherits HashMap class.


It maintains insertion order.

TreeMap TreeMap is the implementation of Map and SortedMap. It maintains


ascending order.

Methods of Map interface

Method Description

V put(Object key, Object value) It is used to insert an entry in the map.

void putAll(Map map) It is used to insert the specified map in the map.

V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the map
only if it is not already specified.

V remove(Object key) It is used to delete an entry for the specified key.

boolean remove(Object key, Object It removes the specified values with the associated specified
value) keys from the map.

Set keySet() It returns the Set view containing all the keys.

Set<Map.Entry<K,V>> entrySet() It returns the Set view containing all the keys and values.

void clear() It is used to reset the map.

V compute(K key, BiFunction<? It is used to compute a mapping for the specified key and its
super K,? super V,? extends V> current mapped value (or null if there is no current mapping).
remappingFunction)

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 23


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

V computeIfAbsent(K key, It is used to compute its value using the given mapping
Function<? super K,? extends V> function, if the specified key is not already associated with a
mappingFunction) value (or is mapped to null), and enters it into this map unless
null.

V computeIfPresent(K key, It is used to compute a new mapping given the key and its
BiFunction<? super K,? super V,? current mapped value if the value for the specified key is
extends V> remappingFunction) present and non-null.

boolean containsValue(Object This method returns true if some value equal to the value
value) exists within the map, else return false.

boolean containsKey(Object key) This method returns true if some key equal to the key exists
within the map, else return false.

boolean equals(Object o) It is used to compare the specified Object with the Map.

void forEach(BiConsumer<? super It performs the given action for each entry in the map until all
K,? super V> action) entries have been processed or the action throws an exception.

V get(Object key) This method returns the object that contains the value
associated with the key.

V getOrDefault(Object key, V It returns the value to which the specified key is mapped, or
defaultValue) defaultValue if the map contains no mapping for the key.

int hashCode() It returns the hash code value for the Map

boolean isEmpty() This method returns true if the map is empty; returns false if
it contains at least one key.

V merge(K key, V value, If the specified key is not already associated with a value or is
BiFunction<? super V,? super V,? associated with null, associates it with the given non-null
extends V> remappingFunction) value.

V replace(K key, V value) It replaces the specified value for a specified key.

boolean replace(K key, V oldValue, It replaces the old value with the new value for a specified
V newValue) key.

void replaceAll(BiFunction<? super It replaces each entry's value with the result of invoking the
K,? super V,? extends V> function) given function on that entry until all entries have been
processed or the function throws an exception.

Collection values() It returns a collection view of the values contained in the map.

int size() This method returns the number of entries in the map.

Map.Entry Interface

 Entry is the subinterface of Map. So we will be accessed it by Map.Entry name.


 It returns a collection-view of the map, whose elements are of this class.
 It provides methods to get key and value.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 24


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Methods of Map.Entry interface

Method Description

K getKey() It is used to obtain a key.

V getValue() It is used to obtain value.

int hashCode() It is used to obtain hashCode.

V setValue(V value) It is used to replace the value corresponding


to this entry with the specified value.

boolean equals(Object o) It is used to compare the specified object


with the other existing objects.

static <K extends Comparable<? super K>,V> It returns a comparator that compare the
Comparator<Map.Entry<K,V>> comparingByKey() objects in natural order on key.

static <K,V> Comparator<Map.Entry<K,V>> It returns a comparator that compare the


comparingByKey(Comparator<? super K> cmp) objects by key using the given Comparator.

static <K,V extends Comparable<? super V>> It returns a comparator that compare the
Comparator<Map.Entry<K,V>> comparingByValue() objects in natural order on value.

static <K,V> Comparator<Map.Entry<K,V>> It returns a comparator that compare the


comparingByValue(Comparator<? super V> cmp) objects by value using the given
Comparator.

Example
import java.util.*;
class MapExample2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
for(Map.Entry m:map.entrySet()){ //Elem can traverse in any order
System.out.println(m.getKey()+" "+m.getValue());
} } }

Java HashMap Class


 Java HashMap class implements the Map interface which allows us to store key and value pair,
where keys should be unique. If you try to insert the duplicate key, it will replace the element of
the corresponding key. It is easy to perform operations using the key index like updation, deletion,
etc. HashMap class is found in the java.util package.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 25


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

 HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to store
the null elements as well, but there should be only one null key. Since Java 5, it is denoted
as HashMap<K,V>, where K stands for key and V for value. It inherits the AbstractMap class and
implements the Map interface.
 K: It is the type of keys maintained by this map. V: It is the type of mapped values.
 It contains values based on the key, it contains only unique keys.
 It may have one null key and multiple null values.
 It is non synchronized and it maintains no order.
 The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
Constructors of Java HashMap class

Constructor Description

HashMap() It is used to construct a default HashMap.

HashMap(Map<? extends K,? It is used to initialize the hash map by using the elements of the
extends V> m) given Map object m.

HashMap(int capacity) It is used to initializes the capacity of the hash map to the given
integer value, capacity.

HashMap(int capacity, float It is used to initialize both the capacity and load factor of the hash
loadFactor) map by using its arguments.

Methods of Java HashMap class

Method Description

void clear() It is used to remove all of the mappings from this map.

boolean isEmpty() It is used to return true if this map contains no key-value mappings.

Object clone() It is used to return a shallow copy of this HashMap instance: the keys
and values themselves are not cloned.

Set entrySet() It is used to return a collection view of the mappings contained in


this map.

Set keySet() It is used to return a set view of the keys contained in this map.

V put(Object key, Object value) It is used to insert an entry in the map.

void putAll(Map map) It is used to insert the specified map in the map.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 26


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the map only
if it is not already specified.

V remove(Object key) It is used to delete an entry for the specified key.

boolean remove(Object key, It removes the specified values with the associated specified keys
Object value) from the map.

boolean containsValue(Object This method returns true if some value equal to the value exists
value) within the map, else return false.

boolean containsKey(Object This method returns true if some key equal to the key exists within
key) the map, else return false.

boolean equals(Object o) It is used to compare the specified Object with the Map.

void forEach(BiConsumer<? It performs the given action for each entry in the map until all entries
super K,? super V> action) have been processed or the action throws an exception.

V get(Object key) This method returns the object that contains the value associated with
the key.

V getOrDefault(Object key, V It returns the value to which the specified key is mapped, or
defaultValue) defaultValue if the map contains no mapping for the key.

boolean isEmpty() This method returns true if the map is empty; returns false if it
contains at least one key.

V replace(K key, V value) It replaces the specified value for a specified key.

boolean replace(K key, V It replaces the old value with the new value for a specified key.
oldValue, V newValue)

Collection<V> values() It returns a collection view of the values contained in the map.

int size() This method returns the number of entries in the map.

Example
import java.util.*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(1,"Mango"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"Banana");
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue()); } } }

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 27


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Java LinkedHashMap Class


 Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface, with
predictable iteration order. It inherits HashMap class and implements the Map interface.
 It contains values based on the key and also contains unique elements.
 It may have one null key and multiple null values.
 It is non synchronized and maintains insertion order.
 The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
Constructors of Java LinkedHashMap class

Constructor Description

LinkedHashMap() It is used to construct a default LinkedHashMap.

LinkedHashMap(int capacity) It is used to initialize a LinkedHashMap with the given capacity.

LinkedHashMap(int capacity, It is used to initialize both the capacity and the load factor.
float loadFactor)

LinkedHashMap(int capacity, It is used to initialize both the capacity and the load factor with
float loadFactor, boolean specified ordering mode.
accessOrder)

LinkedHashMap(Map<? extends It is used to initialize the LinkedHashMap with the elements from
K,? extends V> m) the given Map class m.

Methods of Java LinkedHashMap class

Method Description

V get(Object key) It returns the value to which the specified key is mapped.

void clear() It removes all the key-value pairs from a map.

boolean containsValue(Object It returns true if the map maps one or more keys to the specified
value) value.

Set<Map.Entry<K,V>> It returns a Set view of the mappings contained in the map.


entrySet()

void forEach(BiConsumer<? It performs the given action for each entry in the map until all
super K,? super V> action) entries have been processed or the action throws an exception.

V getOrDefault(Object key, V It returns the value to which the specified key is mapped or
defaultValue) defaultValue if this map contains no mapping for the key.

Set<K> keySet() It returns a Set view of the keys contained in the map

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 28


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

protected boolean It returns true on removing its eldest entry.


removeEldestEntry(Map.Entry<
K,V> eldest)

void replaceAll(BiFunction<? It replaces each entry's value with the result of invoking the given
super K,? super V,? extends V> function on that entry until all entries have been processed or the
function) function throws an exception.

Collection<V> values() It returns a Collection view of the values contained in this map.

Example
import java.util.*;
class LinkedHashMap1{
public static void main(String args[]){
LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
hm.put(100,"FY");
hm.put(101,"SY");
hm.put(102,"TY");
System.out.println("Keys: "+map.keySet());
System.out.println("Values: "+map.values());
System.out.println("Key-Value pairs: "+map.entrySet());
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
} } }

Java TreeMap Class

 Java TreeMap class is a red-black tree based implementation. It provides an efficient means of
storing key-value pairs in sorted order.
 Java TreeMap contains values based on the key. It implements the NavigableMap interface and
extends AbstractMap class, it contains only unique elements.
 Java TreeMap cannot have a null key but can have multiple null values.
 Java TreeMap is non synchronized and maintains ascending order.
Constructors of Java TreeMap class

Constructor Description

TreeMap() It is used to construct an empty tree map that will be sorted


using the natural order of its key.

TreeMap(Comparator<? super K> It is used to construct an empty tree-based map that will be
comparator) sorted using the comparator comp.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 29


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

TreeMap(Map<? extends K,? It is used to initialize a treemap with the entries from m, which
extends V> m) will be sorted using the natural order of the keys.

TreeMap(SortedMap<K,? extends It is used to initialize a treemap with the entries from the
V> m) SortedMap sm, which will be sorted in the same order as sm.

Methods of Java TreeMap class

Method Description

Map.Entry<K,V> ceilingEntry(K It returns the key-value pair having the least key, greater than or
key) equal to the specified key, or null if there is no such key.

K ceilingKey(K key) It returns the least key, greater than the specified key or null if
there is no such key.

void clear() It removes all the key-value pairs from a map.

Object clone() It returns a shallow copy of TreeMap instance.

Comparator<? super K> It returns the comparator that arranges the key in order, or null
comparator() if the map uses the natural ordering.

NavigableSet<K> It returns a reverse order NavigableSet view of the keys


descendingKeySet() contained in the map.

NavigableMap<K,V> It returns the specified key-value pairs in descending order.


descendingMap()

Map.Entry firstEntry() It returns the key-value pair having the least key.

Map.Entry<K,V> floorEntry(K It returns the greatest key, less than or equal to the specified key,
key) or null if there is no such key.

void forEach(BiConsumer<? It performs the given action for each entry in the map until all
super K,? super V> action) entries have been processed or the action throws an exception.

SortedMap<K,V> headMap(K It returns the key-value pairs whose keys are strictly less than
toKey) toKey.

NavigableMap<K,V> headMap(K It returns the key-value pairs whose keys are less than (or equal
toKey, boolean inclusive) to if inclusive is true) toKey.

Map.Entry<K,V> higherEntry(K It returns the least key strictly greater than the given key, or null
key) if there is no such key.

K higherKey(K key) It is used to return true if this map contains a mapping for the
specified key.

Set keySet() It returns the collection of keys exist in the map.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 30


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Map.Entry<K,V> lastEntry() It returns the key-value pair having the greatest key, or null if
there is no such key.

Map.Entry<K,V> lowerEntry(K It returns a key-value mapping associated with the greatest key
key) strictly less than the given key, or null if there is no such key.

K lowerKey(K key) It returns the greatest key strictly less than the given key, or null
if there is no such key.

NavigableSet<K> It returns a NavigableSet view of the keys contained in this map.


navigableKeySet()

Map.Entry<K,V> pollFirstEntry() It removes and returns a key-value mapping associated with the
least key in this map, or null if the map is empty.

Map.Entry<K,V> pollLastEntry() It removes and returns a key-value mapping associated with the
greatest key in this map, or null if the map is empty.

V put(K key, V value) It inserts the specified value with the specified key in the map.

void putAll(Map<? extends K,? It is used to copy all the key-value pair from one map to another
extends V> map) map.

V replace(K key, V value) It replaces the specified value for a specified key.

boolean replace(K key, V It replaces the old value with the new value for a specified key.
oldValue, V newValue)

void replaceAll(BiFunction<? It replaces each entry's value with the result of invoking the
super K,? super V,? extends V> given function on that entry until all entries have been processed
function) or the function throws an exception.

NavigableMap<K,V> subMap(K It returns key-value pairs whose keys range from fromKey to
fromKey, boolean fromInclusive, toKey.
K toKey, boolean toInclusive)

SortedMap<K,V> subMap(K It returns key-value pairs whose keys range from fromKey,
fromKey, K toKey) inclusive, to toKey, exclusive.

SortedMap<K,V> tailMap(K It returns key-value pairs whose keys are greater than or equal
fromKey) to fromKey.

NavigableMap<K,V> tailMap(K It returns key-value pairs whose keys are greater than (or equal
fromKey, boolean inclusive) to, if inclusive is true) fromKey.

boolean containsKey(Object key) It returns true if the map contains a mapping for the specified
key.

boolean containsValue(Object It returns true if the map maps one or more keys to the specified
value) value.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 31


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

K firstKey() Used to return the first (lowest) key currently in this sorted map.

V get(Object key) Used to return the value to which the map maps the specified
key.

K lastKey() Used to return the last (highest) key currently in the sorted map.

V remove(Object key) It removes the key-value pair of the specified key from the map.

Set<Map.Entry<K,V>> entrySet() It returns a set view of the mappings contained in the map.

int size() It returns the number of key-value pairs exists in the hashtable.

Collection values() It returns a collection view of the values contained in the map.

Example
import java.util.*;
class TreeMap1{
public static void main(String args[]){
TreeMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(100,"FY");
map.put(102,"SY");
map.put(101,"TY");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue()); } } }
Comparable Interfaces
 Java Comparable interface is used to order the objects of the user-defined class.
 This interface is found in java.lang package and contains only one method named
compareTo(Object).
 It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single
data member only. For example, it may be rollno, name, age or anything else.

compareTo(Object obj) method


public int compareTo(Object obj): It is used to compare the current object with the specified object. It
returns
 positive integer, if the current object is greater than the specified object.
 negative integer, if the current object is less than the specified object.
 zero, if the current object is equal to the specified object.
We can sort the elements of:
o String objects
o Wrapper class objects
o User-defined class objects

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 32


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Example:
Student.java
class Student implements Comparable<Student> {
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
} public int compareTo(Student st){
if(age==st.age) return 0;
else if(age>st.age) return 1;
else return -1; } }
Comparable1.java
import java.util.*;
public class Comparable1{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Aparna",23));
al.add(new Student(106,"Neha",27));
al.add(new Student(105,"Shruti",21));
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
} } }
Comparator Interfaces
 Java Comparator interface is used to order the objects of a user-defined class.
 This interface is found in java.util package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).
 It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.

Methods of Java Comparator Interface


Method Description

public int compare(Object obj1, Object obj2) It compares the first object with the second object.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 33


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

public boolean equals(Object obj) It is used to compare the current object with the
specified object.

public boolean equals(Object obj) It is used to compare the current object with the
specified object.

Method of Collections class for sorting List elements


public void sort(List list, Comparator c): used to sort the elements of List by the given Comparator.
Difference between Comparable and Comparator

Comparable Comparator

Comparable provides a single sorting sequence. In The Comparator provides multiple sorting
other words, we can sort the collection on the basis sequences. In other words, we can sort the
of a single element such as id, name, and price. collection on the basis of multiple elements such
as id, name, and price etc.

Comparable affects the original class, i.e., the Comparator doesn't affect the original class, i.e.,
actual class is modified. the actual class is not modified.

Comparable provides compareTo() method to Comparator provides compare() method to sort


sort elements. elements.

Comparable is present in java.lang package. A Comparator is present in the java.util package.

We can sort the list elements of Comparable type We can sort the list elements of Comparator type
by Collections.sort(List) method. by Collections.sort(List, Comparator) method.

Enumeration Interfaces
 The Enumeration interface defines the methods by which you can enumerate (obtain one at a time)
the elements in a collection of objects.
 This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is
considered obsolete for new code.
 However, it is used by several methods defined by the legacy classes such as Vector and
Properties, is used by several other API classes, and is currently in widespread use in application
code.

Declaration
public interface Enumeration<E> (Where E is the type of elements stored in a Collection.)

Creating Enumeration Object


Vector ve = new Vector();
Enumeration e = v.elements();
Important Features
 Enumeration is Synchronized.
 It does not support adding, removing, or replacing elements.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 34


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

 Elements of legacy Collections can be accessed in a forward direction using Enumeration.


 Legacy classes have methods to work with enumeration and returns Enumeration objects.

Enumeration Interface Methods

Method Description

boolean When implemented, it must return true while there are still more elements
hasMoreElements( ) to extract, and false when all the elements have been enumerated.

Object nextElement( ) This returns the next object in the enumeration as a generic Object
reference.

Example
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationClass {
public static void main(String args[]){
Enumeration months;
Vector<String> monthNames = new Vector<>();
monthNames.add("January");
monthNames.add("February");
monthNames.add("March");
monthNames.add("April");
monthNames.add("May");
monthNames.add("June");
monthNames.add("July");
monthNames.add("August");
monthNames.add("September");
monthNames.add("October");
monthNames.add("November");
monthNames.add("December");
months = monthNames.elements();
while (months.hasMoreElements()) {
System.out.println(months.nextElement());
}}}

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 35


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Assignment 2: Multithreading

Multithreading
 Multithreading in Java is a process of executing multiple threads simultaneously.
 A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
 However, we use multithreading than multiprocessing because threads use a shared memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
 Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


 It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
 You can perform many operations together, so it saves time.
 Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the
CPU. Multitasking can be achieved in two ways:
 Process-based Multitasking (Multiprocessing)
 Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


 Each process has an address in memory. In other words, each process allocates a separate memory
area.
 A process is heavyweight.Cost of communication between the process is high.
 Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


 Threads share the same address space.
 A thread is lightweight.
 Cost of communication between the thread is low.

Threads

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 36


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

 A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of


execution.
 Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.

 As shown in the above figure, a thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS, and one process can have
multiple threads.

Java Thread class


 Java provides Thread class to achieve thread programming.
 Thread class provides constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.

Java Thread Methods

S.N. Modifier and Type Method Description

1) void start() It is used to start the execution of the


thread.

2) void run() It is used to do an action for a thread.

3) static void sleep() It sleeps a thread for the specified amount


of time.

4) static Thread currentThread() It returns a reference to the currently


executing thread object.

5) void join() It waits for a thread to die.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 37


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

6) int getPriority() It returns the priority of the thread.

7) void setPriority() It changes the priority of the thread.

8) String getName() It returns the name of the thread.

9) void setName() It changes the name of the thread.

10) long getId() It returns the id of the thread.

11) boolean isAlive() It tests if the thread is alive.

12) static void yield() It causes the currently executing thread


object to pause and allow other threads to
execute temporarily.

13) void suspend() It is used to suspend the thread.

14) void resume() It is used to resume the suspended thread.

15) void stop() It is used to stop the thread.

16) void destroy() It is used to destroy the thread group and


all of its subgroups.

17) boolean isDaemon() It tests if the thread is a daemon thread.

18) void setDaemon() It marks the thread as daemon or user


thread.

19) void interrupt() It interrupts the thread.

20) boolean isinterrupted() It tests whether the thread has been


interrupted.

21) static boolean interrupted() It tests whether the current thread has been
interrupted.

22) static int activeCount() It returns the number of active threads in


the current thread's thread group.

23) void checkAccess() It determines if the currently running


thread has permission to modify the thread.

24) static boolean holdLock() It returns true if and only if the current
thread holds the monitor lock on the
specified object.

25) static void dumpStack() It is used to print a stack trace of the current
thread to the standard error stream.

26) StackTraceElement[] getStackTrace() It returns an array of stack trace elements


representing the stack dump of the thread.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 38


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

27) static int enumerate() It is used to copy every active thread's


thread group and its subgroup into the
specified array.

28) Thread.State getState() It is used to return the state of the thread.

29) ThreadGroup getThreadGroup() It is used to return the thread group to


which this thread belongs

30) String toString() It is used to return a string representation


of this thread, including the thread's name,
priority, and thread group.

31) void notify() It is used to give the notification for only


one thread which is waiting for a particular
object.

32) void notifyAll() It is used to give the notification to all


waiting threads of a particular object.

33) void setContextClassLoader( It sets the context ClassLoader for the


) Thread.

34) ClassLoader getContextClassLoader It returns the context ClassLoader for the


() thread.

35) static getDefaultUncaughtEx It returns the default handler invoked when


Thread.UncaughtExc ceptionHandler() a thread abruptly terminates due to an
eptionHandler uncaught exception.

36) static void setDefaultUncaughtExc It sets the default handler invoked when a
eptionHandler() thread abruptly terminates due to an
uncaught exception.

Life cycle of thread (State of Thread)


In Java, a thread always exists in any one of the following states. These states are:
1. New: A thread that is created but not yet started is in this state.
 Example: Thread thread = new Thread();
2. Runnable: A thread that is ready to run and waiting for CPU time is in the runnable state.
 Example: thread.start();
3. Blocked: A thread that is blocked waiting for a monitor lock is in this state.
 Example: synchronized (object) { // critical section }
4. Waiting: A thread that is waiting indefinitely for another thread to perform a particular action is
in this state.
 Example: object.wait();

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 39


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

5. Timed Waiting: A thread that is waiting for another thread to perform an action for up to a
specified waiting time is in this state.
 Example: Thread.sleep(1000); // sleep for 1 second
6. Terminated: A thread that has exited or terminated is in this state.
 Example: A thread's run() method has completed execution.

Explanation of Transitions
1. New → Runnable:
 The transition happens when start() is called on a new thread.
 Example: thread.start();
2. Runnable → Running:
 The thread scheduler picks the thread from the runnable state and executes it.
3. Running → Blocked:
 The thread attempts to enter a synchronized block or method and is blocked because
another thread holds the monitor lock.
 Example: synchronized (object) { // critical section }
4. Running → Waiting:
 The thread calls wait() on an object.
 Example: object.wait();
5. Running → Timed Waiting:
 The thread calls methods like sleep(long millis), wait(long timeout), join(long millis), etc.
 Example: Thread.sleep(1000);
6. Waiting/Timed Waiting → Runnable:
 The thread is notified (notify(), notifyAll()) or the waiting time expires, making it eligible
to run again.
 Example: object.notify();

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 40


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

7. Blocked → Runnable:
 The thread acquires the monitor lock and moves back to the runnable state.
 Example: Exiting the synchronized block.
8. Running → Terminated:
 The thread completes its execution or throws an unhandled exception, transitioning to the
terminated state.
 Example: run() method completes.

Java program to demonstrate thread states


class thread implements Runnable {
public void run(){
// moving thread2 to timed waiting state
try {
Thread.sleep(1500);
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("State of thread1 while it called join() method on thread2 -"+
Test.thread1.getState());
try {
Thread.sleep(200);
}catch (InterruptedException e) {
e.printStackTrace();
}
}}

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 41


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

public class Test implements Runnable {


public static Thread thread1;
public static Test obj;
public static void main(String[] args){
obj = new Test();
thread1 = new Thread(obj);
// thread1 created and is currently in the NEW state.
System.out.println("State of thread1 after creating it - "+ thread1.getState());
thread1.start();
// thread1 moved to Runnable state
System.out.println("State of thread1 after calling .start() method on it - "+ thread1.getState());
}
public void run(){
thread myThread = new thread();
Thread thread2 = new Thread(myThread);
// thread2 created and is currently in the NEW state.
System.out.println("State of thread2 after creating it - "+ thread2.getState());
thread2.start();
// thread2 moved to Runnable state
System.out.println("State of thread2 after calling .start() method on it - "+ thread2.getState());
// moving thread2 to timed waiting state
try { // moving thread2 to timed waiting state
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("State of thread2 after calling .sleep() method on it - "+ thread2.getState());
try {// waiting for thread2 to die
thread2.join();
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("State of thread2 when it has finished it's execution - "+ thread2.getState());
}
}

Creating threads - Thread class, Runnable interface


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class
extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 42


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Commonly used methods of Thread class:


public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause and allow other
threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.
Example
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed
by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 43


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs the following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

Thread priorities

Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases, the
thread scheduler schedules the threads according to their priority (known as preemptive scheduling). But
it is not guaranteed because it depends on JVM specification that which scheduling it chooses. Note that
not only JVM a Java programmer can also assign the priorities of a thread explicitly in a Java program.

Setter & Getter Method of Thread Priority

public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given
thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or


assign the priority of the thread to newPriority. The method throws IllegalArgumentException if the value
newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value
of MAX_PRIORITY is 10.

Example:
import java.lang.*;
public class ThreadPriorityExample extends Thread {
public void run() {
System.out.println("Inside the run() method");
}
public static void main(String argvs[]) {
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 44


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

System.out.println("Priority of the thread th2 is : " + th2.getPriority());


th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
}
}

Daemon Thread in Java

Daemon thread in Java is a service provider thread that provides services to the user thread. Its life
depends on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread
automatically.

There are many java daemon threads running automatically e.g. gc, finalizer etc.

You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides
information about the loaded classes, memory usage, running threads etc.

Points to remember for Daemon Thread in Java


o It provides services to user threads for background supporting tasks. It has no role in life than to
serve user threads.
o Its life depends on user threads.
o It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread?

The sole purpose of the daemon thread is that it provides services to user thread for background supporting
task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates
the daemon thread if there is no user thread.

Methods for Java Daemon thread by Thread class


No. Method Description

1) public void setDaemon(boolean is used to mark the current thread as daemon thread or
status) user thread.

2) public boolean isDaemon() is used to check that current is daemon.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 45


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

public class TestDaemonThread1 extends Thread{


public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t2.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
}
}
Synchronization

Whenever multiple threads are trying to use same resource than they may be chance to of getting wrong
output, to overcome this problem thread synchronization can be used. Java Synchronization is better
option where we want to allow only one thread to access the shared resource.
Allowing only one thread at a time to utilized the same resource out of multiple threads is known as
thread synchronization or thread safe.
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
2. Cooperation (Inter-thread communication in java)

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 46


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can be
achieved by using the following three ways:
1. By Using Synchronized Method
2. By Using Synchronized Block
3. By Using Static Synchronization
Synchronized block
Whenever we want to execute one or more than one statement by a single thread at a time (not allowing
other thread until thread one execution is completed) than those statement should be placed in side
synchronized block.
Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in such cases,
we can use synchronized block.
If we put all the codes of the method in the synchronized block, it will work same as the synchronized
method.
Syntax
synchronized (object reference expression) {
//code block
}
Example
class Table {
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
} } } }
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 47


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

} public void run(){


t.printTable(100);
}}
public class TestSynchronizedBlock1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
} }

Interthread communication
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It
is implemented by following methods of Object class:
o wait()
o notify()
o notifyAll()
1) wait() method
The wait() method causes current thread to release the lock and wait until either another thread invokes
the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method
only otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException It waits until object is notified.

public final void wait(long timeout)throws It waits for the specified amount of time.
InterruptedException
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.
Syntax: public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax: public final void notifyAll()

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 48


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
It is because they are related to lock and object has a lock.
Difference between wait and sleep?

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.

Example
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
} this.amount-=amount;
System.out.println("withdraw completed...");
} synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
public class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 49


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Thread Scheduler
A component of Java that decides which thread to run or execute and which thread to wait is called
a thread scheduler in Java. In Java, a thread is only chosen by a thread scheduler if it is in the runnable
state. However, if there is more than one thread in the runnable state, it is up to the thread scheduler to
pick one of the threads and ignore the other ones.
There are some criteria that decide which thread will execute first. There are two factors for scheduling a
thread i.e. Priority and Time of arrival.
Priority: Priority of each thread lies between 1 to 10. If a thread has a higher priority, it means that thread
has got a better chance of getting picked up by the thread scheduler.
Time of Arrival: Suppose two threads of the same priority enter the runnable state, then priority cannot
be the factor to pick a thread from these two threads. In such a case, arrival time of thread is considered
by the thread scheduler. A thread that arrived first gets the preference over the other threads.

ThreadGroup class
Java provides a convenient way to group multiple threads in a single object. In such a way, we can
suspend, resume or interrupt a group of threads by a single method call. Java thread group is implemented
by java.lang.ThreadGroup class.
A ThreadGroup represents a set of threads. A thread group can also include the other thread group. The
thread group creates a tree in which every thread group except the initial thread group has a parent.
A thread is allowed to access information about its own thread group, but it cannot access the information
about its thread group's parent thread group or any other thread groups.
Constructors of ThreadGroup class
ThreadGroup(String name) - creates a thread group with given name.
ThreadGroup(ThreadGroup parent, String name) - creates a thread group with a given parent group
and name.
Methods of ThreadGroup class
Modifier & Method Description
Type

void checkAccess() This method determines if the currently running thread has
permission to modify the thread group.

int activeCount() This method returns an estimate of the number of active


threads in the thread group and its subgroups.

int activeGroupCount() This method returns an estimate of the number of active


groups in the thread group and its subgroups.

void destroy() This method destroys the thread group and all of its
subgroups.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 50


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

int enumerate(Thread[] This method copies into the specified array every active
list) thread in the thread group and its subgroups.

int getMaxPriority() This method returns the maximum priority of the thread
group.

String getName() This method returns the name of the thread group.

ThreadGroup getParent() This method returns the parent of the thread group.

void interrupt() This method interrupts all threads in the thread group.

boolean isDaemon() This method tests if the thread group is a daemon thread
group.

void setDaemon(boolean This method changes the daemon status of the thread group.
daemon)

boolean isDestroyed() This method tests if this thread group has been destroyed.

void list() This method prints information about the thread group to
the standard output.

boolean parentOf(ThreadGrou This method tests if the thread group is either the thread
pg group argument or one of its ancestor thread groups.

void suspend() This method is used to suspend all threads in the thread
group.

void resume() This method is used to resume all threads in the thread
group which was suspended using suspend() method.

void setMaxPriority(int pri) This method sets the maximum priority of the group.

void stop() This method is used to stop all threads in the thread group.

String toString() This method returns a string representation of the Thread


group.

Example
public class ThreadGroupDemo implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName());
} public static void main(String[] args) {
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
Thread t1 = new Thread(tg1, runnable,"one"); t1.start();
Thread t2 = new Thread(tg1, runnable,"two"); t2.start();
Thread t3 = new Thread(tg1, runnable,"three"); t3.start();
System.out.println("Thread Group Name: "+tg1.getName());
tg1.list(); } }

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 51


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Unit 3: Database Programming

JDBC Introduction
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with
the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with
the database.
We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API,
we can save, update, delete and fetch data from the database. It is like Open Database Connectivity
(ODBC) provided by Microsoft.

Role of JDBC
Before JDBC, ODBC API was the database API to connect and execute the query with the database. But,
ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured).
That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

The java.sql package contains classes and interfaces for JDBC API.
A list of interfaces of JDBC API:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 52


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

A list of classes of JDBC API:


o DriverManager class
o Blob class
o Clob class
o Types class

What is API
API (Application programming interface) is a document that contains a description of all the features of
a product or software. It represents classes and interfaces that software programs can follow to
communicate with each other. An API can be created for applications, libraries, operating systems, etc.

JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in
general, JDBC Architecture consists of two layers −
 JDBC API − This provides the application-to-JDBC Manager connection.
 JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.

 The top level API communicates with the JDBC manager driver API sending it the various SQL
statements.
 Afterwards the manager communicates with the various third party drivers that actually connect
to the database and return the information from the query or perform the action specified by the
query.
 The driver manager also helps to select the most appropriate driver from the previously loaded
driers when a new open database is connected.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 53


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Two-tier and Three-tier model


Two-tier model:
The Java application communicates directly with the database, eliminating the need for an
intermediate tier.
This architecture is suitable for simple applications with limited data processing requirements.
This model refers to as client/server model where user is the client and the machine that has the
database is called as the server.
Java Application
Client Machine
JDBC

DBMS proprietary protocol

DBMC Database Server

Three-Tier model:
An application server or middleware layer acts as an intermediate tier, providing additional
functionality such as security, caching, and data transformation.
This architecture is beneficial for complex applications with high data processing requirements, as it
allows for better control over data access and modification.
Java Applet or Client Machine (GUI)
HTML browser

HTTP, RMI or CORBA calls

Java Application
Server Machine (Business Logic)
JDBC

DBMS proprietary protocol

DBMC Database Server (eg. Oracle, SQL)

Types of drivers
JDBC Driver is a software component that enables java application to interact with the database. There
are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 54


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Type 1 JDBC-ODBC bridge driver: (Quick setup for environments with ODBC drivers but lacks
performance and platform independence.)
 The JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
 The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
 This is now discouraged because of thin driver.

Characteristics:
 Bridge Driver: Translates JDBC calls into ODBC (Open Database Connectivity) calls.
 Platform Dependent: Requires the ODBC driver to be installed on the client machine.
 Sun Microsystems: Initially provided by Sun Microsystems but now largely deprecated due to
performance and compatibility issues.

Advantages:
 Easy to set up for environments that already have ODBC drivers.
 Provides access to almost any database via the ODBC driver.
 It is easy to use and can be easily connected to any database.

Disadvantages:
 Slower compared to other driver types due to the additional layer of ODBC translation.
 Requires ODBC setup on the client machine.
 Not suitable for web applications where portability and performance are critical.

Type 2 Native-API driver (partially java driver): (Offers better performance for specific databases but
is platform-dependent due to native libraries.)
 The Native API driver uses the client-side libraries of the database.
 The driver converts JDBC method calls into native calls of the database API. It is not written
entirely in java.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 55


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Characteristics:
 Partially Java: Uses native code libraries of the database to convert JDBC calls into database-
specific calls.
 Platform Dependent: Requires native database client libraries on the client machine.
Advantages:
 Faster than Type 1 as it converts JDBC calls directly into database-specific calls.
 Optimized for specific databases.
Disadvantages:
 Requires database-specific native libraries on the client machine.
 Limits portability across different platforms.
 The Vendor client library needs to be installed on client machine.

Type 3 Network Protocol driver (fully java driver): (Provides flexibility and portability but requires a
middleware server.)
 The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.

Characteristics:
 Middleware Server: Converts JDBC calls into a database-independent network protocol, which is
then translated to database-specific calls by a middleware server.
 Pure Java: Platform-independent, as it does not require native libraries.

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 56


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Advantages:
 Fully written in Java, making it portable across different platforms.
 Can connect to multiple databases using a single driver.
 Easier to deploy in large-scale environments with centralized middleware.
 No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
 Requires a middleware server, which can introduce additional complexity and potential
bottlenecks.
 Network support is required on client machine.
 Requires database-specific coding to be done in the middle tier.
 Maintenance of Network Protocol driver becomes costly because it requires database-specific
coding to be done in the middle tier.

Type 4 Thin driver (fully java driver): (The most efficient and portable option, ideal for modern web
applications, though it requires database-specific drivers.)
 The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.

Characteristics:
 Direct-to-Database: Converts JDBC calls directly into the database-specific protocol.
 Pure Java: Fully implemented in Java, offering complete platform independence.
Advantages:
 Fastest among all driver types due to direct communication with the database (better performance).
 Platform-independent, ideal for web applications.
 Easy to deploy and use without the need for native libraries or middleware.
 No software is required at client side or server side
Disadvantages:
 Requires different drivers for different databases (Drivers depend on the Database).

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 57


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Connectivity with database


There are 5 steps to connect any java application with the database using JDBC. These steps are as
follows:
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries
5. Close connection

JDBC Statements – Statement, Prepared Statement, Callable Statement, Scrollable and updatable
result sets

Metadata – DatabaseMetadata, ResultSetMetadata (Database: PostgreSQL)

Unit 4: Servlet and JSP

Servlets: Introduction to Servlets and Hierarchy of Servlets, Life cycle of a servlet, Tomcat
configuration (Note: Only for Lab Demonstration), Handing get and post request (HTTP),
Handling a data from HTML to a servlet, Session tracking – Cookies and Http Session

JSP: Simple JSP program, Life cycle of a JSP, Implicit Objects, Scripting elements – Declarations,
Expressions, Scriplets, Comments, JSP Directives – Page Directive, include directive, Mixing
Scriplets and HTML

Unit 5: Applet

Applet basics, Life Cycle of an Applet, The Applet Class, Invoking an Applet, Getting Applet
Parameters, Specifying Applet Parameters, Application Conversion to Applets, Event Handling
Displaying Images, Playing Audio

Unit 6: Spring Framework


Introduction of spring framework, Spring Modules / Architecture, Spring Applications, Spring
MVC, Spring MVC Forms, Validation

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 58


B.C.A.: 2024-2025 Autonomous T.Y. B.C.A. (Science)

Unit 7: Java Networking


Java Socket Programming, Socket classes, ServerSocket classes, URL class and method of URL
class, URLConnection class, methods of URLConnection class, HttpURLConnection class,
HttpURLConnection class methods

Lab Course – I Advanced Java Laboratory 24-BCA-351 Workbook 59

You might also like