KEMBAR78
Java Unit - V | PDF | Queue (Abstract Data Type) | Class (Computer Programming)
0% found this document useful (0 votes)
7 views42 pages

Java Unit - V

Uploaded by

sunilyadhav201
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)
7 views42 pages

Java Unit - V

Uploaded by

sunilyadhav201
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/ 42

22PC1IT201 UNIT - V OOP Through Java

SYLLABUS
The Collection Framework: Collection Objects – Sets, Lists, Queues, Maps – ArrayList, LinkedList -
Vector– HashSet– LinkedHashSet– TreeSet– HashMap– Hashtable. Retrieving Elements from Collections –
Enumeration, Iterator, List Iterator – String Tokenizer and Arrays Class – Sorting using Comparable and
Comparator.
Java Database Connectivity: Introduction to JDBC, Types of Drivers, Basic steps in developing JDBC
applications, JDBC classes and Interfaces, CRUD operations with JDBC, Transaction Management, Stored
Procedures.

The Collection Framework


• It is framework that provides an architecture to store and manipulate a group of objects
• The Java collections framework is a set of classes and interfaces that implement commonly reusable
collection data structures.
• It can achieve all the operation that you can perform on a dataset, such as sorting, searching, insertion etc.
• All the collections available in java.util package.

Collection Objects

1
22PC1IT201 UNIT - V OOP Through Java

Iterable interface:
• It is the root interface in the collection hierarchy, and all direct and indirect subclasses of Collection
implement Iterable.
• Syntax: interface Iterable<T>
• It provides the facility of iterating/traversing different types of collection objects in a forward direction
only.
• The Iterable interface has a single abstract method, iterator( ), which returns an Iterator object for the
collection.
• Syntax: Iterator<T> iterator( )
• Iterate the collection objects using the following methods
boolean hasNext( ) - return true if the iterator has more elements
Object next( ) - return the element and move the cursor pointing to the next element
void remove( ) - it remove the last element returned by the iterator

Collection interface:
• The Collection interface in Java is the root interface of the Java collections framework.
• It defines the basic methods that all collections must implement, such as add( ), remove( ), size( ), and
contains( ).
• The Collection interface is implemented by a number of different classes, including ArrayList,
LinkedList, HashSet, and TreeSet.
• These classes provide different implementations of the collection interface, with different strengths and
weaknesses.
• For example, ArrayList is an ordered list that allows duplicates. LinkedList is an ordered list that does not
allow duplicates.
• The Collection interface is a powerful tool for storing and managing data in Java
• Syntax: interface Collection<E> extends Interable<E>
No Method Description
1 boolean add(E e) It is used to insert an element in this collection.
boolean addAll(Collection<? extends E> It is used to insert the specified collection elements in
2
c) the invoking collection.
3 boolean remove(Object element) It is used to delete an element from the collection.
It is used to delete all the elements of the specified
4 boolean removeAll(Collection<?> c)
collection from the invoking collection.
default boolean removeIf(Predicate<? It is used to delete all the elements of the collection
5
super E> filter) that satisfy the specified predicate.
It is used to delete all the elements of invoking
6 boolean retainAll(Collection<?> c)
collection except the specified collection.
It returns the total number of elements in the
7 int size( )
collection.
It removes the total number of elements from the
8 void clear( )
collection.
9 boolean contains(Object element) It is used to search an element.
It is used to search the specified collection in the
10 boolean containsAll(Collection<?> c)
collection.
11 Object[] toArray() It converts collection into array.
It converts collection into array. Here, the runtime type
12 <T> T[] toArray(T[] a)
of the returned array is that of the specified array.
2
22PC1IT201 UNIT - V OOP Through Java

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


It returns a possibly parallel Stream with the collection
14 default Stream<E> parallelStream()
as its source.
It returns a sequential Stream with the collection as its
15 default Stream<E> stream()
source.
It generates a Spliterator over the specified elements in
16 default Spliterator<E> spliterator()
the collection.
17 boolean equals(Object element) It matches two collections.
18 int hashCode( ) It returns the hash code number of the collection.

• Benefits:
✓ It is a powerful tool for storing and managing data.
✓ It is flexible and can be used to implement a variety of different data structures.
✓ It is efficient and provides a number of performance benefits.
✓ It is easy to use and provides a consistent API.
• Drawbacks:
✓ It can be complex to learn and use.
✓ It can be inefficient for certain operations.
✓ It can be difficult to debug.

List Interface
• The List interface is a collection of objects that stores a specific order.
• Elements can be inserted or accessed by their position in the list, using index.
• A list may contain duplicate elements.
• A list allows multiple null values.
• Syntax: interface List<E> extends Collection<E>
Here, E specifies the type of objects that the list will hold.
• The class implement a list interface: ArrayList, LinkedList, Vector, Stack

Queue Interface
• The Queue interface is an abstract data type that represents a collection of elements that are ordered and
can be accessed in a FIFO (first-in-first-out) manner.
• Besides basic Collection operations, queues provide additional insertion, removal, and examination
operations.
• The Queue interface is implemented by the following classes: LinkedList, PriorityQueue, ArrayDeque.
• Each of these methods exists in two forms: one throws an exception if the operation fails, the other
returns a special value (either null or false, depending on the operation).
Method Description
Inserts the specified element into this queue if it is possible to do so immediately
boolean add(E e) without violating capacity restrictions, returning true upon success and throwing
an IllegalStateException if no space is currently available.
E element() Retrieves, but does not remove, the head of this queue.
Inserts the specified element into this queue if it is possible to do so immediately
boolean offer(E e)
without violating capacity restrictions.
Retrieves, but does not remove, the head of this queue, or returns null if this queue is
E peek( )
empty.
E poll( ) Retrieves and removes the head of this queue, or returns null if this queue is empty.
E remove( ) Retrieves and removes the head of this queue.

3
22PC1IT201 UNIT - V OOP Through Java

Set Interfaces
• The Set interface is a collection of objects that stores a without specific order.
• Elements can be inserted or accessed by their position in the set.
• A set does not allow duplicate elements.
• A list allows at most one null value.
• Syntax: interface Set<E> extends Collection<E>
• The class implement a list interface: HashSet, LinkedHashSet

Map Interfaces
• An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most
one value.
• This interface takes the place of the Dictionary class, which was a totally abstract class rather than an
interface.
• Syntax: interface Map<K,V>
Here, K - the type of keys maintained by this map, and V - the type of mapped values
• The Map interface provides three collection views, which allow a map's contents to be viewed as a set of
keys, collection of values, or set of key-value mappings.
• The order of a map is defined as the order in which the iterators on the map's collection views return their
elements.
• Some map implementations, like the TreeMap class, make specific guarantees as to their order; others,
like the HashMap class, do not.
• A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.
• Nested class
Interface Description
static interface Map.Entry<K, V> A map entry (key-value pair).

• Methods
Method Description
default V compute(K key, BiFunction<? Attempts to compute a mapping for the specified key and
super K,? super V,? its current mapped value (or null if there is no current
extends V> remappingFunction) mapping).
If the specified key is not already associated with a value
default V
(or is mapped to null), attempts to compute its value using
computeIfAbsent(K key, Function<?
the given mapping function and enters it into this map
super K,? extends V> mappingFunction)
unless null.
default V
If the value for the specified key is present and non-null,
computeIfPresent(K key, BiFunction<?
attempts to compute a new mapping given the key and its
super K,? super V,?
current mapped value.
extends V> remappingFunction)
Returns true if this map contains a mapping for the
boolean containsKey(Object key)
specified key.
Returns true if this map maps one or more keys to the
boolean containsValue(Object value)
specified value.
Returns a Set view of the mappings contained in this
Set<Map.Entry<K,V>> entrySet()
map.
boolean equals(Object o) Compares the specified object with this map for equality.
default void forEach(BiConsumer<? Performs the given action for each entry in this map until
4
22PC1IT201 UNIT - V OOP Through Java

super K,? super V> action) all entries have been processed or the action throws an
exception.
Returns the value to which the specified key is mapped,
V get(Object key)
or null if this map contains no mapping for the key.
Returns the value to which the specified key is mapped,
default V
or defaultValue if this map contains no mapping for the
getOrDefault(Object key, V defaultValue)
key.
int hashCode() Returns the hash code value for this map.
boolean isEmpty() Returns true if this map contains no key-value mappings.
Set<K> keySet() Returns a Set view of the keys contained in this map.
default V
If the specified key is not already associated with a value
merge(K key, V value, BiFunction<?
or is associated with null, associates it with the given non-
super V,? super V,?
null value.
extends V> remappingFunction)
Associates the specified value with the specified key in
V put(K key, V value)
this map (optional operation).
void putAll(Map<? extends K,? Copies all of the mappings from the specified map to this
extends V> m) map (optional operation).
If the specified key is not already associated with a value
default V putIfAbsent(K key, V value) (or is mapped to null) associates it with the given value
and returns null, else returns the current value.
Removes the mapping for a key from this map if it is
V remove(Object key)
present (optional operation).
default boolean Removes the entry for the specified key only if it is
remove(Object key, Object value) currently mapped to the specified value.
Replaces the entry for the specified key only if it is
default V replace(K key, V value)
currently mapped to some value.
default boolean Replaces the entry for the specified key only if currently
replace(K key, V oldValue, V newValue) mapped to the specified value.
Replaces each entry's value with the result of invoking the
default void replaceAll(BiFunction<?
given function on that entry until all entries have been
super K,? super V,? extends V> function)
processed or the function throws an exception.
int size( ) Returns the number of key-value mappings in this map.
Returns a Collection view of the values contained in this
Collection<V> values( )
map.

5
22PC1IT201 UNIT - V OOP Through Java

ArrayList class
• It provides dynamic arrays that can grow as needed.
• It is similar to an array, but its size can be dynamically changed.
• ArrayList class is part of the java.util package.
• Syntax to create object: ArrayList<T> name = new ArrayList<>( );
• Example: ArrayList<String> stringList = new ArrayList<>( );
• The important points about the Java ArrayList class are:
✓ Java ArrayList class can contain duplicate elements.
✓ Java ArrayList class maintains insertion order.
✓ Java ArrayList class is non synchronized.
✓ Java ArrayList allows random access because the array works on an index basis.
✓ 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.
✓ Java ArrayList 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.
• Class: public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
• Constructors
Constructor Description
ArrayList( ) Constructs an empty list with an initial capacity of ten.
Constructs a list containing the elements of the specified
ArrayList(Collection<? extends E> c) collection, in the order they are returned by the collection's
iterator.
ArrayList(int initialCapacity) Constructs an empty list with the specified initial capacity.

• Methods:
Method Description
It is used to insert the specified element at the specified
void add(int index, E element)
position in a list.
It is used to append the specified element at the end of a
boolean add(E e)
list.
It is used to append all of the elements in the specified
boolean addAll(Collection<? extends E> c) collection to the end of this list, in the order that they are
returned by the specified collection's iterator.
boolean addAll(int index, Collection<? It is used to append all the elements in the specified
extends E> c) collection, 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 requiredCapacity) It is used to enhance the capacity of an ArrayList instance.
It is used to fetch the element from the particular position
E get(int index)
of the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
It is used to return the index in this list of the last
int lastIndexOf(Object o) occurrence of the specified element, or -1 if the list does
not contain this element.
It is used to return an array containing all of the elements
Object[] toArray()
in this list in the correct order.
<T> T[] toArray(T[] a) It is used to return an array containing all of the elements
6
22PC1IT201 UNIT - V OOP Through Java

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.
It is used to return the index in this list of the first
int indexOf(Object o) occurrence of the specified element, or -1 if the List does
not contain this element.
It is used to remove the element present at the specified
E remove(int index)
position in the list.
It is used to remove the first occurrence of the specified
boolean remove(Object o)
element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super E> It is used to remove all the elements from the list that
filter) satisfies the given predicate.
protected void removeRange(int fromIndex, It is used to remove all the elements lies within the given
int toIndex) range.
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with the
operator) specified element.
It is used to retain all the elements in the list that are
void retainAll(Collection<?> c)
present in the specified collection.
It is used to replace the specified element in the list,
E set(int index, E element)
present at the specified position.
It is used to sort the elements of the list on the basis of the
void sort(Comparator<? super E> c)
specified comparator.
Spliterator<E> spliterator() It is used to create a spliterator over the elements in a list.
It is used to fetch all the elements that lies within the
List<E> subList(int fromIndex, int toIndex)
given range.
It is used to return the number of elements present in the
int size()
list.
It is used to trim the capacity of this ArrayList instance to
void trimToSize()
be the list's current size.

Example: Demonstrate the all operations in ArrayList class.


import java.util.*;
public class Main {
public static void main(String[] args) {
//ArrayList Creation
ArrayList<Integer> roll = new ArrayList<Integer>();
//adding elements
roll.add(60);
roll.add(20);
roll.add(30);
roll.add(30);
roll.add(40);

//traversing
System.out.println("Elements in Collection");
for(Integer itr : roll) {
System.out.print(itr+" ");
}
//adding element in particular index
roll.add(4,50);
//traversing
7
22PC1IT201 UNIT - V OOP Through Java

System.out.println("\nElements in Collection after adding ");


for(Integer itr : roll) {
System.out.print(itr+" ");
}

//sorting
Collections.sort(roll);
//traversing
System.out.println("\nElements after sorting");
for(Integer itr : roll) {
System.out.print(itr+" ");
}

//remove element based on index


roll.remove(3);
//traversing
System.out.println("\nElements after remove element at 3rd index");
for(Integer itr : roll) {
System.out.print(itr+" ");
}

//searching
System.out.print("\nsearch for the element 30: ");
if(roll.contains(30))
System.out.println("found");
else
System.out.println("not found");
}
}

Output:
Elements in Collection
60 20 30 30 40
Elements in Collection after adding
60 20 30 30 50 40
Elements after sorting
20 30 30 40 50 60
Elements after remove element at 3rd index
20 30 30 50 60
search for the element 30: found

8
22PC1IT201 UNIT - V OOP Through Java

LinkedList class
• The LinkedList class extends AbstractSequentialList and implements the List, Deque, and Queue
interfaces.
• It provides a linked-list data structure.
• The important points are:
✓ Java LinkedList class can contain duplicate elements.
✓ Java LinkedList class maintains insertion order.
✓ Java LinkedList class is non synchronized.
✓ In Java LinkedList class, manipulation is fast because no shifting needs to occur.
✓ Java LinkedList class can be used as a list, stack or queue.
• Class: public class LinkedList<E> extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, Serializable
• Constructors
Constructor Description
LinkedList( ) It is used to construct an empty list.
It is used to construct a list containing the elements of the
LinkedList(Collection<? extends E> c) specified collection, in the order, they are returned by the
collection's iterator.
• Methods
Method Description
It is used to append the specified element to the end of a
boolean add(E e)
list.
It is used to insert the specified element at the specified
void add(int index, E element)
position index in a list.
It is used to append all of the elements in the specified
boolean addAll(Collection<? extends E> c) collection to the end of this list, in the order that they are
returned by the specified collection's iterator.
It is used to append all of the elements in the specified
boolean addAll(Collection<? extends E> c) collection to the end of this list, in the order that they are
returned by the specified collection's iterator.
boolean addAll(int index, Collection<? It is used to append all the elements in the specified
extends E> c) collection, starting at the specified position of the list.
It is used to insert the given element at the beginning of a
void addFirst(E e)
list.
void addLast(E e) It is used to append the given element to the end of a list.
void clear( ) It is used to remove all the elements from a list.
Object clone( ) It is used to return a shallow copy of an ArrayList.
It is used to return true if a list contains a specified
boolean contains(Object o)
element.
It is used to return an iterator over the elements in a deque
Iterator<E> descendingIterator()
in reverse sequential order.
E element( ) It is used to retrieve the first element of a list.
It is used to return the element at the specified position in a
E get(int index)
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.
It is used to return the index in a list of the first occurrence
int indexOf(Object o) of the specified element, or -1 if the list does not contain
any element.

9
22PC1IT201 UNIT - V OOP Through Java

It is used to return the index in a list of the last occurrence


int lastIndexOf(Object o) of the specified element, or -1 if the list does not contain
any element.
It is used to return a list-iterator of the elements in proper
ListIterator<E> listIterator(int index)
sequence, 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
It retrieves the first element of a list or returns null if a list
E peekFirst( )
is empty.
It retrieves the last element of a list or returns null if a list
E peekLast( )
is empty.
E poll( ) It retrieves and removes the first element of a list.
It retrieves and removes the first element of a list, or
E pollFirst( )
returns null if a list is empty.
It retrieves and removes the last element of a list, or returns
E pollLast( )
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.
It is used to remove the element at the specified position in
E remove(int index)
a list.
It is used to remove the first occurrence of the specified
boolean remove(Object o)
element in a list.
E removeFirst( ) It removes and returns the first element from a list.
It is used to remove the first occurrence of the specified
boolean removeFirstOccurrence(Object o)
element in a list (when traversing the list from head to tail).
E removeLast( ) It removes and returns the last element from a list.
It removes the last occurrence of the specified element in a
boolean removeLastOccurrence(Object o)
list (when traversing the list from head to tail).
It replaces the element at the specified position in a list
E set(int index, E element)
with the specified element.
It is used to return an array containing all the elements in a
Object[ ] toArray( )
list in proper sequence (from first to the last element).
It returns an array containing all the elements in the proper
<T> T[ ] toArray(T[ ] a) 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: Demonstrate the all operations in LinkedList class.


import java.util.*;
public class Main {
public static void main(String[] args) {
//LinkedList Creation
LinkedList<Integer> roll = new LinkedList<Integer>();
//adding elements
roll.add(20);
roll.add(30);
roll.add(10);
roll.add(40);
roll.add(40);
10
22PC1IT201 UNIT - V OOP Through Java

//traversing
System.out.println("Elements in Collection");
for(Integer itr : roll) {
System.out.print(itr+" ");
}
//adding element in particular index
roll.add(4,50);
//adding element at first
roll.addFirst(60);
//adding element at last
roll.addLast(70);
//traversing
System.out.println("\nElements in Collection after adding ");
for(Integer itr : roll) {
System.out.print(itr+" ");
}

//sorting
Collections.sort(roll);
//traversing
System.out.println("\nElements after sorting");
for(Integer itr : roll) {
System.out.print(itr+" ");
}
//remove element based on index
roll.remove(3);
//traversing
System.out.println("\nElements after remove element at 3rd index");
for(Integer itr : roll) {
System.out.print(itr+" ");
}
//searching
System.out.print("\nsearch for the element 90: ");
if(roll.contains(90))
System.out.println("found");
else
System.out.println("not found");
}
}
Output:
Elements in Collection
20 30 10 40 40
Elements in Collection after adding
60 20 30 10 40 50 40 70
Elements after sorting
10 20 30 40 40 50 60 70
Elements after remove element at 3rd index
10 20 30 40 50 60 70
search for the element 90: not found

11
22PC1IT201 UNIT - V OOP Through Java

Vector class
• Vector is like the dynamic array which can grow or shrink its size.
• 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-
✓ Vector is synchronized.
✓ Java Vector contains many legacy methods that are not the part of a collection’s framework.
• Class: public class Vector<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable

• 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 capacity
capacityIncrement) and capacity increment.
Vector( Collection<? extends E> c) It constructs a vector that contains the elements of a collection
c.

• Methods:
Modifier and Type Method and Description
boolean add(E e) Appends the specified element to the end of this Vector.
Inserts the specified element at the specified position in
void add(int index, E element)
this Vector.
Appends all of the elements in the specified Collection
boolean addAll(Collection<? extends E> c) to the end of this Vector, in the order that they are
returned by the specified Collection's Iterator.
boolean addAll(int index, Collection<? Inserts all of the elements in the specified Collection
extends E> c) into this Vector at the specified position.
Adds the specified component to the end of this vector,
void addElement(E obj)
increasing its size by one.
int capacity() Returns the current capacity of this vector.
void clear() Removes all of the elements from this Vector.
Object clone() Returns a clone of this vector.
Returns true if this vector contains the specified
boolean contains(Object o)
element.
Returns true if this Vector contains all of the elements in
boolean containsAll(Collection<?> c)
the specified Collection.
Copies the components of this vector into the specified
void copyInto(Object[] anArray)
array.
E elementAt(int index) Returns the component at the specified index.
Returns an enumeration of the components of this
Enumeration<E> elements()
vector.
Increases the capacity of this vector, if necessary, to
void ensureCapacity(int minCapacity) ensure that it can hold at least the number of
components specified by the minimum capacity
12
22PC1IT201 UNIT - V OOP Through Java

argument.
Compares the specified Object with this Vector for
boolean equals(Object o)
equality.
Returns the first component (the item at index 0) of this
E firstElement()
vector.
Performs the given action for each element of
void forEach(Consumer<? super E> action) the Iterable until all elements have been processed or the
action throws an exception.
Returns the element at the specified position in this
E get(int index)
Vector.
int hashCode() Returns the hash code value for this Vector.
Returns the index of the first occurrence of the specified
int indexOf(Object o) element in this vector, or -1 if this vector does not
contain the element.
Returns the index of the first occurrence of the specified
int indexOf(Object o, int index) element in this vector, searching forwards from index,
or returns -1 if the element is not found.
Inserts the specified object as a component in this vector
void insertElementAt(E obj, int index)
at the specified index.
boolean isEmpty() Tests if this vector has no components.
Returns an iterator over the elements in this list in
Iterator<E> iterator()
proper sequence.
E lastElement() Returns the last component of the vector.
Returns the index of the last occurrence of the specified
int lastIndexOf(Object o) element in this vector, or -1 if this vector does not
contain the element.
Returns the index of the last occurrence of the specified
int lastIndexOf(Object o, int index) element in this vector, searching backwards from index,
or returns -1 if the element is not found.
Returns a list iterator over the elements in this list (in
ListIterator<E> listIterator()
proper sequence).
Returns a list iterator over the elements in this list (in
ListIterator<E> listIterator(int index) proper sequence), starting at the specified position in the
list.
Removes the element at the specified position in this
E remove(int index)
Vector.
Removes the first occurrence of the specified element in
boolean remove(Object o) this Vector If the Vector does not contain the element, it
is unchanged.
Removes from this Vector all of its elements that are
boolean removeAll(Collection<?> c)
contained in the specified Collection.
Removes all components from this vector and sets its
void removeAllElements()
size to zero.
Removes the first (lowest-indexed) occurrence of the
boolean removeElement(Object obj)
argument from this vector.
void removeElementAt(int index) Deletes the component at the specified index.
boolean removeIf(Predicate<? Removes all of the elements of this collection that
super E> filter) satisfy the given predicate.
protected void removeRange(int fromIndex, Removes from this list all of the elements whose index
int toIndex) is between fromIndex, inclusive, and toIndex, exclusive.
void Replaces each element of this list with the result of
replaceAll(UnaryOperator<E> operator) applying the operator to that element.
boolean retainAll(Collection<?> c) Retains only the elements in this Vector that are
13
22PC1IT201 UNIT - V OOP Through Java

contained in the specified Collection.


Replaces the element at the specified position in this
E set(int index, E element)
Vector with the specified element.
Sets the component at the specified index of this vector
void setElementAt(E obj, int index)
to be the specified object.
void setSize(int newSize) Sets the size of this vector.
int size() Returns the number of components in this vector.
Sorts this list according to the order induced by the
void sort(Comparator<? super E> c)
specified Comparator.
Creates a late-binding and fail-fast Spliterator over the
Spliterator<E> spliterator()
elements in this list.
Returns a view of the portion of this List between
List<E> subList(int fromIndex, int toIndex)
fromIndex, inclusive, and toIndex, exclusive.
Returns an array containing all of the elements in this
Object[] toArray()
Vector in the correct order.
Returns an array containing all of the elements in this
<T> T[] toArray(T[] a) Vector in the correct order; the runtime type of the
returned array is that of the specified array.
Returns a string representation of this Vector, containing
String toString()
the String representation of each element.
Trims the capacity of this vector to be the vector's
void trimToSize()
current size.

Example: Demonstrate the all operations in Vector class.


import java.util.*;
public class Main {
public static void main(String[] args) {
//Vector Creation
Vector<Integer> roll = new Vector<Integer>();
//adding elements
roll.add(20);
roll.add(30);
roll.add(10);
roll.add(40);
roll.add(40);

//traversing
System.out.print("Elements in Collection :");
Enumeration<Integer> en = roll.elements();
while (en.hasMoreElements()){
System.out.print(en.nextElement()+" ");
}

//adding element in particular index


roll.add(4,50);
System.out.println("\nElements in Collection after adding :"+roll);

//sorting
Collections.sort(roll);
//traversing
System.out.println("Elements after sorting :"+roll);

//remove element based on index


14
22PC1IT201 UNIT - V OOP Through Java

roll.remove(3);
//traversing
System.out.println("Elements after remove element at 3rd index :"+roll);

//searching
System.out.print("search for the element 90: ");
if(roll.contains(90))
System.out.println("found");
else
System.out.println("not found");
}
}
Output:
Elements in Collection :20 30 10 40 40
Elements in Collection after adding :[20, 30, 10, 40, 50, 40]
Elements after sorting :[10, 20, 30, 40, 40, 50]
Elements after remove element at 3rd index :[10, 20, 30, 40, 50]
search for the element 90: not found

15
22PC1IT201 UNIT - V OOP Through Java

HashSet class
• Java HashSet class is used to create a collection that uses a hash table for storage.
• The important points about Java HashSet class are:
✓ HashSet stores the elements by using a mechanism called hashing.
✓ HashSet contains unique elements only.
✓ HashSet allows null value.
✓ HashSet class is non synchronized.
✓ HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their
hashcode.
✓ HashSet is the best approach for search operations.
Syntax: public class HashSet<E> extends AbstractSet<E>
implements Set<E>, Cloneable, Serializable
• Constructor
Constructor Description
Constructs a new, empty set; the
HashSet() backing HashMap instance has default initial capacity
(16) and load factor (0.75).
Constructs a new set containing the elements in the
HashSet(Collection<? extends E> c)
specified collection.
Constructs a new, empty set; the
HashSet(int initialCapacity) backing HashMap instance has the specified initial
capacity and default load factor (0.75).
Constructs a new, empty set; the
HashSet(int initialCapacity, float loadFactor) backing HashMap instance has the specified initial
capacity and the specified load factor.

• Methods:
Method Description
boolean add(E e) Adds the specified element to this set if it is not already present.
void clear() Removes all of the elements from this set.
Object clone() Returns a shallow copy of this HashSet instance: the elements
themselves are not cloned.
boolean contains(Object o) Returns true if this set contains the specified element.
boolean isEmpty() Returns true if this set contains no elements.
Iterator<E> iterator() Returns an iterator over the elements in this set.
boolean remove(Object o) Removes the specified element from this set if it is present.
int size() Returns the number of elements in this set (its cardinality).
Spliterator<E> spliterator() Creates a late-binding and fail-fast Spliterator over the elements in this
set.

16
22PC1IT201 UNIT - V OOP Through 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.
• The important points about the Java LinkedHashSet class are:
✓ Java LinkedHashSet class contains unique elements only like HashSet.
✓ Java LinkedHashSet class provides all optional set operations and permits null elements.
✓ Java LinkedHashSet class is non-synchronized.
✓ Java LinkedHashSet class maintains insertion order.
• Syntax: public class LinkedHashSet<E> extends HashSet<E>
implements Set<E>, Cloneable, Serializable

Constructor Description
Constructs a new, empty linked hash set with the default
LinkedHashSet()
initial capacity (16) and load factor (0.75).
LinkedHashSet(Collection<? Constructs a new linked hash set with the same elements as
extends E> c) the specified collection.
Constructs a new, empty linked hash set with the specified
LinkedHashSet(int initialCapacity)
initial capacity and the default load factor (0.75).
LinkedHashSet(int initialCapacity, Constructs a new, empty linked hash set with the specified
float loadFactor) initial capacity and load factor.

• TreeSet
A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural
ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
• This implementation provides guaranteed log(n) time cost for the basic operations
(add, remove and contains).
• The objects of the TreeSet class are stored in ascending order.
• The important points about the Java TreeSet class are:
✓ Java TreeSet class contains unique elements only like HashSet.
✓ Java TreeSet class access and retrieval times are quiet fast.
✓ Java TreeSet class doesn't allow null element.
✓ Java TreeSet class is non synchronized.
✓ Java TreeSet class maintains ascending order.
✓ The TreeSet can only allow those generic types that are comparable. For example The Comparable
interface is being implemented by the StringBuffer class.
✓ Syntax: public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, Serializable
Constructor Description
Constructs a new, empty tree set, sorted according to the
TreeSet()
natural ordering of its elements.
Constructs a new tree set containing the elements in the
TreeSet(Collection<? extends E> c) specified collection, sorted according to the natural
ordering of its elements.
TreeSet(Comparator<? Constructs a new, empty tree set, sorted according to the
super E> comparator) specified comparator.
Constructs a new tree set containing the same elements and
TreeSet(SortedSet<E> s)
using the same ordering as the specified sorted set.

17
22PC1IT201 UNIT - V OOP Through Java

Method Description
boolean add(E e) Adds the specified element to this set if it is not already
present.
boolean addAll(Collection<? extends E> Adds all of the elements in the specified collection to this
c) set.
E ceiling(E e) Returns the least element in this set greater than or equal to
the given element, or null if there is no such element.
void clear() Removes all of the elements from this set.
Object clone() Returns a shallow copy of this TreeSet instance.
Comparator<? super E> comparator() Returns the comparator used to order the elements in this set,
or null if this set uses the natural ordering of its elements.
boolean contains(Object o) Returns true if this set contains the specified element.
Iterator<E> descendingIterator() Returns an iterator over the elements in this set in
descending order.
NavigableSet<E> descendingSet() Returns a reverse order view of the elements contained in
this set.
E first() Returns the first (lowest) element currently in this set.
E floor(E e) Returns the greatest element in this set less than or equal to
the given element, or null if there is no such element.
SortedSet<E> headSet(E toElement) Returns a view of the portion of this set whose elements are
strictly less than toElement.
NavigableSet<E> headSet(E toElement, Returns a view of the portion of this set whose elements are
boolean inclusive) less than (or equal to, if inclusive is true) toElement.
E higher(E e) Returns the least element in this set strictly greater than the
given element, or null if there is no such element.
boolean isEmpty() Returns true if this set contains no elements.
Iterator<E> iterator() Returns an iterator over the elements in this set in ascending
order.
E last() Returns the last (highest) element currently in this set.
E lower(E e) Returns the greatest element in this set strictly less than the
given element, or null if there is no such element.
E pollFirst() Retrieves and removes the first (lowest) element, or
returns null if this set is empty.
E pollLast() Retrieves and removes the last (highest) element, or
returns null if this set is empty.
boolean remove(Object o) Removes the specified element from this set if it is present.
int size() Returns the number of elements in this set (its cardinality).
Spliterator<E> spliterator() Creates a late-binding and fail-fast Spliterator over the
elements in this set.
NavigableSet<E> subSet(E fromElement, Returns a view of the portion of this set whose elements
boolean fromInclusive, E toElement, range from fromElement to toElement.
boolean toInclusive)
SortedSet<E> subSet(E fromElement, E Returns a view of the portion of this set whose elements
toElement) range from fromElement, inclusive, to toElement, exclusive.
SortedSet<E> tailSet(E fromElement) Returns a view of the portion of this set whose elements are
greater than or equal to fromElement.
NavigableSet<E> tailSet(E fromElement, Returns a view of the portion of this set whose elements are
boolean inclusive) greater than (or equal to, if inclusive is true) fromElement.

18
22PC1IT201 UNIT - V OOP Through Java

HashMap
• 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.
• Important points -
✓ 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.
✓ It maintains order.
Syntax: public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
Constructor Description
Constructs an empty HashMap with the default initial capacity
HashMap()
(16) and the default load factor (0.75).
Constructs an empty HashMap with the specified initial
HashMap(int initialCapacity)
capacity and the default load factor (0.75).
HashMap(int initialCapacity, Constructs an empty HashMap with the specified initial
float loadFactor) capacity and load factor.
HashMap(Map<? extends K,? Constructs a new HashMap with the same mappings as the
extends V> m) specified Map.

Method Description
void clear( ) Removes all of the mappings from this map.
Object clone() Returns a shallow copy of this HashMap instance: the keys and
values themselves are not cloned.
V compute(K key, BiFunction<? super Attempts to compute a mapping for the specified key and its
K,? super V,? extends V> current mapped value (or null if there is no current mapping).
remappingFunction)
V computeIfAbsent(K key, If the specified key is not already associated with a value (or is
Function<? super K,? extends V> mapped to null), attempts to compute its value using the given
mappingFunction) mapping function and enters it into this map unless null.
V computeIfPresent(K key, If the value for the specified key is present and non-null,
BiFunction<? super K,? super V,? attempts to compute a new mapping given the key and its
extends V> remappingFunction) current mapped value.
boolean containsKey(Object key) Returns true if this map contains a mapping for the specified
key.
boolean containsValue(Object value) Returns true if this map maps one or more keys to the specified
value.
Set<Map.Entry<K,V>> entrySet() Returns a Set view of the mappings contained in this map.
void forEach(BiConsumer<? super K,? Performs the given action for each entry in this map until all
super V> action) entries have been processed or the action throws an exception.
V get(Object key) Returns the value to which the specified key is mapped,
or null if this map contains no mapping for the key.
V getOrDefault(Object key, V Returns the value to which the specified key is mapped,
defaultValue) or defaultValue if this map contains no mapping for the key.
boolean isEmpty() Returns true if this map contains no key-value mappings.
Set<K> keySet() Returns a Set view of the keys contained in this map.
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 value.
extends V> remappingFunction)
19
22PC1IT201 UNIT - V OOP Through Java

V put(K key, V value) Associates the specified value with the specified key in this
map.
void putAll(Map<? extends K,? Copies all of the mappings from the specified map to this map.
extends V> m)
V putIfAbsent(K key, V value) If the specified key is not already associated with a value (or is
mapped to null) associates it with the given value and
returns null, else returns the current value.
V remove(Object key) Removes the mapping for the specified key from this map if
present.
boolean remove(Object key, Object Removes the entry for the specified key only if it is currently
value) mapped to the specified value.
V replace(K key, V value) Replaces the entry for the specified key only if it is currently
mapped to some value.
boolean replace(K key, V oldValue, V Replaces the entry for the specified key only if currently
newValue) mapped to the specified value.
void replaceAll(BiFunction<? super 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.
int size() Returns the number of key-value mappings in this map.
Collection<V> values() Returns a Collection view of the values contained in this map.

20
22PC1IT201 UNIT - V OOP Through Java

Hashtable
• Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary class and
implements the Map interface.
✓ A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is identified
by calling the hashcode() method. A Hashtable contains values based on the key.
✓ Java Hashtable class contains unique elements.
✓ Java Hashtable class doesn't allow null key or value.
✓ Java Hashtable class is synchronized.
✓ The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
Syntax: public class Hashtable<K,V> extends Dictionary<K,V>
implements Map<K,V>, Cloneable, Serializable

Constructor Description
Constructs a new, empty hashtable with a default
Hashtable( )
initial capacity (11) and load factor (0.75).
Constructs a new, empty hashtable with the specified
Hashtable(int initialCapacity)
initial capacity and default load factor (0.75).
Constructs a new, empty hashtable with the specified
Hashtable(int initialCapacity, float loadFactor)
initial capacity and the specified load factor.
Constructs a new hashtable with the same mappings as
Hashtable(Map<? extends K,? extends V> t)
the given Map.

Method Description
void clear() Clears this hashtable so that it contains no keys.
Object clone() Creates a shallow copy of this hashtable.
Attempts to compute a mapping for the specified key
V compute(K key, BiFunction<? super K,?
and its current mapped value (or null if there is no
super V,? extends V> remappingFunction)
current mapping).
If the specified key is not already associated with a
V computeIfAbsent(K key, Function<? super value (or is mapped to null), attempts to compute its
K,? extends V> mappingFunction) value using the given mapping function and enters it
into this map unless null.
If the value for the specified key is present and non-
V computeIfPresent(K key, BiFunction<? super
null, attempts to compute a new mapping given the
K,? super V,? extends V> remappingFunction)
key and its current mapped value.
Tests if some key maps into the specified value in this
boolean contains(Object value)
hashtable.
boolean containsKey(Object key) Tests if the specified object is a key in this hashtable.
Returns true if this hashtable maps one or more keys to
boolean containsValue(Object value)
this value.
Enumeration<V> elements() Returns an enumeration of the values in this hashtable.
Returns a Set view of the mappings contained in this
Set<Map.Entry<K,V>> entrySet()
map.
Compares the specified Object with this Map for
boolean equals(Object o)
equality, as per the definition in the Map interface.
Performs the given action for each entry in this map
void forEach(BiConsumer<? super K,? super
until all entries have been processed or the action
V> action)
throws an exception.
V get(Object key) Returns the value to which the specified key is
21
22PC1IT201 UNIT - V OOP Through Java

mapped, or null if this map contains no mapping for


the key.
Returns the value to which the specified key is
V getOrDefault(Object key, V defaultValue) mapped, or defaultValue if this map contains no
mapping for the key.
Returns the hash code value for this Map as per the
int hashCode()
definition in the Map interface.
boolean isEmpty() Tests if this hashtable maps no keys to values.
Enumeration<K> keys() Returns an enumeration of the keys in this hashtable.
Set<K> keySet() Returns a Set view of the keys contained in this map.
If the specified key is not already associated with a
V merge(K key, V value, BiFunction<? super
value or is associated with null, associates it with the
V,? super V,? extends V> remappingFunction)
given non-null value.
Maps the specified key to the specified value in this
V put(K key, V value)
hashtable.
Copies all of the mappings from the specified map to
void putAll(Map<? extends K,? extends V> t)
this hashtable.
If the specified key is not already associated with a
V putIfAbsent(K key, V value) value (or is mapped to null) associates it with the given
value and returns null, else returns the current value.
Increases the capacity of and internally reorganizes
protected void rehash( ) this hashtable, in order to accommodate and access its
entries more efficiently.
Removes the key (and its corresponding value) from
V remove(Object key)
this hashtable.
Removes the entry for the specified key only if it is
boolean remove(Object key, Object value)
currently mapped to the specified value.
Replaces the entry for the specified key only if it is
V replace(K key, V value)
currently mapped to some value.
boolean replace(K key, V oldValue, V Replaces the entry for the specified key only if
newValue) currently mapped to the specified value.
Replaces each entry's value with the result of invoking
void replaceAll(BiFunction<? super K,? super
the given function on that entry until all entries have
V,? extends V> function)
been processed or the function throws an exception.
int size( ) Returns the number of keys in this hashtable.
Returns a string representation of this Hashtable object
in the form of a set of entries, enclosed in braces and
String toString( )
separated by the ASCII characters ", " (comma and
space).
Returns a Collection view of the values contained in
Collection<V> values( )
this map.

22
22PC1IT201 UNIT - V OOP Through Java

Retrieving Elements from Collections


There are different ways to retrieve the elements from collection as follows
1. using for
2. using for-each
3. using Iterator
• Iterator is an interface is used to traverse the elements of a collection.
• It traverse the elements in only forward direction only.
• The Iterator interface has four methods:
• hasNext(): This method returns true if there is another element in the collection, false otherwise.
• next(): This method returns the next element in the collection.
• remove(): This method removes the current element from the collection.
• forEachRemaining(): This method performs the given operation on each remaining element in the
collection. using ListIterator

4. using ListIterator
• It extends the Iterator interface and provides additional functionality for bidirectional iteration and
modification of lists.
• The ListIterator interface has following methods:
• hasNext(): This method returns true if there is another element in the collection, false otherwise.
• next(): This method returns the next element in the collection.
• remove(): This method removes the current element from the collection.
• hasPrevious(): This method returns true if there is another element in previously in the collection,
false otherwise.
• previous(): This method returns the previous element in the collection.
• set(): This method update the element in the collection.

5. using Enumeration
• Enumeration is an interface that defines the methods to get a series of elements from a collection of
objects taking one at a time.
• The Enumeration interface has the following methods:
• boolean hasMoreElements( ): This method returns true if there are more elements in the
enumeration, false otherwise.
• Object nextElement( ): This method returns the next element in the enumeration. If there are no
more elements in the enumeration, it throws a NoSuchElementException.

Example:
import java.util.*;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<Integer> marks = new ArrayList<>();
marks.add(89);
marks.add(99);
marks.add(78);
marks.add(75);
marks.add(99);
marks.add(99);
marks.add(99);
marks.add(99);
System.out.println("Collection object :"+marks);
System.out.println("using for:");
23
22PC1IT201 UNIT - V OOP Through Java

for(int i=0;i<marks.size();i++){
System.out.print(marks.get(i)+" ");
}

System.out.println("\nusing for-each:");
for(Integer i:marks){
System.out.print(i+" ");
}
System.out.println("\nusing iterator:");
Iterator<Integer> itr = marks.iterator();
while (itr.hasNext()) {
System.out.print(itr.next()+" ");
}
System.out.println("\nusing list iterator:");
ListIterator<Integer>litr = marks.listIterator(3);
while (litr.hasNext()){
System.out.print(litr.next()+" ");
}
System.out.println("\nusing list iterator:");
ListIterator<Integer> litr2 = marks.listIterator(3);
while (litr2.hasPrevious()){
System.out.print(litr2.previous()+" ");
}
System.out.println("\nusing enumeration:");
Enumeration<Integer> en = Collections.enumeration(marks);
while (en.hasMoreElements()){
System.out.print(en.nextElement()+" ");
}
}
}

24
22PC1IT201 UNIT - V OOP Through Java

Sorting using Comparable and Comparator.


Comparable:
• Comparable interface compares the objects in meaningful ways.
• Syntax: interface Comparable<T>
Here, T represents the type of objects being compared.
• Comparable is defines the compareTo( ) method. This method is used to compare two objects of the
same class.
• Syntax: int compareTo(T obj)
• The return value of the compareTo( ) method is an integer that indicates whether the first object is less
than, equal to, or greater than the second object.
• Note: This interface is implemented by several of the classes already, example Byte, Character, Double,
Float, Long, Short, String, and Integer classes.
Example:
import java.util.*;
class Student implements Comparable<Student>{
int roll;
String name;
public Student(int roll, String name) {
this.roll = roll;
this.name = name;
}
@Override
public int compareTo(Student o) {
return roll - o.roll;
}
}
public class CollectionDemo {
public static void main(String[] args) {
ArrayList<Student> st = new ArrayList<>();
st.add(new Student(5,"Apple"));
st.add(new Student(3,"Mango"));
st.add(new Student(2,"Banana"));
st.add(new Student(4,"Orange"));
System.out.println("Student List:");
for (Student s : st){
System.out.println(s.roll+" - "+s.name);
}
Collections.sort(st);
System.out.println("\nSorting by roll:");
for (Student s : st){
System.out.println(s.roll+" - "+s.name);
}
}
}
output:
Student List:
5 - Apple
3 - Mango
2 - Banana
4 - Orange
Sorting by roll:
2 - Banana
3 - Mango

25
22PC1IT201 UNIT - V OOP Through Java

4 - Orange
5 - Apple

Comparator
• Comparator interface compares the objects in meaningful ways.
• Syntax: interface Comparator<T>
Here, T represents the type of objects being compared.
• Comparator is defines the compare( ), and equals( ) method.
• compare( ) method is used to compare two objects of any class.
• Syntax: int compare(T obj1, T obj2)
• The return value of the compare( ) method is an integer that indicates whether the first object is less than,
equal to, or greater than the second object.
• equals( ) method is used to tests whether an object equals the invoking comparator.
• Syntax: boolean equals(object obj)
• The method returns true if obj and the invoking object are both Comparator objects and use the same
ordering. Otherwise, it returns false.

Example:
import java.util.*;
class Student {
int roll;
String name;
public Student(int roll, String name) {
this.roll = roll;
this.name = name;
}
}
public class CollectionDemo {
public static void main(String[] args) {
ArrayList<Student> st = new ArrayList<>();
st.add(new Student(5,"Apple"));
st.add(new Student(3,"Mango"));
st.add(new Student(2,"Banana"));
st.add(new Student(4,"Orange"));
System.out.println("Student List:");
for (Student s : st){
System.out.println(s.roll+" - "+s.name);
}
Comparator<Student> byroll = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.roll-o2.roll;
}
};
Comparator<Student> byname = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.name.compareTo(o2.name);
}
};

System.out.println("\nSorting by roll:");
Collections.sort(st, byroll);
26
22PC1IT201 UNIT - V OOP Through Java

for (Student s : st){


System.out.println(s.roll+" - "+s.name);
}

System.out.println("\nSorting by name:");
Collections.sort(st, byname);
for (Student s : st){
System.out.println(s.roll+" - "+s.name);
}
}
}
output:
Student List:
5 - Apple
3 - Mango
2 - Banana
4 - Orange

Sorting by roll:
2 - Banana
3 - Mango
4 - Orange
5 - Apple

Sorting by name:
5 - Apple
2 - Banana
3 - Mango
4 – Orange

27
22PC1IT201 UNIT - V OOP Through Java

StringTokenizer class
• The StringTokenizer class divide the text into a set of discrete parts, or tokens, which in a certain
sequence can convey a semantic meaning.
• To use StringTokenizer, you specify an input string and a string that contains delimiters. Delimiters are
characters that separate tokens.
• The default set of delimiters consists of the whitespace characters: space, tab, form feed, newline, and
carriage return.
• Constructors
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, boolean delimAsToken)
• The StringTokenizer class has the following methods

// Demonstrate StringTokenizer.
import java.util.StringTokenizer;
class STDemo {
static String in = "title=Java: The Complete Reference;" +
"author=Schildt;" +
"publisher=McGraw-Hill;" +
"copyright=2014";
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens()) {
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\t" + val);
}
}
}

Output:
title Java: The Complete Reference
author Schildt
publisher McGraw-Hill
copyright 2014

28
22PC1IT201 UNIT - V OOP Through Java

Arrays class
• The Arrays class provides various methods that are useful when working with arrays.
• These methods help bridge the gap between collections and arrays.
• The methods are mentioned as follow

1. asList( )
The asList( ) method returns a List that is backed by a specified array
Syntax: static <T> List asList(T... array)
2. binarySearch( )
The binarySearch( ) method uses a binary search to find a specified value. This method must be applied
to sorted arrays.
Here are some of its forms.
static int binarySearch(byte array[ ], byte value)
static int binarySearch(char array[ ], char value)
static int binarySearch(double array[ ], double value)
static int binarySearch(float array[ ], float value)
static int binarySearch(int array[ ], int value)
static int binarySearch(long array[ ], long value)
static int binarySearch(short array[ ], short value)
static int binarySearch(Object array[ ], Object value)
static <T> int binarySearch(T[ ] array, T value, Comparator<? super T> c)
3. copyOf( )
The copyOf( ) method returns a copy of an array and has the following forms:
static boolean[ ] copyOf(boolean[ ] source, int len)
static byte[ ] copyOf(byte[ ] source, int len)
static char[ ] copyOf(char[ ] source, int len)
static double[ ] copyOf(double[ ] source, int len)
static float[ ] copyOf(float[ ] source, int len)
static int[ ] copyOf(int[ ] source, int len)
static long[ ] copyOf(long[ ] source, int len)
static short[ ] copyOf(short[ ] source, int len)
static <T> T[ ] copyOf(T[ ] source, int len)
static <T,U> T[ ] copyOf(U[ ] source, int len, Class<? extends T[ ]> resultT)
4. copyOfRange( )
The copyOfRange( ) method returns a copy of a range within an array and has the following forms:
static boolean[ ] copyOfRange(boolean[ ] source, int start, int end)
static byte[ ] copyOfRange(byte[ ] source, int start, int end)
static char[ ] copyOfRange(char[ ] source, int start, int end)
static double[ ] copyOfRange(double[ ] source, int start, int end)
static float[ ] copyOfRange(float[ ] source, int start, int end)
static int[ ] copyOfRange(int[ ] source, int start, int end)
static long[ ] copyOfRange(long[ ] source, int start, int end)
static short[ ] copyOfRange(short[ ] source, int start, int end)
static <T> T[ ] copyOfRange(T[ ] source, int start, int end)
static <T,U> T[ ] copyOfRange(U[ ] source, int start, int end, Class<? extends T[ ]> resultT)
5. equals( )
The equals( ) method returns true if two arrays are equivalent. Otherwise, it returns
false. The equals( ) method has the following forms:
static boolean equals(boolean array1[ ], boolean array2 [ ])

29
22PC1IT201 UNIT - V OOP Through Java

static boolean equals(byte array1[ ], byte array2 [ ])


static boolean equals(char array1[ ], char array2 [ ])
static boolean equals(double array1[ ], double array2 [ ])
static boolean equals(float array1[ ], float array2 [ ])
static boolean equals(int array1[ ], int array2 [ ])
static boolean equals(long array1[ ], long array2 [ ])
static boolean equals(short array1[ ], short array2 [ ])
static boolean equals(Object array1[ ], Object array2 [ ])
6. deepEquals( )
The deepEquals( ) method can be used to determine if two arrays, which might contain nested arrays, are
equal. It has this declaration:
static boolean deepEquals(Object[ ] a, Object[ ] b)
7. fill( )
The fill( ) method assigns a value to all elements in an array. In other words, it fills an
array with a specified value. The fill( ) method has two versions. The first version, which has
the following forms, fills an entire array:
static void fill(boolean array[ ], boolean value)
static void fill(byte array[ ], byte value)
static void fill(char array[ ], char value)
static void fill(double array[ ], double value)
static void fill(float array[ ], float value)
static void fill(int array[ ], int value)
static void fill(long array[ ], long value)
static void fill(short array[ ], short value)
static void fill(Object array[ ], Object value)
8. sort( )
The sort( ) method sorts an array so that it is arranged in ascending order. The sort( )
method has two versions. The first version, shown here, sorts the entire array:
static void sort(byte array[ ])
static void sort(char array[ ])
static void sort(double array[ ])
static void sort(float array[ ])
static void sort(int array[ ])
static void sort(long array[ ])
static void sort(short array[ ])
static void sort(Object array[ ])
static <T> void sort(T array[ ], Comparator<? super T> c)
9. parallelSort( )
parallelSort( ) it sorts, into ascending order, portions of an array in parallel and then merges the results.
static void parallelSort(byte array[ ])
static void parallelSort(char array[ ])
static void parallelSort(double array[ ])
static void parallelSort(float array[ ])
static void parallelSort(int array[ ])
static void parallelSort(long array[ ])
static void parallelSort(short array[ ])
static <T extends Comparable<? super T>> void parallelSort(T array[ ])
static <T> void parallelSort(T array[ ], Comparator<? super T> c)

30
22PC1IT201 UNIT - V OOP Through Java

Java Database Connectivity


Introduction to JDBC
• Java Database Connectivity (JDBC) is a Java API that provides a standard way for Java applications to
connect to and interact with databases.
• JDBC is a platform-independent API, which means that it can be used to connect to databases on a
variety of platforms, including Windows, macOS, and Linux.

• JDBC provides a set of classes and interfaces that allow Java applications to perform common database
operations, such as:
✓ Connecting to a database
✓ Executing SQL statements
✓ Retrieving data from a database
✓ Inserting, updating, and deleting data in a database

• JDBC is a powerful API that can be used to develop a wide variety of database applications.
• For example, JDBC can be used to develop applications that:
✓ Access and manipulate data in a relational database
✓ Generate reports from data in a database
✓ Develop database-driven web applications
✓ Develop mobile applications that access data in a database

31
22PC1IT201 UNIT - V OOP Through Java

Types of Drivers: There are four types of JDBC drivers in Java:


Type 1: JDBC-ODBC bridge driver
• This is the oldest type of JDBC driver. It uses the ODBC bridge to connect to the database. This driver is
not very efficient, but it is easy to use because it is compatible with many different databases.

• Advantages:
✓ easy to use.
✓ It can be easily connected to any database.
• Disadvantages:
✓ Performance degraded because JDBC method call is converted into the ODBC function calls.
✓ The ODBC driver needs to be installed on the client machine.
Type 2: Native-API driver
• This type of JDBC driver uses the native API of the database to connect to the database.
• This driver is more efficient than the Type 1 driver, but it is only compatible with a few databases.

• Advantage:
✓ Performance upgraded than JDBC-ODBC bridge driver.
• Disadvantage:
✓ The native driver needs to be installed on each client machine.
✓ The vendor client library needs to be installed on client machine.
Type 3: Network Protocol driver
• This type of JDBC driver uses a network protocol to connect to the database.
• This driver is more efficient than the Type 1 driver, and it is compatible with many different databases.
• Advantage:
✓ No client-side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
32
22PC1IT201 UNIT - V OOP Through Java

• Disadvantages:
✓ 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: Pure Java driver or Thin driver


• This type of JDBC driver uses a pure Java implementation to connect to the database.
• This driver is the most efficient type of JDBC driver, and it is compatible with many different databases.

• Advantage:
✓ Better performance than all other drivers.
✓ No software is required at client side or server side.
• Disadvantage:
✓ Drivers depend on the Database.

• The best type of JDBC driver to use depends on the specific needs of the application.
• If the application needs to be compatible with many different databases, then the Type 3 or Type 4 driver
would be a good choice.
• If the application needs to be as efficient as possible, then the Type 4 driver would be the best choice.

33
22PC1IT201 UNIT - V OOP Through Java

Basic steps in developing JDBC applications


• There are 6 steps to connect any java application with the database using JDBC.
• Here are the steps on how to use JDBC in Java:
• It throws SQLException.
1. Load the JDBC driver
• The forName( ) method of Class class is used to load/register the driver class.
• This method is used to dynamically load the driver class.
• Syntax: public static void forName(String className)throws ClassNotFoundException
• Example: Class.forName("jdbc:mysql.jdbc.Driver");

2. Create a connection to the database


• The getConnection() method of DriverManager class is used to establish connection with the
database.
• It throws SQLException.
• Syntax: public static Connection getConnection(String url)
public static Connection getConnection(String url,String name,String password)
• Example: DriverManager.getConnection("jdbc:mysql://localhost:3306/sample", “root”, “1234”);

3. Create a statement object


• The createStatement() method of Connection interface is used to create statement.
• The object of statement is responsible to execute queries with the database.
• It throws SQLException.
• Syntax: public Statement createStatement( )
• Example: Statement stmt = con.createStatement( );

4. Execute a SQL statement


• There are three different methods to execute statements in JDBC in Java:
1. execute( )
• This method is the most generic method you can use to execute a SQL statement in JDBC.
• It can be used to execute any type of SQL statement, including DDL (Data Definition
Language), DML (Data Manipulation Language), and DCL (Data Control Language) statements.
• The execute( ) method returns a boolean value indicating whether the statement was executed
successfully.
• Syntax: public boolean execute(String sql)
2. executeUpdate( )
• This method is used to execute DML statements, such as INSERT, UPDATE, and DELETE
statements.
• The executeUpdate( ) method returns the number of rows that were affected by the statement.
• Syntax: public int executeUpdate(String sql);
3. executeQuery( )
• This method is used to execute SELECT statements.
• The executeQuery( ) method returns a ResultSet object, which contains the results of the query.
• Syntax: public ResultSet executeQuery(String sql)

5. Close the statement/connection to the database.


• By using close( ) method, terminate the connection between statement/API and database.
• This method throws SQLException.
• Syntax: public void close( )
34
22PC1IT201 UNIT - V OOP Through Java

JDBC classes and Interfaces


• Some of major classes and interfaces which are frequently used while developing a Java application are
as follows:
1. DriverManager class
• DriverManager class acts as an interface between users and drivers.
• It keeps track of the drivers that are available and handles establishing a connection between a
database and the appropriate driver.
• It contains all the appropriate methods to register and deregister the database driver class and to create
a connection between a Java application and the database.
Method Description
It is used to register the given driver with
public static synchronized void
DriverManager. No action is performed by the method
registerDriver(Driver driver)
when the given driver is already registered.
It is used to deregister the given driver (drop the driver
public static synchronized void from the list) with DriverManager. If the given driver
deregisterDriver(Driver driver) has been removed from the list, then no action is
performed by the method.
It is used to establish the connection with the specified
public static Connection getConnection(String url. The SQLException is thrown when the
url) corresponding Driver class of the given database is not
registered with the DriverManager.
It is used to establish the connection with the specified
url, username, and password. The SQLException is
public static Connection getConnection(String
thrown when the corresponding Driver class of the
url,String userName,String password)
given database is not registered with the
DriverManager.
A connection object is returned by this method after
creating a connection to the database present at the
mentioned URL, which is the first parameter of this
method. The second parameter, which is "prop",
public static Connection getConnection(String fetches the authentication details of the database
URL, Properties prop) (username and password.). Similar to the other
variation of the getConnection() method, this method
also throws the SQLException, when the
corresponding Driver class of the given database is not
registered with the DriverManager.

2. Driver interface
This interface is the Base interface for every driver class i.e. If you want to create a JDBC Driver of your
own you need to implement this interface. If you load a Driver class, it will create an instance of itself
and register with the driver manager.
3. Connection interface
• A Connection is a session between a Java application and a database.
• It provides methods for establishing a connection with a database and performing various database
operations.
• The Connection interface is a factory of Statement, PreparedStatement, CallableStatement,
DatabaseMetaData etc.
• Connection interface is help for transaction management.

35
22PC1IT201 UNIT - V OOP Through Java

• Methods:
Method Description
creates a statement object that can be used to execute SQL
public Statement createStatement( )
queries.
public PreparedStatement PreparedStatement is used for executing a precompiled
prepareStatement(String sql) SQL statement.
public CallableStatement prepareCall(String The CallableStatement is an interface which is used to
sql) execute SQL stored procedures, cursors, and Functions.
public void setAutoCommit(boolean status) It is used to set the commit status. By default, it is true.
saves the changes made since the previous
public void commit( )
commit/rollback is permanent.
Drops all changes made since the previous
public void rollback( )
commit/rollback.
closes the connection and Releases a JDBC resources
public void close( )
immediately.

4. Statement interface
• The statement interface in Java is used to create basic SQL statements. It provides methods for
executing queries with the database.
• The different types of statements that are used in JDBC are: Create Statement, Prepared Statement,
Callable Statement.
• The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and
properties that enable you to send SQL or PL/SQL commands and receive data from your database
• Methods:
Method Desecription
It is used to execute SELECT query. It returns the object
public ResultSet executeQuery(String sql)
of ResultSet.
It is used to execute specified query, it may be create,
public int executeUpdate(String sql)
drop, insert, update, delete etc.
It is used to execute queries that may return multiple
public boolean execute(String sql)
results.
public int[ ] executeBatch( ) It is used to execute batch of commands.

5. ResultSet interface
• The JDBC ResultSet interface is a core component of the JDBC Framework that represents the result
set of a database query.
• It is a table of data that is usually generated by executing a statement that queries the database.
• The term "result set" refers to the row and column data contained in a ResultSet object.
Method Description
It is used to move the cursor to the one row next from the
public boolean next( )
current position.
It is used to move the cursor to the one row previous from
public boolean previous( )
the current position.
It is used to move the cursor to the first row in result set
public boolean first( )
object.
It is used to move the cursor to the last row in result set
public boolean last( )
object.
It is used to move the cursor to the specified row number in
public boolean absolute(int row)
the ResultSet object.
It is used to move the cursor to the relative row number in
public boolean relative(int row)
the ResultSet object, it may be positive or negative.
36
22PC1IT201 UNIT - V OOP Through Java

It is used to return the data of specified column index of the


public int getInt(int columnIndex)
current row as int.
It is used to return the data of specified column name of the
public int getInt(String columnName)
current row as int.
is used to return the data of specified column index of the
public String getString(int columnIndex)
current row as String.
public String getString(String It is used to return the data of specified column name of the
columnName) current row as String.

6. ResultSetMetaData interface
• It provides information about a ResultSet object, such as the number of columns, column names,
column data types, and table name.
Method Description
It returns the total number of columns in the ResultSet
public int getColumnCount()
object.
It returns the column name of the specified column
public String getColumnName(int index)
index.
public String getColumnTypeName(int index) It returns the column type name for the specified index.
public String getTableName(int index) It returns the table name for the specified column index.

7. DatabaseMetaData interfaces
• DatabaseMetaData is an interface that provides information about a database's underlying data
sources.
Method Desecription
public String getDriverName( ) It returns the name of the JDBC driver.
public String getDriverVersion( ) It returns the version number of the JDBC driver.
public String getUserName( ) It returns the username of the database.
public String getDatabaseProductName( ) It returns the product name of the database.
public String getDatabaseProductVersion( ) It returns the product version of the database.
public ResultSet getTables(String catalog, It returns the description of the tables of the specified
String schemaPattern, String tableNamePattern, catalog. The table type can be TABLE, VIEW,
String[] types) ALIAS, SYSTEM TABLE, SYNONYM etc.

37
22PC1IT201 UNIT - V OOP Through Java

CRUD operations with JDBC


CREATE operation with JDBC
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
try {
String url = "jdbc:mysql://localhost:3306/demo";
String uname = "root";
String pass = "12345";
Connection con = DriverManager.getConnection(url,uname,pass);
Statement s = con.createStatement();
s.execute("create table course(id int, name varchar(30));");
con.close();
}catch (Exception ex){
System.out.println(ex);
}
}
}
INSERT operation with JDBC
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
try {
String url = "jdbc:mysql://localhost:3306/demo";
String uname = "root";
String pass = "12345";
Connection con = DriverManager.getConnection(url,uname,pass);
Statement s = con.createStatement();
s.executeUpdate("insert into course values(1,'C Program');");
s.executeUpdate("insert into course values(2,'Java');");
con.close();
}catch (Exception ex){
System.out.println(ex);
}
}
}
READ operation with JDBC
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
try {
String url = "jdbc:mysql://localhost:3306/demo";
String uname = "root";
String pass = "12345";
Connection con = DriverManager.getConnection(url,uname,pass);
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("select * from course;");
System.out.println("ID --- Name");
while (rs.next()){
System.out.println(rs.getInt(1)+" --- "+rs.getString(2));
}
con.close();
}catch (Exception ex){

38
22PC1IT201 UNIT - V OOP Through Java

System.out.println(ex);
}
}
}
Output:
ID --- Name
1 --- C Program
2 --- Java
UPDATE operation with JDBC
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
try {
String url = "jdbc:mysql://localhost:3306/demo";
String uname = "root";
String pass = "12345";
Connection con = DriverManager.getConnection(url,uname,pass);
Statement s = con.createStatement();
int res = s.executeUpdate("update course set name='J2EE'
where id=2;");
System.out.println(res + " Rows updated. ");
con.close();
}catch (Exception ex){
System.out.println(ex);
}
}
}
Output:
1 Rows updated.

UPDATE operation with JDBC


import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
try {
String url = "jdbc:mysql://localhost:3306/demo";
String uname = "root";
String pass = "12345";
Connection con = DriverManager.getConnection(url,uname,pass);
Statement s = con.createStatement();
int res = s.executeUpdate("delete from course where id=1;");
System.out.println(res + " Rows updated. ");
con.close();
}catch (Exception ex){
System.out.println(ex);
}
}
}
Output:
1 Rows updated.
39
22PC1IT201 UNIT - V OOP Through Java

Transaction Management
• Transaction is a sequence of operations that are performed on a database as a single unit of work.
• Connection interface provides methods to manage transaction.
• The ACID properties describes the transaction management well.
• ACID stands for Atomicity, Consistency, isolation and durability.
➢ Atomicity means either all successful or none.
➢ Consistency ensures bringing the database from one consistent state to another consistent state.
➢ Isolation ensures that transaction is isolated from other transaction.
➢ Durability means once a transaction has been committed, it will remain so, even in the event of errors,
power loss etc.

Method Description
void setAutoCommit(boolean status) It is true by default means each transaction is committed by default.
void commit() commits the transaction.
void rollback() It is used to undo the changes till the last commit has happened.

Example: demonstrate the commit and rollback


import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) throws SQLException {
Connection con=null;
try {
String url = "jdbc:mysql://localhost:3306/demo";
String uname = "root";
String pass = "12345";
con = DriverManager.getConnection(url,uname,pass);
con.setAutoCommit(false);
Statement s = con.createStatement();
s.executeUpdate("insert into course values(4,'C Program');");
s.executeUpdate("insert into course values('Java',5);");
con.commit();
System.out.println("Transaction committed ");
con.close();
}catch (Exception ex){
System.out.println(ex);
con.rollback();
System.out.println("Transaction roll backed");
}
}
}

40
22PC1IT201 UNIT - V OOP Through Java

Stored Procedures
• A stored procedure in MySQL is a collection of pre-compiled SQL statements that are saved in a
database.
• They are subroutines that contain a name, a parameter list, and SQL statements.
• Stored procedures can be used to implement reusable business logic across multiple applications.
• This streamlines the process and reduces the need to duplicate the same logic in multiple applications.
• CallableStatement interface is used to call the stored procedures and functions.
• To call a stored procedure in MySQL using JDBC, you can do the following:
1. Open a connection to the MySQL server by creating a new Connection object
2. Prepare a stored procedure call and create a CallableStatement object by calling prepareCall() method
of the Connection object
3. Pass all the parameters to the stored procedure
4. Use the CALL statement to call a stored procedure
5. Execute the store procedure

//creating procedure
DELIMITER &&
CREATE PROCEDURE getAllCourses ( )
BEGIN
SELECT * FROM demo.course;
END &&
DELIMITER ;

//calling procedure using JDBC


import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) throws SQLException {
try {
String url = "jdbc:mysql://localhost:3306/demo";
String uname = "root";
String pass = "12345";
Connection con = DriverManager.getConnection(url,uname,pass);
CallableStatement cs = con.prepareCall("call getAllCourses();");
ResultSet res = cs.executeQuery();
System.out.println("ID --- Name");
while (res.next()){
System.out.println(res.getInt(1)+" --- "+res.getString(2));
}
con.close();
}catch (Exception ex){
System.out.println(ex);
}
}
}

41
22PC1IT201 UNIT - V OOP Through Java

Model Questions
2 marks
1. Define collection and write is advantages.
2. List different collection classes.
3. Differentiate ArrayList and LinkedList.
4. Differentiate List and Set.
5. Differentiate Set and Map.
6. What is the use of StringTokenizer? Write its syntax.
7. What is the use of Arrays class? List some methods.
8. Differentiate Comparable and Comparator intrefaces.
9. Define JDBC and its usages.
10. List the steps to connect with database.
11. What are the different drives available in JDBC?
12. List the classes and interfaces in JDBC.
13. What is Transaction management and how it achieved.
14. Define stored procedure and write its use.
Essay question
1. Explain about Collection hierarchy with neat diagram.
2. Explain ArrayList class with example program.
3. Explain HashSet class with example program.
4. Explain HashMap class with example program.
5. Explain different ways of retrieving elements from collection with example program.
6. write a Java program to create a class called Student with the fields rollno, name, and age. Sort the
student data using rollno and display it after storing it using ArrayList.
7. List and explain basic step to connect with database using JDBC.
8. List and explain different classes and interfaces in JDBC
9. Explain different Drivers available in JDBC.
10. Define Transaction. Describe properties of transaction and write sample program to achieve
transaction.
11. Write a JDBC program to demonstrate CRUD operations.

42

You might also like