JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
II [Link] II- Semester
CS405PC
Java Programming (R18) 2021-22
UNIT-IV PART-I & II
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 1
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
UNIT-IV
The Collections Framework ([Link])- Collections overview, Collection Interfaces, The
Collection classes- Array List, Linked List, Hash Set, Tree Set, Priority Queue, Array
Deque. Accessing a Collection via an Iterator, Using an Iterator, The For-Each alternative,
Map Interfaces and Classes, Comparators, Collection algorithms, Arrays, The Legacy
Classes and Interfaces- Dictionary, Hashtable, Properties, Stack, Vector More Utility
classes, String Tokenizer, Bit Set, Date, Calendar, Random, Formatter, Scanner
Java Collection Framework
The Collection in Java is a framework that provides architecture to store and manipulate the
group of objects.
The java collection framework holds several classes that provide a large number of methods
to store and process a group of objects. These classes make the programmer task super easy
and fast.
Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
Java collection framework was introduced in java 1.2 version.
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).
The Java collections framework provides a set of interfaces and classes to implement
various data structures and algorithms.
For example, the LinkedList class of the collections framework provides the
implementation of the doubly-linked list data structure.
What is Collection in Java
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.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 2
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Why use Java collection?
There are several benefits of using Java collections such as:
✔ Reducing the effort required to write the code by providing useful data structures
and algorithms
✔ Java collections provide high-performance and high-quality data structures and
algorithms thereby increasing the speed and quality
✔ Unrelated APIs can pass collection interfaces back and forth
✔ Decreases extra effort required to learn, use, and design new API’s
✔ Supports reusability of standard data structures and algorithms
Java collection framework has the following hierarchy.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 3
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Before the collection framework in java (before java 1.2 version), there was a set of classes
like Array, Vector, Stack, HashTable. These classes are known as legacy classes.
The java collection framework contains List, Queue, Set, and Map as top-level interfaces.
The List, Queue, and Set stores single value as its element, whereas Map stores a pair of a
key and value as its element.
Java Collection Interface
The Collection interface is the root interface for most of the interfaces and classes of
collection framework. The Collection interface is available inside the [Link] package. It
defines the methods that are commonly used by almost all the collections.
The Collection interface defines the following methods.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 4
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
The Collection interface extends Iterable interface.
Iterator interface : Iterator is an interface that iterates the elements. It is used to traverse
the list and modify the elements. Iterator interface has three methods which are mentioned
below:
✔ public boolean hasNext() – This method returns true if the iterator has more
elements.
✔ public object next() – It returns the element and moves the cursor pointer to the
next element.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 5
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
✔ public void remove() – This method removes the last elements returned by the
iterator.
Note:
There are three components that extend the collection interface i.e List, Queue and Sets.
Example:
Example program on ArrayList to illustrate the methods of Collection interface.
import [Link].*;
public class CollectionInterfaceExample {
public static void main(String[] args) {
List list_1 = new ArrayList();
List<String> list_2 = new ArrayList<String>();
list_1.add(27);
list_1.add(23);
list_2.add("Jyothishmathi");
list_2.add("Karimnagar");
list_2.add("Telangana");
[Link]("Elements of list_1: " + list_1);
[Link]("Elements of list_2: " + list_2);
list_1.addAll(list_2);
[Link]("Elements of list_1: " + list_1);
[Link]("Search for BTech: " + list_1.contains("Karimnagar"));
[Link]("Search for list_2 in list_1: " + list_1.containsAll(list_2));
[Link]("Check whether list_1 and list_2 are equal: " +
list_1.equals(list_2));
[Link]("Check is list_1 empty: " + list_1.isEmpty());
[Link]("Size of list_1: " + list_1.size());
[Link]("Hashcode of list_1: " + list_1.hashCode());
list_1.remove(0);
[Link](list_1);
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 6
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
list_1.retainAll(list_2);
[Link](list_1);
list_1.removeAll(list_2);
[Link](list_1);
list_2.clear();
[Link](list_2);
}
}
Output:
Elements of list_1: [27, 23]
Elements of list_2: [Jyothishmathi, Karimnagar, Telangana]
Elements of list_1: [27, 23, Jyothishmathi, Karimnagar, Telangana]
Search for BTech: true
Search for list_2 in list_1: true
Check whether list_1 and list_2 are equal: false
Check is list_1 empty: false
Size of list_1: 5
Hashcode of list_1: 206150570
[23, Jyothishmathi, Karimnagar, Telangana]
[Jyothishmathi, Karimnagar, Telangana]
[]
[]
Java List Interface
The List interface is a child interface of the Collection interface. The List interface is
available inside the [Link] package. It defines the methods that are commonly used by
classes like ArrayList, LinkedList, Vector, and Stack.
✔ The List interface extends Collection interface.
✔ The List interface allows duplicate elements.
✔ The List interface preserves the order of insertion.
✔ The List allows accessing the elements based on the index value that starts with zero.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 7
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
The List interface defines the following methods.
Example:
import [Link];
import [Link];
public class ListInterfaceExample {
public static void main(String[] args) {
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 8
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
List list_1 = new ArrayList();
List<String> list_2 = new ArrayList<String>();
list_1.add(0, 10);
list_1.add(1, 27);
list_2.add(0, "Jyothishmathi");
list_2.add(1, "Karimnagar");
list_2.add(2, "Telangana");
[Link]("\nElements of list_1: " + list_1);
list_1.addAll(2, list_2);
[Link]("\nElements of list_1: " + list_1);
[Link]("\nElement at index 2: " + list_1.get(2));
[Link]("\nSublist : " + list_1.subList(2, 4));
list_1.set(2, 77);
[Link]("\nAfter updating the value at index 2: " + list_1);
list_1.set(4, 77);
[Link]("\nIndex of value 10: " + list_1.indexOf(10));
[Link]("\nAfter updating the value at index 2: " + list_1);
[Link]("\nLast index of value 10: " + list_1.lastIndexOf(77));
}
}
Output:
Elements of list_1: [10, 27]
Elements of list_1: [10, 27, Jyothishmathi, Karimnagar, Telangana]
Element at index 2: Jyothishmathi
Sublist : [Jyothishmathi, Karimnagar]
After updating the value at index 2: [10, 27, 77, Karimnagar, Telangana]
Index of value 10: 0
After updating the value at index 2: [10, 27, 77, Karimnagar, 77]
Last index of value 10: 4
Java Queue Interface
The Queue interface is a child interface of the Collection interface. The Queue interface is
available inside the [Link] package. It defines the methods that are commonly used by
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 9
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
classes like PriorityQueue and ArrayDeque.
The Queue is used to organize a sequence of elements prior to the actual operation.
✔ The Queue interface extends Collection interface.
✔ The Queue interface allows duplicate elements.
✔ The Queue interface preserves the order of insertion.
The Queue interface defines the following methods.
Example:
Example program on PriorityQueue to illustrate the methods of Queue interface.
import [Link].*;
public class QueueInterfaceExample {
public static void main(String[] args) {
Queue queue = new PriorityQueue();
[Link](66);
[Link](22);
[Link](77);
[Link](44);
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 10
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link](55);
[Link]("\nQueue elements are - " + queue);
[Link]("\nHead element - " + [Link]());
[Link]("\nHead element again - " + [Link]());
[Link]();
[Link]("\nElements after Head removal - " + queue);
[Link]();
[Link]("\nElements after one more Head removal - " + queue);
}
}
Output:
Queue elements are - [22, 44, 77, 66, 55]
Head element - 22
Head element again - 22
Elements after Head removal - [44, 55, 77, 66]
Elements after one more Head removal - [55, 66, 77]
Java Deque Interface
The Deque interface is a child interface of the Queue interface. The Deque interface is
available inside the [Link] package. It defines the methods that are used by class
ArrayDeque.
✔ The Deque interface extends Queue interface.
✔ The Deque interface allows duplicate elements.
✔ The Deque interface preserves the order of insertion.
The Deque interface defines the following methods.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 11
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Example:
Example program on ArrayDeque to illustrate the methods of Deque interface.
import [Link].*;
public class DequeInterfaceExample {
public static void main(String[] args) {
Deque deque = new ArrayDeque();
[Link](10);
[Link](20);
[Link](5);
[Link](25);
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 12
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link](2);
[Link]("\nElements of deque - " + deque);
[Link]("\nFirst element - " + [Link]());
[Link]("\nLast element - " + [Link]());
[Link]("\nFirst element - " + [Link]());
[Link]("\nLast element - " + [Link]());
[Link]("\nRemove first element - " + [Link]());
[Link]("\nRemove one more first element - " +
[Link]());
[Link]("\nRemove last element - " + [Link]());
[Link]("\nRemove one more first element - " +
[Link]());
[Link]("\nRemove one more last element - " +
[Link]());
}
}
Output:
Elements of deque - [2, 5, 10, 20, 25]
First element - 2
Last element - 25
First element - 2
Last element - 25
Remove first element - 2
Remove one more first element - 5
Remove last element - 25
Remove one more first element - 10
Remove one more last element – 20
Java SortedSet Interface
Set Interface
The Set interface is a child interface of Collection interface. It does not defines any
additional methods of it, it has all the methods that are inherited from Collection interface.
The Set interface does not allow duplicates. Set is a generic interface.
SortedSet Interface
The SortedSet interface is a child interface of the Set interface. The SortedSet interface is
available inside the [Link] package. It defines the methods that are used by classes
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 13
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
HashSet, LinkedHashSet, and TreeSet.
● The SortedSet interface extends Set interface.
● The SortedSet interface does not allow duplicate elements.
● The SortedSet interface organize the elements based on the ascending order.
Example program on TreeSet to illustrate the methods of SortedSet interface.
import [Link].*;
public class SortedSetInterfaceExample {
public static void main(String[] args) {
SortedSet sortedSet = new TreeSet();
[Link](23);
[Link](7);
[Link](5);
[Link](110);
[Link](21);
[Link]("\nElements of sortedSet: " + sortedSet);
[Link]("\nFirst element: " + [Link]());
[Link]("\nLast element: " + [Link]());
[Link]("\nSubset with upper limit: " + [Link](110));
[Link]("\nSubset with lower limit: " + [Link](21));
[Link]("\nSubset with upper and lower limit: " +
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 14
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link](1, 22));
}
}
Output:
Elements of sortedSet: [5, 7, 21, 23, 110]
First element: 5
Last element: 110
Subset with upper limit: [5, 7, 21, 23]
Subset with lower limit: [21, 23, 110]
Subset with upper and lower limit: [5, 7, 21]
Java NavigableSet Interface
The NavigableSet interface is a child interface of the SortedSet interface. The NavigableSet
interface is available inside the [Link] package. It defines the methods that are used by
class TreeSet.
● The NavigableSet interface extends SortedSet interface.
● The SortedSet interface does not allow duplicate elements.
● The SortedSet interface organise the elements based on the ascending order.
The NavigableSet interface defines several utility methods that are used in the TreeSet class
and they are as follows.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 15
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Example:
import [Link].*;
public class NavigableSetInterfaceExample {
public static void main(String[] args) {
NavigableSet navSet = new TreeSet();
[Link](10);
[Link](20);
[Link](5);
[Link](40);
[Link](30);
[Link]("\nElements of sortedSet: " + navSet);
[Link]("\nSmallest element from subSet of larger than 25: " +
[Link](25));
[Link]("\nLargest element from subSet of smaller than 25: " +
[Link](25));
[Link]("\nSmallest element from subSet of larger than 25: " +
[Link](25));
[Link]("\nLargest element from subSet of smaller than 25: " +
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 16
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link](25));
[Link]("\nSubset with upperBound, including it: " +
[Link](30, true));
[Link]("\nSubset with upperBound, excluding it: " +
[Link](30, false));
[Link]("\nSubset with lowwerBound, including it: " +
[Link](30, true));
[Link]("\nSubset with lowerBound, excluding it: " +
[Link](30, false));
[Link]("\nRemove the first element: " + [Link]());
[Link]("\nRemove the last element: " + [Link]());
}
}
Output:
Elements of sortedSet: [5, 10, 20, 30, 40]
Smallest element from subSet of larger than 25: 30
Largest element from subSet of smaller than 25: 20
Smallest element from subSet of larger than 25: 30
Largest element from subSet of smaller than 25: 20
Subset with upperBound, including it: [5, 10, 20, 30]
Subset with upperBound, excluding it: [5, 10, 20]
Subset with lowwerBound, including it: [30, 40]
Subset with lowerBound, excluding it: [40]
Remove the first element: 5
Remove the last element: 40
Java ArrayList Class
The ArrayList class is a part of java collection framework. It is available inside the
[Link] package. The ArrayList class extends AbstractList class and implements List
interface.
The elements of ArrayList are organized as an array internally. The default size of an
ArrayList is 10.
The ArrayList class is used to create a dynamic array that can grow or shrunk as needed.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 17
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
● The ArrayList is a child class of AbstractList
● The ArrayList implements interfaces like List, Serializable, Cloneable, and
RandomAccess.
● The ArrayList allows storing duplicate data values.
● The ArrayList allows to access elements randomly using index-based accessing.
● The ArrayList maintains the order of insertion.
ArrayList class declaration
The ArrayList class has the following declaration.
Example
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess,
Cloneable, Serializable
ArrayList class constructors
The ArrayList class has the following constructors.
ArrayList( ) - Creates an empty ArrayList.
ArrayList(Collection c) - Creates an ArrayList with given collection of elements.
ArrayList(int size) - Creates an empty ArrayList with given size (capacity).
Operations on ArrayList
The ArrayList class allows us to perform several operations like adding, accessing, deleting,
updating, looping, etc. Let's look at each operation with examples.
Adding Items
The ArrayList class has the following methods to add items.
boolean add(E element) - Appends given element to the ArrayList.
boolean addAll(Collection c) - Appends given collection of elements to the ArrayList.
void add(int index, E element) - Inserts the given element at specified index.
boolean addAll(int index, Collection c) - Inserts the given collection of elements at
specified index.
Example program to illustrate adding items to the ArrayList.
import [Link].*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list_1 = new ArrayList<String>();
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 18
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
ArrayList list_2 = new ArrayList();
//Appending
list_1.add("Jyothishmathi ");
[Link]("list_1: " + list_1);
list_1.add("Institute");
[Link]("list_1: " + list_1);
//Inserting at specified index
list_1.add(1, "Karimnagar");
[Link]("list_1: " + list_1);
//Appending a collection of elements
list_2.addAll(list_1);
[Link]("list_2: " + list_2);
//Inserting collection of elements at specified index
list_2.addAll(2, list_1);
[Link]("list_2: " + list_2);
}
}
Output:
list_1: [Jyothishmathi ]
list_1: [Jyothishmathi , Institute]
list_1: [Jyothishmathi , Karimnagar, Institute]
list_2: [Jyothishmathi , Karimnagar, Institute]
list_2: [Jyothishmathi , Karimnagar, Jyothishmathi , Karimnagar, Institute, Institute]
Accessing Items
The ArrayList class has the following methods to access items.
E get(int index) - Returns element at specified index from the ArrayList.
ArrayList subList(int startIndex, int lastIndex) - Returns an ArrayList that contails
elements from specified startIndex to lastIndex-1 from the invoking ArrayList.
int indexOf(E element) - Returns the index value of given element first occurence in the
ArrayList.
int lastIndexOf(E element) - Returns the index value of given element last occurence in the
ArrayList.
Example program to illustrate accessing items from the ArrayList.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 19
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
import [Link].*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list_1 = new ArrayList<String>();
list_1.add("Jyothishmathi");
list_1.add("Institute");
list_1.add("of");
list_1.add("Technology");
list_1.add("and");
list_1.add("Science");
list_1.add("Karimnagar");
[Link]("Element at index 4 is " + list_1.get(4));
[Link]("Sublist from index 1 to 4: " + list_1.subList(1, 5));
[Link]("Index of element \"Technology\" is " +
list_1.indexOf("Technology"));
[Link]("Last index of element \"Jyothishmathi\" is " +
list_1.lastIndexOf("Jyothishmathi"));
}
}
Output:
Element at index 4 is and
Sublist from index 1 to 4: [Institute, of, Technology, and]
Index of element "Technology" is 3
Last index of element "Jyothishmathi" is 0
Java LinkedList Class
The LinkedList class is a part of java collection framework. It is available inside the
[Link] package. The LinkedList class extends AbstractSequentialList class and
implements List and Deque interface.
The elements of LinkedList are organized as the elements of linked list data structure.
The LinkedList class is used to create a dynamic list of elements that can grow or shrunk as
needed.
● The LinkedList is a child class of AbstractSequentialList
● The LinkedList implements interfaces like List, Deque, Cloneable, and Serializable.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 20
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
● The LinkedList allows to store duplicate data values.
● The LinkedList maintains the order of insertion.
LinkedList class declaration
The LinkedList class has the following declaration.
Example:
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>,
Deque<E>, Cloneable, Serializable
LinkedList class constructors
The LinkedList class has the following constructors.
✔ LinkedList( ) - Creates an empty List.
✔ LinkedList(Collection c) - Creates a List with given collection of elements.
Operations on LinkedList
The LinkedList class allow us to perform several operations like adding, accesing, deleting,
updating, looping, etc. Let's look at each operation with examples.
Adding Items
The LinkedList class has the following methods to add items.
● boolean add(E element) - Appends given element to the List.
● boolean addAll(Collection c) - Appends given collection of elements to the List.
● void add(int position, E element) - Inserts the given element at specified position.
● boolean addAll(int position, Collection c) - Inserts the given collection of elements at
specified position.
● void addFirst(E element) - Inserts the given element at beginning of the list.
● void addLast(E element) - Inserts the given element at end of the list.
● boolean offer(E element) - Inserts the given element at end of the list.
● boolean offerFirst(E element) - Inserts the given element at beginning of the list.
● boolean offerLast(E element) - Inserts the given element at end of the list.
● void push(E element) - Inserts the given element at beginning of the list.
Example:
import [Link].*;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> list_1 = new LinkedList<String>();
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 21
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
LinkedList list_2 = new LinkedList();
list_2.add(10);
list_2.add(20);
list_2.addFirst(5);
list_2.addLast(25);
list_2.offer(2);
list_2.offerFirst(1);
list_2.offerLast(10);
list_2.push(40);
list_1.addAll(list_2);
[Link]("List_1: " + list_1);
[Link]("List_2: " + list_2);
}
}
Java PriorityQueue Class
The PriorityQueue class is a part of java collection framework. It is available inside the
[Link] package. The PriorityQueue class extends AbstractQueue class and implements
Serializable interface.
The elements of PriorityQueue are organized as the elements of queue data structure, but it
does not follow FIFO principle. The PriorityQueue elements are organized based on the
priority heap.
✔ The PriorityQueue is a child class of AbstractQueue
✔ The PriorityQueue implements interface Serializable.
✔ The PriorityQueue allows to store duplicate data values, but not null values.
✔ The PriorityQueue maintains the order of insertion.
✔ The PriorityQueue used priority heap to organize its elements.
PriorityQueue class declaration
The PriorityQueue class has the following declaration.
Example:
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 22
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
PriorityQueue class constructors
The PriorityQueue class has the following constructors.
● PriorityQueue( ) - Creates an empty PriorityQueue with the default initial capacity (11) that
orders its elements according to their natural ordering.
● PriorityQueue(Collection c) - Creates a PriorityQueue with given collection of elements.
● PriorityQueue(int initialCapacity) - Creates an empty PriorityQueue with the specified
initial capacity.
● PriorityQueue(int initialCapacity, Comparator comparator) - Creates an empty
PriorityQueue with the specified initial capacity that orders its elements according to the
specified comparator.
● PriorityQueue(PriorityQueue pq) - Creates a PriorityQueue with the elements in the
specified priority queue.
● PriorityQueue(SortedSet ss) - Creates a PriorityQueue with the elements in the specified
SortedSet.
Operations on PriorityQueue
The PriorityQueue class allow us to perform several operations like adding, accesing,
deleting, updating, looping, etc. Let's look at each operation with examples.
Adding Items
The PriorityQueue class has the following methods to add items.
boolean add(E element) - Appends given element to the PriorityQueue.
boolean addAll(Collection c) - Appends given collection of elements to the PriorityQueue.
boolean offer(E element) - Appends given element to the PriorityQueue.
Example program to illustrate adding items to the PriorityQueue.
import [Link].*;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue queue = new PriorityQueue();
PriorityQueue anotherQueue = new PriorityQueue();
[Link](10);
[Link](20);
[Link](15);
[Link]("\nQueue is " + queue);
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 23
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link](queue);
[Link]("\nanotherQueue is " + anotherQueue);
[Link](25);
[Link]("\nanotherQueue is " + anotherQueue);
}
}
Accessing Items
The PriorityQueue class has the following methods to access items.
E element( ) - Returns the first element from the invoking PriorityQueue.
E peek( ) - Returns the first element from the invoking PriorityQueue, returns null if this
queue is empty.
import [Link].*;
public class PriorityQueueExample {
public static void main(String[] args) {
PriorityQueue queue = new PriorityQueue();
[Link](10);
[Link](20);
[Link](15);
[Link]("\nQueue is " + queue);
[Link]("\nelement() - " + [Link]());
[Link]("\npeek() - " + [Link]());
}
}
Java ArrayDeque Class
The ArrayDeque class is a part of java collection framework. It is available inside the
[Link] package. The ArrayDeque class extends AbstractCollection class and implements
Deque, Cloneable, and Serializable interfaces.
The elements of ArrayDeque are organized as the elements of double ended queue data
structure. The ArrayDeque is a special kind of array that grows and allows users to add or
remove an element from both the sides of the queue.
The ArrayDeque class is used to create a dynamic double ended queue of elements that can
grow or shrunk as needed.
✔ The ArrayDeque is a child class of AbstractCollection
✔ The ArrayDeque implements interfaces like Deque, Cloneable, and Serializable.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 24
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
✔ The ArrayDeque allows to store duplicate data values, but not null values.
✔ The ArrayDeque maintains the order of insertion.
✔ The ArrayDeque allows to add and remove elements at both the ends.
✔ The ArrayDeque is faster than LinkedList and Stack.
ArrayDeque class declaration
The ArrayDeque class has the following declaration.
Example
public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>,
Cloneable, Serializable
ArrayDeque class constructors
The PriorityQueue class has the following constructors.
ArrayDeque( ) - Creates an empty ArrayDeque with the default initial capacity (16).
ArrayDeque(Collection c) - Creates a ArrayDeque with given collection of elements.
ArrayDeque(int initialCapacity) - Creates an empty ArrayDeque with the specified initial
capacity.
Operations on ArrayDeque
The ArrayDeque class allow us to perform several operations like adding, accesing,
deleting, updating, looping, etc. Let's look at each operation with examples.
Adding Items
The ArrayDeque class has the following methods to add items.
boolean add(E element) - Appends given element to the ArrayDeque.
boolean addAll(Collection c) - Appends given collection of elements to the ArrayDeque.
void addFirst(E element) - Adds given element at front of the ArrayDeque.
void addLast(E element) - Adds given element at end of the ArrayDeque.
boolean offer(E element) - Adds given element at end of the ArrayDeque.
boolean offerFirst(E element) - Adds given element at front of the ArrayDeque.
boolean offerLast(E element) - Adds given element at end of the ArrayDeque.
void push(E element) - Adds given element at front of the ArrayDeque.
An example program to illustrate adding items to the ArrayDeque.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 25
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
import [Link].*;
public class ArrayDequeExample {
public static void main(String[] args) {
ArrayDeque deque = new ArrayDeque();
ArrayDeque anotherDeque = new ArrayDeque();
[Link](10);
[Link](5);
[Link](15);
[Link](20);
[Link](10);
[Link](30);
[Link]("\nDeque is\n" + deque);
[Link](deque);
[Link]("\nanotherDeque is\n" + anotherDeque);
[Link](40);
[Link]("\nanotherDeque after push(40) is\n" + anotherDeque);
}
}
Accessing Items
The ArrayDeque class has the following methods to access items.
E element( ) - Returns the first element from the invoking ArrayDeque.
E getFirst( ) - Returns the first element from the invoking ArrayDeque.
E getLast( ) - Returns the last element from the invoking ArrayDeque.
E peek( ) - Returns the first element from the invoking ArrayDeque, returns null if this
queue is empty.
E peekFirst( ) - Returns the first element from the invoking ArrayDeque, returns null if this
queue is empty.
E peekLast( ) - Returns the last element from the invoking ArrayDeque, returns null if this
queue is empty.
Example program to illustrate accessing items from the ArrayDeque.
import [Link].*;
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 26
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
public class ArrayDequeExample {
public static void main(String[] args) {
ArrayDeque deque = new ArrayDeque();
for(int i = 1; i <= 10; i++)
[Link](i);
[Link]("\nDeque is\n" + deque);
[Link]("\nelement() - " + [Link]());
[Link]("\ngetFirst() - " + [Link]());
[Link]("\ngetLast() - " + [Link]());
[Link]("\npeek() - " + [Link]());
[Link]("\npeekFirst() - " + [Link]());
[Link]("\npeekLast() - " + [Link]());
}
}
Java HashSet Class
The HashSet class is a part of java collection framework. It is available inside the [Link]
package. The HashSet class extends AbstractSet class and implements Set interface.
The elements of HashSet are organized using a mechanism called hashing. The HashSet is
used to create hash table for storing set of elements.
The HashSet class is used to create a collection that uses a hash table for storing set of
elements.
● The HashSet is a child class of AbstractSet
● The HashSet implements interfaces like Set, Cloneable, and Serializable.
● The HashSet does not allows to store duplicate data values, but null values are
allowed.
● The HashSet does not maintains the order of insertion.
● The HashSet initial capacity is 16 elements.
● The HashSet is best suitable for search operations.
HashSet class declaration
The HashSet class has the following declaration.
Example
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 27
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable,
Serializable
HashSet class constructors
The HashSet class has the following constructors.
HashSet( ) - Creates an empty HashSet with the default initial capacity (16).
HashSet(Collection c) - Creates a HashSet with given collection of elements.
HashSet(int initialCapacity) - Creates an empty HashSet with the specified initial capacity.
HashSet(int initialCapacity, float loadFactor) - Creates an empty HashSet with the
specified initial capacity and loadFactor.
Operations on HashSet
The HashSet class allow us to perform several operations like adding, accesing, deleting,
updating, looping, etc. Let's look at each operation with examples.
Adding Items
The HashSet class has the following methods to add items.
boolean add(E element) - Inserts given element to the HashSet.
boolean addAll(Collection c) - Inserts given collection of elements to the HashSet.
Example program to illustrate adding items to the HashSet.
import [Link].*;
public class HashSetExample {
public static void main(String[] args) {
HashSet set = new HashSet();
HashSet anotherSet = new HashSet();
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);
[Link]("\nHashSet is\n" + set);
[Link](set);
[Link]("\nanotherSet is\n" + anotherSet);
}
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 28
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
}
Java TreeSet Class
The TreeSet class is a part of java collection framework. It is available inside the [Link]
package. The TreeSet class extends AbstractSet class and implements NavigableSet,
Cloneable, and Serializable interfaces.
The elements of TreeSet are organized using a mechanism called tree. The TreeSet class
internally uses a TreeMap to store elements. The elements in a TreeSet are sorted according
to their natural ordering.
✔ The TreeSet is a child class of AbstractSet
✔ The TreeSet implements interfaces like NavigableSet, Cloneable, and Serializable.
✔ The TreeSet does not allows to store duplicate data values, but null values are
allowed.
✔ The elements in a TreeSet are sorted according to their natural ordering.
✔ The TreeSet initial capacity is 16 elements.
✔ The TreeSet is best suitable for search operations.
TreeSet class declaration
The TreeSet class has the following declaration.
Example sorting order
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable,
Serializable
TreeSet class constructors
The TreeSet class has the following constructors.
TreeSet( ) - Creates an empty TreeSet in which elements will get stored in default natural
sorting order.
TreeSet(Collection c) - Creates a TreeSet with given collection of elements.
TreeSet(Comparator c) - Creates an empty TreeSet with the specified sorting order.
TreeSet(SortedSet s) - This constructor is used to convert SortedSet to TreeSet.
Operations on TreeSet
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 29
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
The TreeSet class allow us to perform several operations like adding, accessing, deleting,
updating, looping, etc. Let's look at each operation with examples.
The TreeSet class has the following methods to add items.
boolean add(E element) - Inserts given element to the TreeSet if it does not exist.
boolean addAll(Collection c) - Inserts given collection of elements to the TreeSet.
Example program to illustrate adding items to the TreeSet.
import [Link].*;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet set = new TreeSet();
TreeSet anotherSet = new TreeSet();
[Link](10);
[Link](20);
[Link](15);
[Link](5);
[Link]("\nset is\n" + set);
[Link](set);
[Link]("\nanotherSet is\n" + anotherSet);
}
}
Accessing a Java Collection via a Iterator
The java collection framework often we want to cycle through the elements. For example,
we might want to display each element of a collection. The java provides an interface
Iterator that is available inside the [Link] package to cycle through each element of a
collection.
✔ The Iterator allows us to move only forward direction.
✔ The Iterator does not support the replacement and addition of new elements.
We use the following steps to access a collection of elements using the Iterator.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 30
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Step - 1: Create an object of the Iterator by calling [Link]( ) method.
Step - 2: Use the method hasNext( ) to access to check does the collection has the next
element. (Use a loop).
Step - 3: Use the method next( ) to access each element from the collection. (use inside the
loop).
Method Description
Iterator iterator( ) Used to obtain an iterator to the start of the collection.
boolean hasNext( Returns true if the collection has the next element, otherwise, it returns
) false.
E next( ) Returns the next element available in the collection.
Example program to illustrate accessing elements of a collection via the Iterator.
import [Link].*;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet set = new TreeSet();
Random num = new Random();
for(int i = 0; i < 10; i++)
[Link]([Link](100));
Iterator collection = [Link]();
[Link]("All the elements of TreeSet collection:");
while([Link]())
[Link]([Link]() + ", ");
}
}
Accessing a collection using for-each
We can use the for-each statement to access elements of a collection.
Example program to illustrate accessing items from a collection using a for-each
statement.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 31
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
import [Link].*;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet set = new TreeSet();
ArrayList list = new ArrayList();
PriorityQueue queue = new PriorityQueue();
Random num = new Random();
for(int i = 0; i < 10; i++) {
[Link]([Link](100));
[Link]([Link](100));
[Link]([Link](100));
}
[Link]("\nAll the elements of TreeSet collection:");
for(Object element:set) {
[Link](element + ", ");
}
[Link]("\n\nAll the elements of ArrayList collection:");
for(Object element:list) {
[Link](element + ", ");
}
[Link]("\n\nAll the elements of PriorityQueue collection:");
for(Object element:queue) {
[Link](element + ", ");
}
}
}
Map Interface in java
The java collection framework has an interface Map that is available inside the [Link]
package. The Map interface is not a subtype of Collection interface.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 32
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
✔ The Map stores the elements as a pair of key and value.
✔ The Map does not allows duplicate keys, but allows duplicate values.
✔ In a Map, each key can map to at most one value only.
✔ In a Map, the order of elements depends on specific implementations, e.g TreeMap
and LinkedHashMap have predictable order, while HashMap does not.
The Map interface has the following child interfaces.
Interface Description
Map Maps unique key to value.
[Link] Describe an element in key and value pair in a map. Entry is sub interface
of Map.
SortedMap It is a child of Map so that key are maintained in an ascending order.
NavigableMa It is a child of SortedMap to handle the retrienal of entries based on closest
p match searches.
The Map interface has the following three classes.
Class Description
HashMap It implements the Map interface, but it doesn't maintain any order.
LinkedHashMap It implements the Map interface, it also extends HashMap class. It
maintains the insertion order.
TreeMap It implements the Map and SortedMap interfaces. It maintains the
ascending order.
Map Interface methods
he Map interface contains methods for handling elements of a map. It has the following
methods.
The insertion of a key, value pair is said to be an entry in the map terminology.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 33
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Method Description
V put(Object key, Object Inserts an entry in the map.
value)
void putAll(Map map) Inserts the specified map into the invoking map.
V putIfAbsent(K key, V Inserts the specified value with the specified key in the map
value) only if that key does not exist.
Set keySet( ) Returns a Set that contains all the keys of invoking Map.
Collection values( ) Returns a collection that contains all the values of invoking
Map.
Set<[Link]<K,V>> Returns a Set that contains all the keys and values of
entrySet() invoking Map.
V get(Object key) Returns the value associated with the specified key.
V getOrDefault(Object key, Returns the value associated with the specified key, or
V defaultValue) defaultValue if the map does not contain the key.
boolean Returns true if specified value found in the map, else return
containsValue(Object value) false.
boolean containsKey(Object Returns true if specified key found in the map, else return
key) false.
V replace(K key, V value) Used to replace the specified value for the specified key.
boolean replace(K key, V Used to replaces the oldValue with the newValue for a
oldValue, V newValue) specified key.
void replaceAll(BiFunction Replaces each entry's value with the result of invoking the
function) given function on that entry until all entries have been
processed or the function throws an exception.
V merge(K key, V value, If the specified key is not already associated with a value or
BiFunction is associated with null, associates it with the given non-null
remappingFunction) value.
V compute(K key, Used to compute a mapping for the specified key and its
BiFunction current mapped value.
remappingFunction)
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 34
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Method Description
V computeIfAbsent(K key, Used to compute its value using the given mapping
Function mappingFunction) function, if the specified key is not already associated with a
value, and enters it into this map unless null.
V computeIfPresent(K key, Used to compute a new mapping given the key and its
BiFunction current mapped value if the value for the specified key is
remappingFunction) present and non-null.
void forEach(BiConsumer It performs the given action for each entry in the map until
action) all entries have been processed or the action throws an
exception.
V remove(Object key) Removes an entry for the specified key.
boolean remove(Object key, Removes the specified values with the associated specified
Object value) keys from the map.
void clear() Removes all the entries from the map.
boolean equals(Object o) It is used to compare the specified Object with the Map.
int hashCode() Returns the hash code for invoking the Map.
boolean isEmpty() Returns true if the map is empty; otherwise returns false.
int size() Returns total number of entries in the invoking Map.
Map Interface Classes in java
The java collection framework has an interface Map that is available inside the [Link]
package. The Map interface is not a subtype of Collection interface.
The Map interface has the following three classes.
Class Description
HashMap It implements the Map interface, but it doesn't maintain any order.
LinkedHashMap It implements the Map interface, it also extends HashMap class. It
maintains the insertion order.
TreeMap It implements the Map and SortedMap interfaces. It maintains the
ascending order.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 35
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Commonly used methods defined by Map interface
Method Description
Object put(Object k, Object v) It performs an entry into the Map.
Object putAll(Map m) It inserts all the entries of m into invoking Map.
Object get(Object k) It returns the value associated with given key.
boolean containsKey(Object k) It returns true if map contain k as key. Otherwise false.
Set keySet() It returns a set that contains all the keys from the
invoking Map.
Set valueSet() It returns a set that contains all the values from the
invoking Map.
Set entrySet() It returns a set that contains all the entries from the
invoking Map.
HashMap Class
The HashMap class is a child class of AbstractMap, and it implements the Map interface.
The HashMap is used to store the data in the form of key, value pair using hash table
concept.
Key Properties of HashMap
✔ HashMap is a child class of AbstractMap class.
✔ HashMap implements the interfeaces Map, Cloneable, and Serializable.
✔ HashMap stores data as a pair of key and value.
✔ HashMap uses Hash table concept to store the data.
✔ HashMap does not allow duplicate keys, but values may be repeated.
✔ HashMap allows only one null key and multiple null values.
✔ HashMap does not follow any oreder.
✔ HashMap has the default capacity 16 entries.
Example program to illustrate HashMap
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 36
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
import [Link].*;
public class HashMapExample {
public static void main(String[] args) {
Scanner read = new Scanner([Link]);
HashMap employeeInfo = new HashMap();
HashMap contactInfo = new HashMap();
[Link](1, "Varun");
[Link](2, "Joel");
[Link](3, "Snigdha");
[Link](4, "Donny");
[Link](5, "Sunny");
[Link]("Employee Information\n" + employeeInfo);
[Link]("\nPlease enter the ID and Contact number");
[Link]("Employee IDs : " + [Link]());
[Link]("Enter ID: ");
int id = [Link]();
[Link]("Enter Contact Number: ");
long contactNo = [Link]();
if([Link](id)) {
[Link](id, contactNo);
}
[Link]("\n\nEmployee Contact Information\n");
[Link]("ID - " + id);
[Link]("Name - " + [Link](id));
[Link]("Contact Number - " + [Link](id));
}
}
LinkedHashMap Class
The LinkedHashMap class is a child class of HashMap, and it implements the Map
interface. The LinkedHashMap is used to store the data in the form of key, value pair using
hash table and linked list concepts.
Key Properties of LinkedHashMap
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 37
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
✔ LinkedHashMap is a child class of HashMap class.
✔ LinkedHashMap implements the Map interface.
✔ LinkedHashMap stores data as a pair of key and value.
✔ LinkedHashMap uses Hash table concept to store the data.
✔ LinkedHashMap does not allow duplicate keys, but values may be repeated.
✔ LinkedHashMap allows only one null key and multiple null values.
✔ LinkedHashMap follows the insertion oreder.
✔ LinkedHashMap has the default capacity 16 entries.
Example program to illustrate LinkedHashMap
import [Link].*;
public class HashMapExample {
public static void main(String[] args) {
Scanner read = new Scanner([Link]);
LinkedHashMap employeeInfo = new LinkedHashMap();
LinkedHashMap contactInfo = new LinkedHashMap();
[Link](1, "Raja");
[Link](2, "Gouthami");
[Link](3, "Heyansh");
[Link](4, "Yamini");
[Link](5, "ManuTej");
[Link]("Employee Information\n" + employeeInfo);
[Link]("\nPlease enter the ID and Contact number");
[Link]("Employee IDs : " + [Link]());
[Link]("Enter ID: ");
int id = [Link]();
[Link]("Enter Contact Number: ");
long contactNo = [Link]();
if([Link](id)) {
[Link](id, contactNo);
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 38
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
}
[Link]("\n\nEmployee Contact Information\n");
[Link]("ID - " + id);
[Link]("Name - " + [Link](id));
[Link]("Contact Number - " + [Link](id));
}
}
TreeMap Class
The TreeMap class is a child class of AbstractMap, and it implements the NavigableMap
interface which is a child interface of SortedMap. The TreeMap is used to store the data in
the form of key, value pair using red-black tree concepts.
Key Properties of TreeMap
✔ TreeMap is a child class of AbstractMap class.
✔ TreeMap implements the NavigableMap interface which is a child interface of
SortedMap interface.
✔ TreeMap stores data as a pair of key and value.
✔ TreeMap uses red-black tree concept to store the data.
✔ TreeMap does not allow duplicate keys, but values may be repeated.
✔ TreeMap does not allow null key, but allows null values.
✔ TreeMap follows the ascending oreder based on keys.
Example program to illustrate TreeMap.
import [Link].*;
public class HashMapExample {
public static void main(String[] args) {
Scanner read = new Scanner([Link]);
TreeMap employeeInfo = new TreeMap();
TreeMap contactInfo = new TreeMap();
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 39
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link](1, "Varun");
[Link](4, "Joel");
[Link](5, "Snigdha");
[Link](3, "Shailaja");
[Link](2, "Sunny");
[Link]("Employee Information\n" + employeeInfo);
[Link]("\nPlease enter the ID and Contact number");
[Link]("Employee IDs : " + [Link]());
[Link]("Enter ID: ");
int id = [Link]();
[Link]("Enter Contact Number: ");
long contactNo = [Link]();
if([Link](id)) {
[Link](id, contactNo);
}
[Link]("\n\nEmployee Contact Information\n");
[Link]("ID - " + id);
[Link]("Name - " + [Link](id));
[Link]("Contact Number - " + [Link](id));
}
}
Comparators in java
The Comparator is an interface available in the [Link] package. The java Comparator is
used to order the objects of user-defined classes. The java Comparator can compare two
objects from two different classes.
Using the java Comparator, we can sort the elements based on data members of a class. For
example, we can sort based on roolNo, age, salary, marks, etc.
The Comparator interface has the following methods.
Method Description
int compare(Object obj1, It is used to compares the obj1 with o bj2 .
Object obj2)
boolean equals(Object obj) It is used to check the equity between current object and
argumented object.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 40
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
The Comparator can be used in the following three ways.
✔ Using a separate class that implements Comparator interface.
✔ Using anonymous class.
✔ Using lamda expression.
Using a separate class
We use the following steps to use Comparator with a seperate class.
Step - 1: Create the user-defined class.
Step - 2: Create a class that implements Comparator interface.
Step - 3: Implement the compare( ) method of Comparator interface inside the above
defined class(step - 2).
Step - 4: Create the actual class where we use the Compatator object with sort method of
Collections class.
Step - 5: Create the object of Compatator interface using the class crearted in step - 2.
Step - 6: Call the sort method of Collections class by passing the object created in step - 6.
Step - 7: Use a for-each (any loop) to print the sorted information.
Example program to illustrate Comparator using a separate class.
import [Link].*;
class Student{
String name;
float percentage;
Student(String name, float percentage){
[Link] = name;
[Link] = percentage;
}
}
class PercentageComparator implements Comparator<Student>{
public int compare(Student stud1, Student stud2) {
if([Link] < [Link])
return 1;
return -1;
}
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 41
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
}
public class StudentCompare{
public static void main(String args[]) {
ArrayList<Student> studList = new ArrayList<Student>();
[Link](new Student("Varun", 90.61f));
[Link](new Student("Joel", 83.55f));
[Link](new Student("Snigdha", 85.55f));
[Link](new Student("shailaja", 77.56f));
[Link](new Student("sunny", 80.89f));
Comparator<Student> com = new PercentageComparator();
[Link](studList, com);
[Link]("Avg % --> Name");
[Link]("---------------------");
for(Student stud:studList) {
[Link]([Link] + " --> " + [Link]);
}
}
}
Using anonymous class
We use the following steps to use Comparator with anonymous class.
Step - 1: Create the user-defined class.
Step - 2: Create the actual class where we use the Comparator object with sort method of
Collections class.
Step - 3: Create the object of Comparator interface using anonymous class and implement
compare method of Comparator interface.
Step - 4: Call the sort method of Collections class by passing the object created in step - 6.
Step - 5: Use a for-each (any loop) to print the sorted information.
Example program to illustrate Comparator using a separate class.
import [Link].*;
class Student{
String name;
float percentage;
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 42
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Student(String name, float percentage){
[Link] = name;
[Link] = percentage;
}
}
public class StudentCompare{
public static void main(String args[]) {
ArrayList<Student> studList = new ArrayList<Student>();
[Link](new Student("Varun", 90.61f));
[Link](new Student("Joel", 83.55f));
[Link](new Student("Snigdha", 85.55f));
[Link](new Student("shailaja", 77.56f));
[Link](new Student("Sunny", 80.89f));
Comparator<Student> com = new Comparator<Student>() {
public int compare(Student stud1, Student stud2) {
if([Link] < [Link])
return 1;
return -1;
}
};
[Link](studList, com);
[Link]("Avg % --> Name");
[Link]("---------------------");
for(Student stud:studList) {
[Link]([Link] + " --> " + [Link]);
}
}
}
Using lamda expression
We use the following steps to use Comparator with lamda expression.
Step - 1: Create the user-defined class.
Step - 2: Create the actual class where we use the Comparator object with sort method of
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 43
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Collections class.
Step - 3: Create the object of Comparator interface using lamda expression and implement
the code for compare method of Comparator interface.
Step - 4: Call the sort method of Collections class by passing the object created in step - 6.
Step - 5: Use a for-each (any loop) to print the sorted information.
Example program to illustrate Comparator using a separate class.
import [Link].*;
class Student{
String name;
float percentage;
Student(String name, float percentage){
[Link] = name;
[Link] = percentage;
}
}
public class StudentCompare{
public static void main(String args[]) {
ArrayList<Student> studList = new ArrayList<Student>();
[Link](new Student("Varun", 90.61f));
[Link](new Student("Joel", 83.55f));
[Link](new Student("Snigdha", 85.55f));
[Link](new Student("Shailaja", 77.56f));
[Link](new Student("Sunny", 80.89f));
Comparator<Student> com = (stud1, stud2) -> {
if([Link] < [Link])
return 1;
return -1;
};
[Link](studList, com);
[Link]("Avg % --> Name");
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 44
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]("---------------------");
for(Student stud:studList) {
[Link]([Link] + " --> " + [Link]);
}
}
}
Collection algorithms in java
The java collection framework defines several algorithms as static methods that can be used
with collections and map objects.
All the collection algorithms in the java are defined in a class called Collections which
defined in the [Link] package.
All these algorithms are highly efficient and make coding very easy. It is better to use them
than trying to re-implement them.
The collection framework has the following methods as algorithms.
Method Description
void sort(List list) Sorts the elements of the list as determined by
their natural ordering.
void sort(List list, Comparator comp) Sorts the elements of the list as determined by
Comparator comp.
void reverse(List list) Reverses all the elements sequence in list.
void rotate(List list, int n) Rotates list by n places to the right. To rotate
left, use a negative value for n.
void shuffle(List list) Shuffles the elements in list.
void shuffle(List list, Random r) Shuffles the elements in the list by using r as a
source of random numbers.
void copy(List list1, List list2) Copies the elements of list2 to list1.
List nCopies(int num, Object obj) Returns num copies of obj contained in an
immutable list. num can not be zero or negative.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 45
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Method Description
void swap(List list, int idx1, int idx2) Exchanges the elements in the list at the indices
specified by idx1 and idx2.
int binarySearch(List list, Object value) Returns the position of value in the list (must be
in the sorted order), or -1 if value is not found.
int binarySearch(List list, Object value, Returns the position of value in the list ordered
Comparator c) according to c, or -1 if value is not found.
int indexOfSubList(List list, List Returns the index of the first match of subList in
subList) the list, or -1 if no match is found.
int lastIndexOfSubList(List list, List Returns the index of the last match of subList in
subList) the list, or -1 if no match is found.
Object max(Collection c) Returns the largest element from the collection c
as determined by natural ordering.
Object max(Collection c, Comparator Returns the largest element from the collection c
comp) as determined by Comparator comp.
Object min(Collection c) Returns the smallest element from the collection
c as determined by natural ordering.
Object min(Collection c, Comparator Returns the smallest element from the collection
comp) c as determined by Comparator comp.
void fill(List list, Object obj) Assigns obj to each element of the list.
boolean replaceAll(List list, Object old, Replaces all occurrences of old with new in the
Object new) list.
Enumeration enumeration(Collection c) Returns an enumeration over Collection c.
ArrayList list(Enumeration enum) Returns an ArrayList that contains the elements
of enum.
Set singleton(Object obj) Returns obj as an immutable set.
List singletonList(Object obj) Returns obj as an immutable list.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 46
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Method Description
Map singletonMap(Object k, Object v) Returns the key(k)/value(v) pair as an
immutable map.
Collection Returns a thread-safe collection backed by c.
synchronizedCollection(Collection c)
List synchronizedList(List list) Returns a thread-safe list backed by list.
Map synchronizedMap(Map m) Returns a thread-safe map backed by m.
SortedMap Returns a thread-safe SortedMap backed by sm.
synchronizedSortedMap(SortedMap sm)
Set synchronizedSet(Set s) Returns a thread-safe set backed by s.
SortedSet Returns a thread-safe set backed by ss.
synchronizedSortedSet(SortedSet ss)
Collection Returns an unmodifiable collection backed by c.
unmodifiableCollection(Collection c)
List unmodifiableList(List list) Returns an unmodifiable list backed by list.
Set unmodifiableSet(Set s) Returns an unmodifiable thread-safe set backed
by s.
SortedSet Returns an unmodifiable set backed by ss.
unmodifiableSortedSet(SortedSet ss)
Map unmodifiableMap(Map m) Returns an unmodifiable map backed by m.
SortedMap Returns an unmodifiable SortedMap backed by
unmodifiableSortedMap(SortedMap sm) sm.
Example program to illustrate Collections algorithms
import [Link].*;
public class CollectionAlgorithmsExample {
public static void main(String[] args) {
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 47
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
ArrayList list = new ArrayList();
PriorityQueue queue = new PriorityQueue();
HashSet set = new HashSet();
HashMap map = new HashMap();
Random num = new Random();
for(int i = 0; i < 5; i++) {
[Link]([Link](100));
[Link]([Link](100));
[Link]([Link](100));
[Link](i, [Link](100));
}
[Link]("List => " + list);
[Link]("Queue => " + queue);
[Link]("Set => " + set);
[Link]("Map => " + map);
[Link]("---------------------------------------");
[Link](list);
[Link]("List in ascending order => " + list);
[Link]("Largest element in set => " + [Link](set));
[Link]("Smallest element in queue => " +
[Link](queue));
[Link](list);
[Link]("List in reverse order => " + list);
[Link](list);
[Link]("List after shuffle => " + list);
}
}
Arrays class in java
The java collection framework has a class Arrays that provides methods for creating
dynamic array and perform various operations like search, asList, campare, etc.
The Arrays class in java is defined in the [Link] package. All the methods defined by
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 48
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Arrays class are static methods.
The Arrays class in java has the following methods.
Method Description
List<T> asList(T[] arr) It returns a fixed-size list backed by the specified Arrays.
int binarySearch(T[] arr, It searches for the specified element in the array with the
element) help of Binary Search algorithm, and returns the position.
int binarySearch(T[] arr, int It searches a range of the specified array for the specified
fromIndex, int toIndex, T key, object using the binary search algorithm.
Comparator c)
T[] copyOf(T[] originalArr, It copies the specified array, truncating or padding with the
int newLength) default value (if necessary) so the copy has the specified
length.
T[] copyOfRange(T[] It copies the specified range of the specified array into a
originalArr, int fromIndex, int new Arrays.
endIndex)
boolean equals(T[] arr1, T[] It returns true if the two specified arrays of booleans are
arr2) equal to one another, otherwise retruns false.
boolean deepEquals(T[] arr1, It returns true if the two specified arrays of booleans are
T[] arr2) deeply equal to one another, otherwise retruns false (it
compares including nested arrays).
int hashCode(T[] arr) It returns the hash code for the specified array.
int deepHashCode(T[] arr) It returns the hash code for the specified array including
nested arrays.
String toString(T[] arr) It Returns a string representation of the contents of the
specified array.
String deepToString(T[] arr) It Returns a string representation of the contents of the
specified array including nested arrays.
void fill(T[] arr, T value) It assigns the specified value to each element of the
specified array.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 49
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Method Description
void fill(T[] arr, int It assigns the specified value to each element of the
fromIndex, int toIndex, T specified range of the specified array. The range to be filled
value) extends from fromIndex, inclusive, to toIndex, exclusive.
void parallelPrefix(T[] arr, It Cumulates, in parallel, each element of the given array in
BinaryOperator o) place, using the supplied function.
void setAll(T[] arr, It sets all elements of the specified array, using the
FunctionGenerator) provided generator function to compute each element.
void parallelSetAll(T[] arr, It Sets all elements of the specified array, in parallel, using
FunctionGenerator) the provided generator function to compute each element.
void sort(T[] arr) It sorts the specified array into ascending order.
void parallelSort(T[] arr) It sorts the specified array of objects into ascending order,
according to the natural ordering of its elements.
Of<T> spliterator(T[] arr) It returns a [Link]<T> covering all of the specified
array.
Stream<T> stream(T[] arr) It returns a sequential Stream with the specified array as its
source.
Example program to illustrate methods of Arrays class
import [Link].*;
public class ArraysClassExample {
public static void main(String[] args) {
int[] arr1 = {10, 3, 50, 7, 30, 66, 28, 54, 42};
int[] arr2 = {67, 2, 54, 67, 13, 56, 98};
[Link]("Array1 => ");
for(int i:arr1)
[Link](i + ", ");
[Link]("\nArray2 => ");
for(int i:arr2)
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 50
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link](i + ", ");
[Link]("\n-------------------------------------------");
[Link]("Array1 as List => " + [Link](arr1));
[Link]("Position of 30 in Array1 => " +
[Link](arr1, 30));
[Link]("equity of array1 and array2 => " + [Link](arr1,
arr2));
[Link]("Hash code of Array1 => " + [Link](arr1));
[Link](arr1, 15);
[Link]("fill Array1 with 15 => ");
for(int i:arr1)
[Link](i + ", ");
[Link](arr2);
[Link]("\nArray2 in sorted order => ");
for(int i:arr2)
[Link](i + ", ");
}
}.
Dictionary class in java
In java, the package [Link] contains a class called Dictionary which works like a Map. The
Dictionary is an abstract class used to store and manage elements in the form of a pair of
key and value.
The Dictionary stores data as a pair of key and value. In the dictionary, each key associates
with a value. We can use the key to retrieve the value back when needed.
✔ The Dictionary class is no longer in use, it is obsolete.
✔ As Dictionary is an abstract class we can not create its object. It needs a child class
like Hashtable.
The Dictionary class in java has the following methods.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 51
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
S. No Methods with Description
1 Dictionary( )
It's a constructor.
2 Object put(Object key, Object value)
Inserts a key and its value into the dictionary. Returns null on success; returns the
previous value associated with the key if the key is already exist.
3 Object remove(Object key)
It returns the value associated with given key and removes the same; Returns null if
the key does not exist.
4 Object get(Object key)
It returns the value associated with given key; Returns null if the key does not exist.
5 Enumeration keys( )
Returns an enumeration of the keys contained in the dictionary.
6 Enumeration elements( )
Returns an enumeration of the values contained in the dictionary.
7 boolean isEmpty( )
It returns true if dictionary has no elements; otherwise returns false.
8 int size( )
It returns the total number of elements in the dictionary.
Example program to illustrate methods of Dictionary class.
import [Link].*;
public class DictionaryExample {
public static void main(String args[]) {
Dictionary dict = new Hashtable();
[Link](1, "Varun");
[Link](2, "Joel");
[Link](3, "Nithin");
[Link](4, "snigdha");
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 52
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link](5, "Dart");
[Link]("Dictionary\n=> " + dict);
// keys()
[Link]("\nKeys in Dictionary\n=> ");
for (Enumeration i = [Link](); [Link]();)
{
[Link](" " + [Link]());
}
// elements()
[Link]("\n\nValues in Dictionary\n=> ");
for (Enumeration i = [Link](); [Link]();)
{
[Link](" " + [Link]());
}
//get()
[Link]("\n\nValue associated with key 3 => " + [Link](3));
[Link]("Value associated with key 30 => " + [Link](30));
//size()
[Link]("\nDictionary has " + [Link]() + " elements");
//isEmpty()
[Link]("\nIs Dictionary empty? " + [Link]());
}
}
Hashtable class in java
In java, the package [Link] contains a class called Hashtable which works like a HashMap
but it is synchronized. The Hashtable is a concrete class of Dictionary. It is used to store and
manage elements in the form of a pair of key and value.
The Hashtable stores data as a pair of key and value. In the Hashtable, each key associates
with a value. Any non-null object can be used as a key or as a value. We can use the key to
retrieve the value back when needed.
✔ The Hashtable class is no longer in use, it is obsolete. The alternate class is
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 53
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
HashMap.
✔ The Hashtable class is a concrete class of Dictionary.
✔ The Hashtable class is synchronized.
✔ The Hashtable does no allow null key or value.
✔ The Hashtable has the initial default capacity 11.
The Hashtable class in java has the following constructors.
S. No. Constructor with Description
1 Hashtable( )
It creates an empty hashtable with the default initial capacity 11.
2 Hashtable(int capacity)
It creates an empty hashtable with the specified initial capacity.
3 Hashtable(int capacity, float loadFactor)
It creates an empty hashtable with the specified initial capacity and loading factor.
4 Hashtable(Map m)
It creates a hashtable containing elements of Map m.
S. No. Methods with Description
1 V put(K key, V value)
It inserts the specified key and value into the hash table.
2 void putAll(Map m))
It inserts all the elements of Map m into the invoking Hashtable.
3 V putIfAbsent(K key, V value)
If the specified key is not already associated with a value associates it with the
given value and returns null, else returns the current value.
4 V getOrDefault(Object key, V defaultValue)
It returns the value associated with given key; or defaultValue if the hashtable
contains no mapping for the key.
5 V get(Object key)
It returns the value associated with the given key.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 54
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
S. No. Constructor with Description
6 Enumeration keys()
Returns an enumeration of the keys of the hashtable.
7 Set keySet()
Returns a set view of the keys of the hashtable.
8 Collection values()
It returns a collection view of the values contained in the Hashtable.
9 Enumeration elements()
Returns an enumeration of the values of the hashtable.
10 Set entrySet()
It returns a set view of the mappings contained in the hashtable.
11 int hashCode()
It returns the hash code of the hashtable.
12 Object clone()
It returns a shallow copy of the Hashtable.
13 V remove(Object key)
It returns the value associated with given key and removes the same.
14 boolean remove(Object key, Object value)
It removes the specified values with the associated specified keys from the
hashtable.
15 boolean contains(Object value)
It returns true if the specified value found within the hash table, else return false.
16 boolean containsValue(Object value)
It returns true if the specified value found within the hash table, else return false.
17 boolean containsKey(Object key)
It returns true if the specified key found within the hash table, else return false.
18 V replace(K key, V value)
It replaces the specified value for a specified key.
19 boolean replace(K key, V oldValue, V newValue)
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 55
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
S. No. Constructor with Description
It replaces the old value with the new value for a specified key.
20 void replaceAll(BiFunction function)
It replaces each entry's value with the result of invoking the given function on that
entry until all entries have been processed or the function throws an exception.
21 void rehash()
It is used to increase the size of the hash table and rehashes all of its keys.
22 String toString()
It returns a string representation of the Hashtable object.
23 V merge(K key, V value, BiFunction remappingFunction)
If the specified key is not already associated with a value or is associated with null,
associates it with the given non-null value.
24 void forEach(BiConsumer action)
It performs the given action for each entry in the map until all entries have been
processed or the action throws an exception.
25 boolean isEmpty( )
It returns true if Hashtable has no elements; otherwise returns false.
26 int size( )
It returns the total number of elements in the Hashtable.
27 void clear()
It is used to remove all the lements of a Hashtable.
28 boolean equals(Object o)
It is used to compare the specified Object with the Hashtable.
Example program to illustrate methods of Hashtable class.
import [Link].*;
public class HashtableExample {
public static void main(String[] args) {
Random num = new Random();
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 56
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Hashtable table = new Hashtable();
//put(key, value)
for(int i = 1; i <= 5; i++)
[Link](i, [Link](100));
[Link]("Hashtable => " + table);
//get(key)
[Link]("\nValue associated with key 3 => " + [Link](3));
[Link]("Value associated with key 30 => " + [Link](30));
//keySet()
[Link]("\nKeys => " + [Link]());
//values()
[Link]("\nValues => " + [Link]());
//entrySet()
[Link]("\nKey, Value pairs as a set => " + [Link]());
//hashCode()
[Link]("\nHash code => " + [Link]());
//hashCode()
[Link]("\nTotal number of elements => " + [Link]());
//isEmpty()
[Link]("\nEmpty status of Hashtable => " + [Link]());
}
}
Properties class in java
In java, the package [Link] contains a class called Properties which is a child class of
Hashtable class. It implements interfaces like Map, Cloneable, and Serializable.
Java has this built-in class Properties which allow us to save and load multiple values from a
file. This makes the class extremely useful for accessing data related to configuration.
The Properties class used to store configuration values managed as key, value pairs. In each
pair, both key and value are String values. We can use the key to retrieve the value back
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 57
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
when needed.
The Properties class provides methods to get data from the properties file and store data into
the properties file. It can also be used to get the properties of a system.
✔ The Properties class is child class of Hashtable class.
✔ The Properties class implements Map, Cloneable, and Serializable interfaces.
✔ The Properties class used to store configuration values.
✔ The Properties class stores the data as key, value pairs.
✔ In Properties class both key and value are String data type.
✔ Using Properties class, we can load key, value pairs into a Properties object from a
stream.
✔ Using Properties class, we can save the Properties object to a stream.
The Properties class in java has the following constructors.
S. No. Constructor with Description
1 Properties( )
It creates an empty property list with no default values.
2 Properties(Properties defaults)
It creates an empty property list with the specified defaults.
The Properties class in java has the following methods.
[Link] Methods with Description
.
1 void load(Reader r)
It loads data from the Reader object.
2 void load(InputStream is)
It loads data from the InputStream object.
3 void store(Writer w, String comment)
It writes the properties in the writer object.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 58
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link] Methods with Description
.
4 void store(OutputStream os, String comment)
It writes the properties in the OutputStream object.
5 String getProperty(String key)
It returns value associated with the specified key.
6 String getProperty(String key, String defaultValue)
It returns the value associated with given key; or defaultValue if the Properties
contains no mapping for the key.
7 void setProperty(String key, String value)
It calls the put method of Hashtable.
8 Enumeration propertyNames())
It returns an enumeration of all the keys from the property list.
9 Set stringPropertyNames()
Returns a set view of the keys of the Properties.
10 void list(PrintStream out)
It is used to print the property list out to the specified output stream.
11 void loadFromXML(InputStream in)
It is used to load all of the properties represented by the XML document on the
specified input stream into this properties table.
12 void storeToXML(OutputStream os, String comment)
It writes the properties in the writer object for generating XML document.
13 void storeToXML(Writer w, String comment, String encoding)
It writes the properties in the writer object for generating XML document with the
specified encoding.
Example program to illustrate methods of Properties class to store a user
configuration details to a properties file.
import [Link].*;
import [Link].*;
public class PropertiesClassExample {
public static void main(String[] args) {
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 59
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
FileOutputStream fos = null;
File configFile = null;
try {
configFile = new File("[Link]");
fos = new FileOutputStream(configFile);
Properties configProperties = new Properties();
[Link]("userName", "btechsmartclass");
[Link]("password", "java");
[Link]("email", "user@[Link]");
[Link](fos, "Login Details");
[Link]();
[Link]("Configuration saved!!!");
}
catch(Exception e) {
[Link]("Something went wrong while opening file");
}
}
}
Stack class in java
In java, the package [Link] contains a class called Stack which is a child class of Vector
class. It implements the standard principle Last-In-First-Out of stack data structure.
The Stack has push method for inesrtion and pop method for deletion. It also has other
utility methods.
In Stack, the elements are added to the top of the stack and removed from the top of the
stack.
The Stack class in java has the following constructor.
S. No. Constructor with Description
1 Stack( )
It creates an empty Stack.
The Stack class in java has the following methods.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 60
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]. Methods with Description
1 Object push(Object element)
It pushes the element onto the stack and returns the same.
2 Object pop( )
It returns the element on the top of the stack and removes the same.
3 int search(Object element)
If element found, it returns offset from the top. Otherwise, -1 is returned.
4 Object peek( )
It returns the element on the top of the stack.
5 boolean empty()
It returns true if the stack is empty, otherwise returns false.
Example program to illustrate methods of Stack class.
import [Link].*;
public class StackClassExample {
public static void main(String[] args) {
Stack stack = new Stack();
Random num = new Random();
for(int i = 0; i < 5; i++)
[Link]([Link](100));
[Link]("Stack elements => " + stack);
[Link]("Top element is " + [Link]());
[Link]("Removed element is " + [Link]());
[Link]("Element 50 availability => " + [Link](50));
[Link]("Stack is empty? - " + [Link]());
}
}
Vector class in java
In java, the package [Link] contains a class called Vector which implements the List
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 61
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
interface.
The Vector is similar to an ArrayList. Like ArrayList Vector also maintains the insertion
order. But Vector is synchronized, due to this reason, it is rarly used in the non-thread
application. It also lead to poor performance.
✔ The Vector is a class in the [Link] package.
✔ The Vector implements List interface.
✔ The Vector is a legacy class.
✔ The Vector is synchronized.
The Vector class in java has the following constructor.
S. No. Constructor with Description
1 Vector( )
It creates an empty Vector with default initail capacity of 10.
2 Vector(int initialSize)
It creates an empty Vector with specified initail capacity.
3 Vector(int initialSize, int incr)
It creates a vector whose initial capacity is specified by size and whose increment
is specified by incr.
4 Vector(Collection c)
It creates a vector that contains the elements of collection c.
The Vector class in java has the following methods.
[Link] Methods with Description
.
1 boolean add(Object o)
It appends the specified element to the end of this Vector.
2 void add(int index, Object element)
It inserts the specified element at the specified position in this Vector.
3 void addElement(Object obj)
Adds the specified object to the end of the vector, increasing its size by one.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 62
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link] Methods with Description
.
4 boolean addAll(Collection c)
It appends all of the elements in the specified Collection to the end of the Vector.
5 boolean addAll(int index, Collection c)
It inserts all of the elements in in the specified Collection into the Vector at the
specified position.
6 Object set(int index, Object element)
It replaces the element at the specified position in the vector with the specified
element.
7 void setElementAt(Object obj, int index)
It sets the element at the specified index of the vector to be the specified object.
8 Object remove(int index)
It removes the element at the specified position in the vector.
9 boolean remove(Object o)
It removes the first occurrence of the specified element in the vector.
10 boolean removeElement(Object obj)
It removes the first occurrence of the specified element in the vector.
11 void removeElementAt(int index)
It removes the element at specified index in the vector.
12 void removeRange(int fromIndex, int toIndex)
It removes from the Vector all of the elements whose index is between fromIndex,
inclusive and toIndex, exclusive.
13 boolean removeAll(Collection c)
It removes from the vector all of its elements that are contained in the specified
Collection.
14 void removeAllElements()
It removes all the elements from the vector.
15 boolean retainAll(Collection c)
It removes all the elements from the vector except elements those are in the given
collection.
16 Object elementAt(int index)
It returns the element at specified index in the Vector.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 63
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link] Methods with Description
.
17 Object get(int index)
It returns the element at specified index in the Vector.
18 Enumeration elements()
It returns the Enumeration of all the elements of the Vector.
19 Object firstElement()
It returns the first element of the Vector.
20 Object lastElement()
It returns the last element of the Vector.
21 int indexOf(Object element)
It returns the index value of the first occurence of the given element in the Vector.
22 int indexOf(Object elem, int index)
It returns the index value of the first occurence of the given element, search
beginning at specified index in the Vector.
23 int lastIndexOf(Object elememnt)
It returns the index value of the last occurence of the given element, search
beginning at specified index in the Vector.
24 List subList(int fromIndex, int toIndex)
It returns a list containing elements fromIndex to toIndex in the Vector.
25 int capacity()
It returns the current capacity of the Vector.
26 void clear()
It removes all the elements from the Vector.
27 Object clone()
It returns a clone of the Vector.
28 boolean contains(Object element)
It returns true if element found in the Vector, otherwise returns false.
29 boolean containsAll(Collection c)
It returns true if all the elements of geven collection found in the Vector, otherwise
returns false.
30 void ensureCapacity(int minCapacity)
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 64
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link] Methods with Description
.
It increases the capacity of this vector, if necessary, to ensure that it can hold at least
the number of components specified by the minimum capacity argument.
31 boolean equals(Object o)
It compares the specified Object with this vector for equality.
32 int hashCode()
It returns the hash code of the Vector.
33 boolean isEmpty()
It returns true if Vector has no elements, otherwise returns false.
34 void setSize(int newSize)
It sets the size of the vector.
35 int size()
It returns total number of elements in the vector.
36 Object[] toArray()
It returns an array containing all the elements of the Vector.
37 String toString()
It returns a string representation of the Vector.
38 void trimToSize()
It trims the capacity of the vector to be the vector's current size.
Example program to illustrate methods of Vector class
import [Link].*;
public class VectorClassExample {
public static void main(String[] args) {
Vector list = new Vector();
[Link](10);
[Link](30);
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 65
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link](0, 100);
[Link](50);
[Link]("Vector => " + list);
[Link]("get(2) => " + [Link](2));
[Link]("firstElement() => " + [Link]());
[Link]("indexOf(50) => " + [Link](50));
[Link]("contains(30) => " + [Link](30));
[Link]("capacity() => " + [Link]());
[Link]("size() => " + [Link]());
[Link]("isEmpty() => " + [Link]());
}
}
StringTokenizer class in java
The StringTokenizer is a built-in class in java used to break a string into tokens. The
StringTokenizer class is available inside the [Link] package.
The StringTokenizer class object internally maintains a current position within the string to
be tokenized.
Note:
A token is returned by taking a substring of the string that was used to create the
StringTokenizer object.
The StringTokenizer class in java has the following constructor.
S. No. Constructor with Description
1 StringTokenizer(String str)
It creates StringTokenizer object for the specified string str with default delimeter.
2 StringTokenizer(String str, String delimeter)
It creates StringTokenizer object for the specified string str with specified
delimeter.
3 StringTokenizer(String str, String delimeter, boolean returnValue)
It creates StringTokenizer object with specified string, delimeter and returnValue.
Example:
import [Link];
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 66
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
public class StringTokenizerExample {
public static void main(String[] args) {
String url = "[Link]
String title = "Engineering College";
StringTokenizer tokens = new StringTokenizer(title);
StringTokenizer anotherTokens = new StringTokenizer(url, ".");
[Link]("\nTotal tokens in title is " + [Link]());
[Link]("Tokens in the title => ");
while([Link]()) {
[Link]([Link]() + ", ");
}
[Link]("\n\nTotal tokens in url is " +
[Link]());
[Link]("Tokens in the url with delimeter (.) => ");
while([Link]()) {
[Link]([Link]() + ", ");
}
}
}
BitSet class in java
The BitSet is a built-in class in java used to create a dynamic array of bits represented by
boolean values. The BitSet class is available inside the [Link] package.
The BitSet array can increase in size as needed. This feature makes the BitSet similar to a
Vector of bits.
● The bit values can be accessed by non-negative integers as an index.
● The size of the array is flexible and can grow to accommodate additional bit as
needed.
● The default value of the BitSet is boolean false with a representation as 0 (off).
● BitSet uses 1 bit of memory per each boolean value.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 67
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
The BitSet class in java has the following constructor.
S. Constructor with Description
No.
1 BitSet( )
It creates a default BitSet object.
2 BitSet(int noOfBits)
It creates a BitSet object with number of bits that it can hold. All bits are initialized
to zero.
Example:
import [Link].*;
public class BitSetClassExample {
public static void main(String[] args) {
BitSet bSet_1 = new BitSet();
BitSet bSet_2 = new BitSet(16);
bSet_1.set(10);
bSet_1.set(5);
bSet_1.set(0);
bSet_1.set(7);
bSet_1.set(20);
bSet_2.set(1);
bSet_2.set(15);
bSet_2.set(20);
bSet_2.set(77);
bSet_2.set(50);
[Link]("BitSet_1 => " + bSet_1);
[Link]("BitSet_2 => " + bSet_2);
bSet_1.and(bSet_2);
[Link]("BitSet_1 after and with bSet_2 => " + bSet_1);
bSet_1.andNot(bSet_2);
[Link]("BitSet_1 after andNot with bSet_2 => " + bSet_1);
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 68
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]("Length of the bSet_2 => " + bSet_2.length());
[Link]("Size of the bSet_2 => " + bSet_2.size());
[Link]("Bit at index 2 in bSet_2 => " + bSet_2.get(2));
bSet_2.set(2);
[Link]("Bit at index 2 after set in bSet_2 => " + bSet_2.get(2));
}
}
Date class in java
The Date is a built-in class in java used to work with date and time in java. The Date class is
available inside the [Link] package. The Date class represents the date and time with
millisecond precision.
The Date class implements Serializable, Cloneable and Comparable interface.
Note:
Most of the constructors and methods of Date class has been deprecated after Calendar class
introduced.
The Date class in java has the following constructor.
S. Constructor with Description
No.
1 Date( )
It creates a Date object that represents current date and time.
2 Date(long milliseconds)
It creates a date object for the given milliseconds since January 1, 1970, 00:00:00
GMT.
3 Date(int year, int month, int date) - Depricated
It creates a date object with the specified year, month, and date.
4 Date(int year, int month, int date, int hrs, int min) - Depricated
It creates a date object with the specified year, month, date, hours, and minuts.
5 Date(int year, int month, int date, int hrs, int min, int sec) - Depricated
It creates a date object with the specified year, month, date, hours, minuts and
seconds.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 69
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
S. Constructor with Description
No.
5 Date(String s) - Depricated
It creates a Date object and initializes it so that it represents the date and time
indicated by the string s, which is interpreted as if by the parse([Link])
method.
The Date class in java has the following methods.
[Link]. Methods with Description
1 long getTime()
It returns the time represented by this date object.
2 boolean after(Date date)
It returns true, if the invoking date is after the argumented date.
3 boolean before(Date date)
It returns true, if the invoking date is before the argumented date.
4 Date from(Instant instant)
It returns an instance of Date object from Instant date.
5 void setTime(long time)
It changes the current date and time to given time.
6 Object clone( )
It duplicates the invoking Date object.
7 int compareTo(Date date)
It compares current date with given date.
8 boolean equals(Date date)
It compares current date with given date for equality.
9 int hashCode()
It returns the hash code value of the invoking date object.
10 Instant toInstant()
It converts current date into Instant object.
11 String toString()
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 70
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]. Methods with Description
It converts this date into Instant object.
An example program to illustrate methods of Date class.
Example:
import [Link];
import [Link];
public class DateClassExample {
public static void main(String[] args) {
Date time = new Date();
[Link]("Current date => " + time);
[Link]("Date => " + [Link]() + " milliseconds");
[Link]("after() => " + [Link](time) + " milliseconds");
[Link]("before() => " + [Link](time) + " milliseconds");
[Link]("hashCode() => " + [Link]());
}
}
Calendar class in java
The Calendar is a built-in abstract class in java used to convert date between a specific
instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. The
Calendar class is available inside the [Link] package.
The Calendar class implements Serializable, Cloneable and Comparable interface.
● As the Calendar class is an abstract class, we can not create an object using it.
● We will use the static method [Link]() to instantiate and implement a
sub-class.
The Calendar class in java has the following methods.
[Link] Methods with Description
.
1 Calendar getInstance()
It returns a calendar using the default time zone and locale.
2 Date getTime()
It returns a Date object representing the invoking Calendar's time value.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 71
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link] Methods with Description
.
3 TimeZone getTimeZone()
It returns the time zone object associated with the invoking calendar.
4 String getCalendarType()
It returns an instance of Date object from Instant date.
5 int get(int field)
It rerturns the value for the given calendar field.
6 int getFirstDayOfWeek()
It returns the day of the week in integer form.
7 int getWeeksInWeekYear()
It retruns the total weeks in week year.
8 int getWeekYear()
It returns the week year represented by current Calendar.
9 void add(int field, int amount)
It adds the specified amount of time to the given calendar field.
10 boolean after (Object when)
It returns true if the time represented by the Calendar is after the time represented by
when Object.
11 boolean before(Object when)
It returns true if the time represented by the Calendar is before the time represented
by when Object.
12 void clear(int field)
It sets the given calendar field value and the time value of this Calendar undefined.
13 Object clone()
It retruns the copy of the current object.
14 int compareTo(Calendar anotherCalendar)
It compares and retruns the time values (millisecond offsets) between two calendar
object.
15 void complete()
It sets any unset fields in the calendar fields.
16 void computeFields()
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 72
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link] Methods with Description
.
It converts the current millisecond time value time to calendar field values in
fields[].
17 void computeTime()
It converts the current calendar field values in fields[] to the millisecond time value
time.
18 boolean equals(Object object)
It returns true if both invoking object and argumented object are equal.
19 int getActualMaximum(int field)
It returns the Maximum possible value of the specified calendar field.
20 int getActualMinimum(int field)
It returns the Minimum possible value of the specified calendar field.
21 Set getAvailableCalendarTypes()
It returns a string set of all available calendar type supported by Java Runtime
Environment.
22 Locale[] getAvailableLocales()
It returns an array of all locales available in java runtime environment.
23 String getDisplayName(int field, int style, Locale locale)
It returns the String representation of the specified calendar field value in a given
style, and local.
24 Map getDisplayNames(int field, int style, Locale locale)
It returns Map representation of the given calendar field value in a given style and
local.
25 int getGreatestMinimum(int field)
It returns the highest minimum value of the specified Calendar field.
26 int getLeastMaximum(int field)
It returns the highest maximum value of the specified Calendar field.
27 int getMaximum(int field)
It returns the maximum value of the specified calendar field.
28 int getMinimalDaysInFirstWeek()
It returns required minimum days in integer form.
29 int getMinimum(int field)
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 73
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link] Methods with Description
.
It returns the minimum value of specified calendar field.
30 long getTimeInMillis()
It returns the current time in millisecond.
31 int hashCode()
It returns the hash code of the invoking object.
32 int internalGet(int field)
It returns the value of the given calendar field.
33 boolean isLenient()
It returns true if the interpretation mode of this calendar is lenient; false otherwise.
34 boolean isSet(int field)
If not set then it returns false otherwise true.
35 boolean isWeekDateSupported()
It returns true if the calendar supports week date. The default value is false.
36 void roll(int field, boolean up)
It increase or decrease the specified calendar field by one unit without affecting the
other field
37 void set(int field, int value)
It sets the specified calendar field by the specified value.
38 void setFirstDayOfWeek(int value)
It sets the first day of the week.
39 void setMinimalDaysInFirstWeek(int value)
It sets the minimal days required in the first week.
40 void setTime(Date date)
It sets the Time of current calendar object.
41 void setTimeInMillis(long millis)
It sets the current time in millisecond.
42 void setTimeZone(TimeZone value)
It sets the TimeZone with passed TimeZone value.
43 void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek)
It sets the current date with specified integer value.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 74
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link] Methods with Description
.
44 Instant toInstant()
It converts the current object to an instant.
45 String toString()
It returns a string representation of the current object.
Example:
import [Link].*;
public class CalendarClassExample {
public static void main(String[] args) {
Calendar cal = [Link]();
[Link]("Current date and time : \n=>" + cal);
[Link]("Current Calendar type : " + [Link]());
[Link]("Current date and time : \n=>" + [Link]());
[Link]("Current date time zone : \n=>" + [Link]());
[Link]("Calendar filed 1 (year): " + [Link](1));
[Link]("Calendar day in integer form: " + [Link]());
[Link]("Calendar weeks in a year: " + [Link]());
[Link]("Time in milliseconds: " + [Link]());
[Link]("Available Calendar types: " + [Link]());
[Link]("Calendar hash code: " + [Link]());
[Link]("Is calendar supports week date? " + [Link]());
[Link]("Calendar string representation: " + [Link]());
}
}
Random class in java
The Random is a built-in class in java used to generate a stream of pseudo-random numbers
in java programming. The Random class is available inside the [Link] package.
The Random class implements Serializable, Cloneable and Comparable interface.
● The Random class is a part of [Link] package.
● The Random class provides several methods to generate random numbers of type
integer, double, long, float etc.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 75
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
● The Random class is thread-safe.
● Random number generation algorithm works on the seed value. If not provided, seed
value is created from system nano time.
The Random class in java has the following constructors.
[Link]. Constructor with Description
1 Random()
It creates a new random number generator.
2 Random(long seedValue)
It creates a new random number generator using a single long seedValue.
The Random class in java has the following methods.
[Link] Methods with Description
.
1 int next(int bits)
It generates the next pseudo-random number.
2 Boolean nextBoolean()
It generates the next uniformly distributed pseudo-random boolean value.
3 double nextDouble()
It generates the next pseudo-random double number between 0.0 and 1.0.
4 void nextBytes(byte[] bytes)
It places the generated random bytes into an user-supplied byte array.
5 float nextFloat()
It generates the next pseudo-random float number between 0.0 and 1.0..
6 int nextInt()
It generates the next pseudo-random int number.
7 int nextInt(int n)
It generates the next pseudo-random integer value between zero and n.
8 long nextLong()
It generates the next pseudo-random, uniformly distributed long value.
9 double nextGaussian()
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 76
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link] Methods with Description
.
It generates the next pseudo-random Gaussian distributed double number with mean
0.0 and standard deviation 1.0.
10 void setSeed(long seedValue)
It sets the seed of the random number generator using a single long seedValue.
11 DoubleStream doubles()
It returns a stream of pseudo-random double values, each conforming between 0.0
and 1.0.
12 DoubleStream doubles(double start, double end)
It retruns an unlimited stream of pseudo-random double values, each conforming to
the given start and end.
13 DoubleStream doubles(long streamSize)
It returns a stream producing the pseudo-random double values for the given
streamSize number, each between 0.0 and 1.0.
14 DoubleStream doubles(long streamSize, double start, double end)
It returns a stream producing the given streamSizenumber of pseudo-random double
values, each conforming to the given start and end.
15 IntStream ints()
It returns a stream of pseudo-random integer values.
16 IntStream ints(int start, int end)
It retruns an unlimited stream of pseudo-random integer values, each conforming to
the given start and end.
17 IntStream ints(long streamSize)
It returns a stream producing the pseudo-random integer values for the given
streamSize number.
18 IntStream ints(long streamSize, int start, int end)
It returns a stream producing the given streamSizenumber of pseudo-random integer
values, each conforming to the given start and end.
19 LongStream longs()
It returns a stream of pseudo-random long values.
20 LongStream longs(long start, long end)
It retruns an unlimited stream of pseudo-random long values, each conforming to
the given start and end.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 77
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link] Methods with Description
.
21 LongStream longs(long streamSize)
It returns a stream producing the pseudo-random long values for the given
streamSize number.
22 LongStream longs(long streamSize, long start, long end)
It returns a stream producing the given streamSizenumber of pseudo-random long
values, each conforming to the given start and end.
An example program to illustrate methods of Random class.
Example:
import [Link];
public class RandomClassExample {
public static void main(String[] args) {
Random rand = new Random();
[Link]("Integer random number - " + [Link]());
[Link]("Integer random number from 0 to 100 - " +
[Link](100));
[Link]("Boolean random value - " + [Link]());
[Link]("Double random number - " + [Link]());
[Link]("Float random number - " + [Link]());
[Link]("Long random number - " + [Link]());
[Link]("Gaussian random number - " + [Link]());
Formatter class in java
The Formatter is a built-in class in java used for layout justification and alignment, common
formats for numeric, string, and date/time data, and locale-specific output in java
programming. The Formatter class is defined as final class inside the [Link] package.
The Formatter class implements Cloneable and Flushable interface.
The Formatter class in java has the following constructors.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 78
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link]. Constructor with Description
1 Formatter()
It creates a new formatter.
2 Formatter(Appendable a)
It creates a new formatter with the specified destination.
3 Formatter(Appendable a, Locale l)
It creates a new formatter with the specified destination and locale.
4 Formatter(File file)
It creates a new formatter with the specified file.
5 Formatter(File file, String charset)
It creates a new formatter with the specified file and charset.
6 Formatter(File file, String charset, Locale l)
It creates a new formatter with the specified file, charset, and locale.
7 Formatter(Locale l)
It creates a new formatter with the specified locale.
8 Formatter(OutputStream os)
It creates a new formatter with the specified output stream.
9 Formatter(OutputStream os, String charset)
It creates a new formatter with the specified output stream and charset.
10 Formatter(OutputStream os, String charset, Locale l)
It creates a new formatter with the specified output stream, charset, and locale.
11 Formatter(PrintStream ps)
It creates a new formatter with the specified print stream.
12 Formatter(String fileName)
It creates a new formatter with the specified file name.
13 Formatter(String fileName, String charset)
It creates a new formatter with the specified file name and charset.
14 Formatter(String fileName, String charset, Locale l)
It creates a new formatter with the specified file name, charset, and locale.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 79
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
Example:
import [Link].*;
public class FormatterClassExample {
public static void main(String[] args) {
Formatter formatter=new Formatter();
[Link]("%2$5s %1$5s %3$5s", "Smart", "BTech", "Class");
[Link](formatter);
formatter = new Formatter();
[Link]([Link],"%.5f", -1325.789);
[Link](formatter);
String name = "Java";
formatter = new Formatter();
[Link]([Link],"Hello %s !", name);
[Link]("" + formatter + " " + [Link]());
formatter = new Formatter();
[Link]("%.4f", 123.1234567);
[Link]("Decimal floating-point notation to 4 places: " + formatter);
formatter = new Formatter();
[Link]("%010d", 88);
[Link]("value in 10 digits: " + formatter);
}
}
Scanner class in java
The Scanner is a built-in class in java used for read the input from the user in java
programming. The Scanner class is defined inside the [Link] package.
The Scanner class implements Iterator interface.
Note:
The Scanner object breaks its input into tokens using a delimiter pattern, the default
delimiter is whitespace.
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 80
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
The Scanner class in java has the following constructors.
[Link] Constructor with Description
.
1 Scanner(InputStream source)
It creates a new Scanner that produces values read from the specified input stream.
2 Scanner(InputStream source, String charsetName)
It creates a new Scanner that produces values read from the specified input stream.
3 Scanner(File source)
It creates a new Scanner that produces values scanned from the specified file.
4 Scanner(File source, String charsetName)
It creates a new Scanner that produces values scanned from the specified file.
5 Scanner(String source)
It creates a new Scanner that produces values scanned from the specified string.
6 Scanner(Readable source)
It creates a new Scanner that produces values scanned from the specified source.
7 Scanner(ReadableByteChannel source)
It creates a new Scanner that produces values scanned from the specified channel.
8 Scanner(ReadableByteChannel source, String charsetName)
It creates a new Scanner that produces values scanned from the specified channel.
The Scanner class in java has the following methods.
[Link] Methods with Description
.
1 String next()
It reads the next complete token from the invoking scanner.
2 String next(Pattern pattern)
It reads the next token if it matches the specified pattern.
3 String next(String pattern)
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 81
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
[Link] Methods with Description
.
It reads the next token if it matches the pattern constructed from the specified string.
4 boolean nextBoolean()
It reads a boolean value from the user.
5 byte nextByte()
It reads a byte value from the user.
6 double nextDouble()
It reads a double value from the user.
7 float nextFloat()
It reads a floating-point value from the user.
8 int nextInt()
It reads an integer value from the user.
9 long nextLong()
It reads a long value from the user.
10 short nextShort()
It reads a short value from the user.
11 String nextLine()
It reads a string value from the user.
12 boolean hasNext()
It returns true if the invoking scanner has another token in its input.
13 void remove()
It is used when remove operation is not supported by this implementation of
Iterator.
14 void close()
It closes the invoking scanner.
Example:
import [Link];
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 82
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND
SCIENCE
(Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad)
KARMNAGAR - 505481
II [Link] II- Semester Java Programming (R18) 2021-22
public class ScannerClassExample {
public static void main(String[] args) {
Scanner read = new Scanner([Link]); // Input stream is used
[Link]("Enter any name: ");
String name = [Link]();
[Link]("Enter your age in years: ");
int age = [Link]();
[Link]("Enter your salary: ");
double salary = [Link]();
[Link]("Enter any message: ");
read = new Scanner([Link]);
String msg = [Link]();
[Link]("\n------------------------------------------");
[Link]("Hello, " + name);
[Link]("You are " + age + " years old.");
[Link]("You are earning Rs." + salary + " per month.");
[Link]("Words from " + name + " - " + msg);
}
}
Prepared by [Link] Teja, Assistant Professor, CSE Dept Page 83