Java Unit4 Jntu r18 Oops Using Java
Java Unit4 Jntu r18 Oops Using Java
UNIT-IV
THE COLLECTIONS FRAMEWORK
The Collections Framework (java.util)- 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
WHAT IS COLLECTION?
A Collection is a group of individual objects represented as a single unit.
WHAT IS FRAMEWORK?
A Framework provides ready-made architecture and represents a group of classes and interface .
WHAT IS COLLECTION FRAMEWORK?
Collection framework is implemented in java.util package.
Collection framework provides a set of interfaces and classes to implement various data structures
and algorithms.
Collection classes in java used to manage the data very efficiently like inserting, deleting, updating,
retrieving, sorting the data etc.
It is one of the standardized mechanisms which allow us to group multiple values either of same
types or different type or both the types in a single variable with dynamic size in nature. This single
variable is known as collection framework variable.
BENEFITS OF COLLECTIONS FRAMEWORK IN JAVA
I. Reusability: Java Collections Framework provides common classes and utility methods than can be
used with different types of collections. This promotes the reusability of the code. A developer does not
have to re-invent the wheel by writing the same method again.
II. Quality: Using Java Collection Framework improves the program quality, since the code is already
tested and used by thousands of developers.
III. Speed: Most of programmers report that their development speed increased since they can focus on
core logic and use the generic collections provided by Java framework.
IV. Maintenance: Since most of the Java Collections framework code is open source and API documents
is widely available, it is easy to maintain the code written with the help of Java Collections framework.
One developer can easily pick the code of previous developer.
HIERARCHY OF COLLECTION FRAMEWORK
The java.util package contains all the classes and interfaces for the Collection framework.
In the above image, blue part refers to the different interfaces and the green part defines the class.
COLLECTION INTERFACE
The Collection interface is the root interface of the collections framework hierarchy.
The Collection interface is available inside the java.util package.
The Collection interface extends Iterable interface.
Java does not provide direct implementations of the Collection interface but provides
implementations of its subinterfaces like List, Set, and Queue.
METHODS OF COLLECTION INTERFACE
1. boolean add(element obj) : This method appends the specified element to the end of the
ArrayList. If the element is added successfully then the preceding method returns true.
2. int size() : This method returns the number of elements present in the ArrayList.
3. element remove ( int position ) : This method removes the element at the specified position in the
ArrayList.
4. addAll() : adds all the elements of a collection to another collection
5. iterator() : returns an iterator to access elements of the collection
6. removeAll() : removes all the elements of the specified collection from the collection
7. clear() : removes all the elements of the collection
COLLECTION INTERFACE TYPES
Collection Interface is divided into three types of interfaces.
1. List Interface
2. Queue Interface
3. Set Interface
1. LIST INTERFACE
The List interface is a child interface of the Collection interface. The List interface is available inside
the java.util package.
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.
LIST INTERFACE IMPLEMENTATION CLASSES
1. Array List
2. Linked List
3. Stack
4. Vector
3
THE COLLECTION CLASSES
ARRAYLIST CLASS
ArrayList is part of Java’s collection framework and implements List interface.
An ArrayList is like an array.
ArrayList can grow in memory dynamically. It means that when we store elements into the ArrayList,
depending on the number of elements, the memory is dynamically allotted and re-allotted to
accommodate all the elements.
ArrayList allows duplicate and null values.
ArrayList is an ordered collection. It maintains the insertion order of the elements.
ARRAYLIST CLASS METHODS
boolean add (element obj) : This method adds an element to the arraylist. It returns true if the
element is added successfully.
void add (int position, element obj) : This method inserts the specified element at the specified
position in the Array List.
boolean addAll(element obj) : This method adds each element of the given element at the end of
the Array List, It returns True if element is added successfully, and returns false if it is not.
boolean addAll(int position, element obj): This methods add each element of the Specific
element type at index given in the argument. It returns True if element is successfully added, and
returns false if not.
int size() : This method returns the number of elements present in the list.
boolean contains( Object obj ) : This method returns true if the calling Array list object has the
specific element present as given in the argument list, otherwise it returns false.
int indexOf(Object obj ) : This method returns the index of the element given in the Array list
starting from first position.Otherwise it will return -1, if that element is not present in the Array list.
int lastIndexOf(Object obj ) : This method returns the index of the element given in the Array list
starting from last position. Otherwise it will return -1, if that element is not present in the Array
list.
element remove ( int position ) : This method removes an element at the specified position in
the Array list.
boolean remove(Object o): This method deletes the first occurrence of given element in
argument list from the Array list.
void clear() :This method removes all the elements from the Array list.
EXAMPLE
import java.util.*;
class ArrayListDemo
{
public static void main(String args[])
{
ArrayList<String> alist=new ArrayList<String>();
System.out.println("Initial list of elements: "+alist);
alist.add("Hi");
alist.add("I");
alist.add("Love");
alist.add("java");
alist.add("Hi");
System.out.println("After invoking add method: "+ alist);
alist.add(1,"Element");
System.out.println("After invoking add() method: "+alist);
ArrayList<String> alist1=new ArrayList<String>();
alist1.add("I");
alist1.add("Love");
alist1.add("Android");
System.out.println("After invoking add method: "+ alist1);
alist.addAll(alist1);
System.out.println("After invoking addAll method: "+ alist);
alist.addAll(2, alist1);
System.out.println("After invoking addAll method: "+ alist);
System.out.println("ArrayList contains 'Android':" + alist.contains("Android"));
System.out.println("ArrayList contains 'c++':" + alist.contains("c++"));
System.out.println("Index for I :" + alist.indexOf("I"));
System.out.println("Index for Android :" + alist.indexOf("Android"));
System.out.println("Last Index for Hi: " + alist.lastIndexOf("Hi"));
System.out.println("Last Index for Android: " + alist.lastIndexOf("Android"));
System.out.println("Elements using Iterator :");
Iterator<String> it = alist.iterator();
System.out.print("Display the ArrayList1: ");
while(it.hasNext())
{
System.out.print(" "+it.next());
}
System.out.println("Element to be removed:" + alist.remove(2));
System.out.println("ArrayList:" + alist);
System.out.println("Hi is in the list:" + alist.remove("Hi"));
System.out.println("ArrayList:" + alist);
System.out.println("Object to be replaced:" + alist.set(3, "Android"));
System.out.println("Array List:" + alist);
System.out.println("Array List size:" + alist.size());
}
}
LINKEDLIST CLASS
Linked List class uses a doubly linked list.
A linked List contains a group of elements in the form of nodes. Each node will have three fields.
Previous - stores an address of the previous element in the list. It is null for the first element
Next - stores an address of the next element in the list. It is null for the last element
Data - stores the actual data
Properties of Linked List class
The underlying data structure is Double Linked List.
LinkedList class can contain duplicate elements..
LinkedList class maintains insertion order.
Heterogeneous objects are allowed.
In LinkedList class Insertion of NULL values are allowed.
LinkedList class is non synchronized.
Linked List implements Serializable and Clonable interfaces but not Random Acess Interface.
Linked List class, manipulation is fast because no shifting needs to occur.
LINKEDLIST CLASS METHODS
boolean add (element obj) : This method adds an element to the linked list. It returns true if
the element is added successfully.
void add (int position, element obj) : This method inserts the specified element at the
specified position in the Linked List.
boolean addAll(element obj) : This method adds each element of the given collection at the end of
the Linked List, It returns True if collection is added successfully, and returns false if it is not.
boolean addAll(int position, element obj): This methods add each element of the Specific
collection type at index given in the argument. It returns True if collection is successfully added,
and returns false if not.
int size() : This method returns the number of elements present in the list.
void addFirst(element obj) : This method adds the first element from the linked list
void addLast(element obj) : This method adds the specified element to the end of the linked list.
boolean contains( Object obj ) : This method returns true if the calling linked list object has the
specific element present as given in the argument list, otherwise it returns false.
int indexOf(Object obj ) : This method returns the index of the element given in the linked list
starting from first position.Otherwise it will return -1, if that element is not present in the linked
list.
int lastIndexOf(Object obj ) : This method returns the index of the element given in the linked list
starting from last position. Otherwise it will return -1, if that element is not present in the linked
list.
element remove ( int position ) : This method removes an element at the specified position in
the linked list.
boolean remove(Object o): This method deletes the first occurrence of given element in
argument list from the linked list.
element removeFirst() : This method removes the first element from the linked list and returns it.
element removeLast() : This method removes the last element from the linked list and returns it.
void clear() :This method removes all the elements from the linked list.
element set (int position, element obj) : This method replaces the content at index given with the
element given in argument list.
element get (int position ) : This method returns the element at the specified position in
the linked list.
element getFirst() : This method returns the first element from the list.
element getLast() : This method returns the last element from the list.
EXAMPLE
import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
LinkedList<String> llist=new
LinkedList<String>(); System.out.println("Initial
list of elements: "+llist); llist.add("Hi");
llist.add("I");
llist.add("se");
llist.add("java");
llist.add("Hi");
System.out.println("After invoking add method: "+ llist);
llist.add(1,"Element");
System.out.println("After invoking add(int index, E element) method: "+llist);
LinkedList<String> llist1=new LinkedList<String>();
llist1.add("I");
llist1.add("se");
llist1.add("Android");
System.out.println("After invoking add method: "+ llist1);
llist.addAll(llist1);
System.out.println("After invoking addAll method: "+ llist);
llist.addAll(2, llist1);
System.out.println("After invoking addAll method: "+ llist);
llist.addFirst("First");
System.out.println("After invoking addFirst method: "+ llist);
llist.addLast("Last");
System.out.println("After invoking addLast method: "+ llist);
System.out.println("List contains 'Android':" + llist.contains("Android"));
System.out.println("List contains 'java':" + llist.contains("java"));
System.out.println("Index for I :" + llist.indexOf("I"));
System.out.println("Index for Android :" + llist.indexOf("Android"));
System.out.println("Last Index for Hi: " + llist.lastIndexOf("Hi"));
System.out.println("Last Index for Android: " + llist.lastIndexOf("Android"));
System.out.println("Elements using ListIterator :");
ListIterator lit=llist.listIterator ();
System.out.println("In Forward Direction :");
while(lit.hasNext())
{
System.out.println(lit.next());
}
System.out.println("In Backward Direction :");
while(lit.hasPrevious())
{
System.out.println(lit.previous());
}
System.out.println("Element to be removed:" + llist.remove(2));
System.out.println("LinkedList:" + llist);
System.out.println("Hi is in the list:" + llist.remove("Hi"));
System.out.println("LinkedList:" + llist);
llist.removeFirst();
System.out.println("After invoking removeFirst() method: "+llist);
llist.removeLast();
System.out.println("After invoking removeLast() method: "+llist);
System.out.println("Object to be replaced:" + llist.set(3, "Android"));
System.out.println("Linked List:" + llist);
System.out.println("linked List size:" + llist.size());
System.out.println("First Element from the
List:"+llist.getFirst()); System.out.println("Last Element from the
List:"+llist.getLast());
}
}
VECTOR CLASS
Vector class is part of Java’s collection framework and implements List interface.
Vector Class is similar to ArrayList.
Vector class can grow in memory dynamically. It means that when we store elements into the
Vector, depending on the number of elements, the memory is dynamically allotted and re-allotted to
accommodate all the elements.
Vector Class allows duplicate and null values.
Vector is synchronized. it means even if several threads act on Vector object simultaneously,
the results will be reliable.
Vector increases its size every time by doubling it. ( 100 PERCENT )
Note: Vector contains many legacy methods that are not part of collection framework
VECTOR METHODS IN JAVA
Vector contains many legacy methods that are not part of collection framework .
1. boolean add (element obj) : This method adds an element to the vector. It returns true if
the element is added successfully.
2. void add (int position, element obj) : This method inserts the specified element at the
specified position in the vector.
3. boolean addAll(element obj) : This method adds each element of the given element at the end of
the vector, It returns True if collection is added successfully, and returns false if it is not.
4. boolean addAll(int position, element obj): This methods add each element of the Specific
element type at index given in the argument. It returns True if element is successfully added,
and returns false if not.
5. int size() : This method returns the number of elements present in the list.
6. void addElement(Element obj) : This method adds the specified element at the end of the vector
also increasing its size by 1.
7. boolean contains( Object obj ) : This method returns true if the calling vector object has the
specific element present as given in the argument list, otherwise it returns false.
8. int indexOf(Object obj ) : This method returns the index of the element given in the vector
starting from first position.Otherwise it will return -1, if that element is not present in the vector.
9. int lastIndexOf(Object obj ) : This method returns the index of the element given in the vector
starting from last position. Otherwise it will return -1, if that element is not present in the
vector.
10. Object elementAt(int index): This method gives specific element at index mentioned in
the argument.
11. Enumeration elements(): This method returns an object of Enumeration class that can be used
for traversing over elements of vector.
12. Object firstElement() : This method returns the first element at index 0.
13. Object lastElement() : This method returns the last element of the vector
14. boolean isEmpty() : This method checks weather vector is empty or not .
15. element remove ( int position ) : This method removes an element at the specified position in the
linked list.
16. boolean remove(Object o): This method deletes the first occurrence of given element in
argument list from the linked list.
17. boolean removeAll(Collection c): This method removes all the elements of specified
collection form the vector.
18. void clear() :This method removes all the elements from the Vector.
19. element get (int position ) : This method retrieves an element at specified position of the vector.
EXAMPLE
import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
Vector<Integer> v = new Vector<Integer>();
v.add(3);
v.add(5);
v.add(4);
v.add(1);
v.add(2);
v.add(8);
v.add(8);
System.out.println("Values in Vector Object :" +v);
v.add(1,10);
v.addElement(2);
System.out.println("Values in Vector Object :" +v);
Vector<Integer> v1 = new Vector<Integer>();
v1.add(8);
v1.add(9);
System.out.println("Values in Vector Object :" +v1);
v.addAll(v1);
System.out.println("Values in Vector Object :" +v);
v.addAll(2,v1);
System.out.println("Values in Vector Object :" +v);
System.out.println("vector object contains elemnent 4?" +v.contains(4));
System.out.println("vector object contains elemnent 10?" +v.contains(100));
Enumeration e=v.elements();
System.out.println("Data in enum object :");
while (e.hasMoreElements())
{
System.out.println("value: " + e.nextElement());
}
System.out.println("Testing two vector objects: " +v.equals(v1));
System.out.println("value at first index :" +v.firstElement());
System.out.println("Last element of vector object is : "+v.lastElement());
System.out.println("value at index 2: " +v.get(2));
System.out.println("Index of element 8 is : " +v.indexOf(8));
System.out.println("Index of element 8 is : " +v.lastIndexOf(8));
System.out.println("Is vector object empty: " +v.isEmpty());
System.out.println("removed element at index 2 : " +v.remove(2));
v.removeAll(v1);
System.out.println("Values in vector :" +v);
System.out.println("Size of the vector is : " +v.size());
System.out.println("Element at position 2 : " +v.elementAt(2) );
v1.clear();
System.out.println("Values in vector1 :" +v1);
}
}
STACK CLASS
A stack represents a group of elements stored in LIFO (Last In First Out) principle.
Stack is a linear data structure in which the insertion and deletion operations are performed at only
one end.
In a stack, adding and removing of elements are performed at a single position which is known as
"top".
That means, a new element is added at top of the stack and an element is removed from the top of
the stack.
How to create a Stack Class Object
If we want to create a stack, first, import the java.util package and create an object of the Stack class.
Syntax: Stack s = new Stack();
[ or ]
Stack<data type > s = new Stack<data type > ();
METHODS OF THE STACK CLASS
element push(element obj) : This method pushes an element obj onto the top of the stack and
returns that element.
element pop() : This method pops the top most element from the stack and returns it.
element peek() : This method returns the top most element from the stack.
boolean empty() : This method tests whether the stack is empty or not. If the stack is empty then
true is returned otherwise false.
int search(Object obj) : This method returns the position of an element from the top of the stack. If
the element is not found in the stack then it returns -1.
EXAMPLE
import java.util.*;
class MyClass
{
public static void main (String[] args)
{
Stack<Integer> even = new Stack<>();
s.push(0);
s.push(2);
s.push(4);
s.push(6);
s.push(8);
s.push(10);
s.push(12);
s.push(14);
s.push(16);
System.out.println("Print Stack before pop:"+s);
System.out.println("pop => " + s.pop());
System.out.println("pop => " + s.pop());
System.out.println("pop => " + s.pop());
System.out.println("Print Stack after pop:"+s);
System.out.println("Number on top of the stack is => " + s.peek());
System.out.println("Is stack empty? Ans:" + s.empty());
System.out.println("Position of 8 from the top is " + s.search(8));
System.out.println("Position of 20 from the top is " + s.search(20));
}
}
2. QUEUE INTERFACE
The Queue interface is a child interface of the Collection interface. The Queue
interface is available inside the java.util package.
The Queue interface extends Collection interface.
The Queue interface allows duplicate elements.
The Queue interface preserves the order of insertion.
METHODS OF QUEUE
The Queue interface includes all the methods of the Collection interface. It is because Collection is the
super interface of Queue.
add(): The add() operation is used to insert new element into the queue. If it performs insert
operation successfully, it returns “true” value. Otherwise it throws java.lang.IllegalStateException.
offer(): The offer() operation is used to insert new element into the queue. If it performs insert
operation successfully, it returns “true” value. Otherwise it returns “false” value.
element(): The element() operation is used to retrieve an element from the head of the queue,
without removing it. If it performs examine operation successfully, it returns the head element of
the queue. Otherwise it throws java.util.NoSuchElementException.
peek(): The peek() operation is used to retrieve an element from the head of the queue, without
removing it. If it performs examine operation successfully, it returns the head element of the queue.
Otherwise it returns null value.
poll(): The poll() operation is used to delete an element from the head of the queue. If it performs
delete operation successfully, it returns the head element of the queue. Otherwise it returns “null”
value.
remove(): The remove() operation is used to delete an element from the head of the queue. If it
performs delete operation successfully, it returns the head element of the queue. Otherwise it
throws java.util.NoSuchElementException.
size(): This method returns the count of the element available in the queue.
Queue interface is implemented by the classes
PriorityQueue
LinkedList
PRIORITYQUEUE CLASS
PriorityQueue is a child class of Queue 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 class is used to create a dynamic queue of elements that can grow as needed.
The PriorityQueue allows to store duplicate data values, but not null values.
The PriorityQueue maintains the order of insertion.
Element at the head of priority queue is least element.
Element at the tail of priority queue is greatest element.
Removal of elements always takes place from the front end (head) of queue.
PriorityQueue is not synchronized. That means it is not thread-safe. For working in a multithreading
environment.
PRIORITYQUEUE METHOS
add(): The add() operation is used to insert new element into the PriorityQueue. If it performs
insert operation successfully, it returns “true” value. Otherwise it throws
java.lang.IllegalStateException.
offer(): The offer() operation is used to insert new element into the PriorityQueue. If it performs
insert operation successfully, it returns “true” value. Otherwise it returns “false” value.
element(): The element() operation is used to retrieve an element from the head of the
PriorityQueue, without removing it. If it performs examine operation successfully, it returns
the head element of the PriorityQueue. Otherwise it throws java.util.NoSuchElementException.
peek(): The peek() operation is used to retrieve an element from the head of the PriorityQueue,
without removing it. If it performs examine operation successfully, it returns the head element
of the queue. Otherwise it returns null value.
poll(): The poll() operation is used to delete an element from the head of the PriorityQueue. If it
performs delete operation successfully, it returns the head element of the PriorityQueue. Otherwise
it returns “null” value.
remove(): The remove() operation is used to delete an element from the head of the PriorityQueue.
If it performs delete operation successfully, it returns the head element of the PriorityQueue.
Otherwise it throws java.util.NoSuchElementException.
size(): This method returns the count of the element available in the PriorityQueue.
void clear() : This method remove all the elements from the PriorityQueue.
boolean isEmpty( ) : This method checks whether the PriorityQueue is empty or not. If it is
empty this method will return true, else it will return false.
EXAMPLE
import java.util.*;
class PriorityQueueDemo
{
public static void main(String[] args)
{
PriorityQueue q = new PriorityQueue();
q.add(20);
q.add(40);
q.add(60);
q.add(80);
q.add(100);
q.offer(200);
q.offer(180);
q.offer(120);
System.out.println("\nTotal item count in PriorityQueue: " + q.size());
System.out.println("\nItems in PriorityQueue: " + q);
System.out.println("\nHead item of the PriorityQueue: " + q.element());
q.remove();
System.out.println("\nAvailable item in PriorityQueue: " + q);
System.out.println("\nHead item of the PriorityQueue: " + q.peek());
q.poll();
System.out.println("\nAvailable item in PriorityQueue: " + q);
System.out.println("\nHead item of the PriorityQueue: " + q.contains(80));
System.out.println("The PriorityQueue elements through iterator:");
Iterator it = q.iterator();
while(it.hasNext())
{
System.out.println( " "+it.next());
}
q.clear();
System.out.println("The PriorityQueue elements are:"+q);
System.out.println("\nHead item of the PriorityQueue: " + q.peek());
System.out.println("\nHead item of the PriorityQueue: " + q.poll());
System.out.println("\nHead item of the PriorityQueue: " + q.element());
System.out.println("\nHead item of the PriorityQueue: " + q.remove());
}
}
DEQUE INTERFACE
The Deque interface is a child interface of the Queue interface. The Deque interface is available
inside the java.util package.
The Deque interface extends Queue interface.
The Deque interface allows duplicate elements.
The Deque interface preserves the order of insertion.
DEQUE INTERFACE IMPLEMENTATION CLASSES
ArrayDeque
ARRAYDEQUE CLASS
ArrayDeque in Java is a concrete class that creates a dynamic array (resizable array) to store its
elements from both sides of the queue.
It provides a resizable-array implementation of deque interface. Therefore, it is also known as array
double-ended queue or simply array deck.
Since ArrayDeque has no capacity restrictions, ArrayDeque is especially useful for implementing
stacks and queues whose sizes are not known in advance.
ArrayDeque class was added by Java 6 version that makes it a recent addition to the Java Collections
Framework. It is present in java.util.ArrayDeque package.
Array deque is not synchronized. That means it is not thread-safe. Multiple threads can access the
same ArrayDeque object at the same time.
Null elements are restricted in the ArrayDeque.
ArrayDeque class performs faster operations than Stack when used as a stack.
ArrayDeque class performs faster operations than LinkedList when used as a queue.
METHODS OF ARRAYDEQUE
add(): The add() operation is used to insert new element into the queue. If it performs insert
operation successfully, it returns “true” value. Otherwise it throws java.lang.IllegalStateException.
void addFirst(Object o): It inserts the specified element to the front of the deque.
void addLast(Object o): It inserts the specified element to the last of deque.
offer(): The offer() operation is used to insert new element into the queue. If it performs insert
operation successfully, it returns “true” value. Otherwise it returns “false” value.
boolean offerFirst(Object element): It inserts the specified element at the front of deque.
boolean offerLast(Object element): It inserts the specified element at the end of deque.
remove(): The remove() operation is used to delete an element from the head of the queue. If it
performs delete operation successfully, it returns the head element of the queue. Otherwise it
throws java.util.NoSuchElementException.
boolean removeFirst(): This method is used to retrieve and remove the first element from the
deque.
boolean removeLast(): This method is used to retrieve and remove the last element from the
deque.
poll(): The poll() operation is used to delete an element from the head of the queue. If it performs
delete operation successfully, it returns the head element of the queue. Otherwise it returns “null”
value.
Object pollFirst(): The pollFirst() method retrieves and removes the first element of deque. It
returns null element if the deque is empty.
Object pollLast(): The pollLast() method retrieves and removes the last element of deque. It
returns null element if the deque is empty.
Object getFirst(): This method is used to retrieve the first element of deque. It does not remove
element.
Object getLast(): This method is used to retrieve the last element of deque. It does not remove
element.
boolean isEmpty(): The isEmpty() method returns true if deque has no elements.
peek(): The peek() operation is used to retrieve an element from the head of the queue, without
removing it. If it performs examine operation successfully, it returns the head element of the queue.
Otherwise it returns null value.
Object peekFirst(): The peekFirst() method retrieves the first element from the head of deque but
does not remove it. It returns null element if the deque is empty.
Object peekLast(): The peekLast() method retrieves the last element from deque but does not
remove it. It returns null element if the deque is empty.
element(): The element() operation is used to retrieve an element from the head of the queue,
without removing it. If it performs examine operation successfully, it returns the head element of
the queue. Otherwise it throws java.util.NoSuchElementException.
void clear(): This method is used to remove all elements from deque.
boolean contains(Object element): It returns true if the deque contains the specified element.
EXAMPLE
import java.util.*;
class ArrayDequeDemo
{
public static void main(String[] args)
{
ArrayDeque ad = new ArrayDeque();
ad.add(20);
ad.add(40);
ad.add(60);
ad.add(80);
ad.addFirst(7);
ad.offer(100);
ad.offerFirst(35);
ad.offer(200);
ad.offer(180);
ad.offerLast(45);
ad.offerFirst(55);
ad.offerLast(95);
ad.addLast(79);
System.out.println("\nTotal item count in ArrayDeque: " + ad.size());
System.out.println("\nItems in ArrayDeque: " + ad);
System.out.println("Deleted Element: " + ad.remove());
System.out.println("Deleted First Element: " + ad.removeFirst());
System.out.println("Deleted Last Element: " + ad.removeLast());
System.out.println("\nItems in ArrayDeque: " + ad);
System.out.println("Deleted poll Element: " + ad.poll());
System.out.println("Deleted pollFirst Element: " + ad.pollFirst());
System.out.println("Deleted pollLast Element: " + ad.pollLast());
System.out.println("First Element is(using peekFirst()): " + ad.peekFirst());
System.out.println("Last Element is(using PeekLast()): " +ad.peekLast());
System.out.println("First element is: " + ad.getFirst());
System.out.println("Last element is: " + ad.getLast()); System.out.println("\
nItems in ArrayDeque: " + ad);
Iterator i = ad.iterator();
System.out.printf("The Elements are :");
while(i.hasNext())
{
System.out.print(i.next()+" ");
}
}
}
3. SET INTERFACE
The Set interface is a child interface of Collection interface.
SET INTERFACE IMPLEMENTATION CLASSES
1. HashSet
2. LinkedHashSet
HASHSET CLASS
HashSet class Duplicate elements are not allowed. If we trying to insert duplicate elements, we
won’t get any compiletime or runtime errors. add() method simply returns false.
Insertion order is not preserved and all objects will be inserted based on hash-code objects.
Heterogeneous objects are allowed.
In Hashset Insertion of NULL values are allowed.
HashSet implements Serializable and Clonable interfaces but not RandomAcess.
HashSet is the best Choice, if our frequent operation is Search operation.
HashSet class is non synchronized.
The HashSet class extends AbstractSet class which implements Set interface. The Set interface inherits
Collection and Iterable interfaces in hierarchical order.
METHODS OF HASHSET CLASS
boolean add(element obj) : This method adds an element to the HashSetet. It returns true if
the element is added successfully.
boolean addAll() : inserts all the elements of the specified collection to the HashSet.
int size() : This method returns the number of elements in the HashSet.
boolean remove(Object o) : This method removes first Occurrence of the element specified in the
argument list from the hashset , and returns true if that element is removed, or false if it is not.
removeAll() : removes all the elements from the HashSet.
void clear() : This method remove all the elements from the set
boolean isEmpty( ) : This method checks whether the hashset is empty or not. If it is empty
this method will return true, else it will return false.
boolean contains( Object obj ) : This method returns true if the calling hashset object contains
the specific element as given in the argument list, otherwise it returns false
Iterator iterator() : This methods returns the iterator, so that we can traverse over the elements
of the hashset.
EXAMPLE
import java.util.*;
class HashSetDemo
{
public static void main(String args[])
{
HashSet hs=new HashSet();
hs.add(80);
hs.add(20);
hs.add(90);
hs.add(45);
hs.add(30);
hs.add(10);
hs.add(20);
System.out.println("Display the HashSet1 :"+hs);
HashSet hs1=new HashSet();
hs1.add(100);
hs1.add(70);
hs1.add(65);
hs1.add(40);
hs1.add(30);
hs1.add(15);
System.out.println("Display the HashSet2 :"+hs1);
hs.addAll(hs1);
System.out.println("Update Display the HashSet1 :"+hs);
System.out.println("Size of the HashSet1 :"+hs.size());
hs1.remove(70);
System.out.println("Updated HashSet2: " +
hs1); hs.removeAll(hs1);
System.out.println("Updated HashSet1: " + hs);
Iterator it= hs.iterator();
System.out.print("HashSet using Iterator: ");
while(it.hasNext())
22
{
System.out.print(" "+it.next());
}
System.out.println("Hash Set Contains '10'" :+hs.contains(10));
HashSet hs2=new HashSet();
hs2= (HashSet) hs.clone();
System.out.println("values in HashSet clone object "+ hs2);
System.out.println("Is the set empty: "+hs.isEmpty());
hs2.clear();
System.out.println("values in HashSet object After using Clear method"+hs2 );
}
}
SORTEDSET INTERFACE
The Sorted Set interface is a child interface of the Set interface. The Sorted Set interface is
available inside the java.util package.
The SortedSet interface extends Set interface.
The SortedSet interface does not allow duplicate elements.
The SortedSet interface organise the elements based on the ascending order.
SORTEDSET INTERFACE IMPLEMENTATION CLASSES
TreeSet
TREE SET CLASS
TreeSet class is implements Set Interface.
TreeSet class is available in java.util package.
In TreeSet all the values are stored in their natural order, like all integer values are stored
in ascending order and strings are stored according to Dictionary values.
TreeSet is best choice for storing large amount of data.
TreeSet class retrieval and access time is very fast, which makes data to be found in no time.
Tree Set do not allow null values.
TreeSet class do not allow duplicate elements to be stored.
TreeSet class is non synchronized.
METHODS OF TREESET
boolean add(Object o): This methods adds element in the object, which will automatically
stores all the elements in increasing order.
boolean addAll(Collection c): This method adds all the elements of one object to another.
Object ceiling(Object o):This method retrieves the least element which is greater than or equal
to the given element in the argument list, or null if there is no such element in the set.
void clear():This method removes all of the elements from this object.
boolean contains(Object o): This method returns true if specified element is present in the
given set.
Iterator descendingIterator(): This method retrieves an object of Iterator class which is set in
decreasing order of the elements in the Set.
NavigableSet descendingSet():This method returns a all the elements in Decreasing order.
Object first():This method returns the lowest element in the Set.
Object floor(Object o): This method returns the greatest element which is less than or equal to the
given element in the argument list, or null if there is no such element.
SortedSet headSet(Object toElement): This method returns group of elements that are strictly
less than toElement.
NavigableSet headSet(Object toElement, boolean inclusive): This method Returns group of
elements that are less than (or equal to, if inclusive is true) toElement as mentioned in the argument
list.
Object higher(Object o):This method returns the least element in the TreeSet which is strictly
greater than the given element in the argument of this method, or it will return null if there is no
such element.
boolean isEmpty():This method returns true if the set is empty or false if set contains any element.
Object last(): This method returns the highest element present in the treeset.
Object pollFirst(): This method returns as well as removes the lowest element, or it will returns
null if this tree set is empty.
Object pollLast():This method retrieves as well as removes the highest element, or it will returns
null if this set is empty.
boolean remove(Object o):This method removes the element specified from the treeset, if it is
present.
Integer size():This method gives the size of treeset.
EXAMPLE
import java.util.*;
class TreSetMethodsDemo
{
public static void main(String args[])
{
TreeSet <Integer>ts1 = new
TreeSet<Integer>(); TreeSet <Integer>ts2 =
new TreeSet<Integer>(); TreeSet <Integer>ts3
= new TreeSet<Integer>(); ts1.add(3);
ts1.add(5);
ts1.add(5);
ts1.add(1);
ts1.add(2);
ts2.add(9);
ts2.add(11);
ts2.add(4);
ts2.add(8);
ts2.add(7);
System.out.println("Values in TreeSet object 1: " +ts1);
System.out.println("Values in TreeSet object 2: " +ts2);
ts1.addAll(ts2);
System.out.println("Values in TreeSet object 1: " +ts1);
System.out.println("Ceiling value of '6' is:" +ts1.ceiling(6));
System.out.println("Ceiling value of '11' is:" +ts1.ceiling(10));
ts2.clear();
System.out.println("Values in TreeSet object 2:" +ts2);
System.out.println("Tree Set Object contains element '0' : "+ts1.contains(0));
System.out.println("Values in TreeSet object 1 are :”);
Iterator itr = ts1.descendingIterator();
while (itr.hasNext())
{
System.out.println(itr.next() + " ");
}
ts2= (TreeSet<Integer>) ts1.descendingSet();
System.out.println("Values in Reverse order: " +ts2);
System.out.println("Lowest element in the tree set is : " +ts1.first());
System.out.println("Floor value of '6' : " +ts1.floor(6));
System.out.println("Floor value of '10' : " +ts1.floor(10));
25
ts2=(TreeSet<Integer>) ts1.headSet(4);
System.out.println("Values in Tress Set Head Set : " + ts2 );
ts2=(TreeSet<Integer>) ts1.headSet(4, true);
ts3=(TreeSet<Integer>) ts1.headSet(4, false);
System.out.println("Values in Tress Set Head Set in object 2: " + ts2 );
System.out.println("Values in Tress Set Head Set in object 3: " + ts3 );
System.out.println("highest value than 4 : " + ts1.higher(4) );
System.out.println("highest value than 5 : " + ts1.higher(5) );
System.out.println("Is Tree Set empty ?: " +ts1.isEmpty());
System.out.println("Last elememt in Tree Set object is: "+ts1.last());
System.out.println("Greatest Element Less than 5: "+ts1.lower(5));
System.out.println("Greatest Element Less than 5: "+ts1.lower(1));
System.out.println("Removed Element using Pollfirst method :"+ts1.pollFirst());
System.out.println("Values in Tree Set object: " + ts1);
System.out.println("Removed Element using PollLast method "+ts1.pollLast());
System.out.println("Values in Tree Set object: " + ts1);
System.out.println("Is element '1' removed ? " +ts1.remove(5));
System.out.println("Values in Tree Set Object: " +ts1);
System.out.println("Size of the Tree Set Object : " +ts1.size());
}
}
Every key is associated with at most one value, as shown in the following figure.
Once the value is stored in a dictionary object, we can retrieve it by using the key.
Dictionary class Methods
1. 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.
2. int size( ) : It returns the total number of elements in the dictionary.
3. Object get(Object key) : It returns the value associated with given key; Returns null if the key does
not exist.
4. boolean isEmpty( ) : It returns true if dictionary has no elements otherwise returns false.
5. Object remove (Object key) : It returns the value associated with given key and removes the
same; Returns null if the key does not exist.
6. Enumeration keys ( ): Returns an enumeration of the keys contained in the dictionary.
7. Enumeration elements ( ): Returns an enumeration of the elements contained in the dictionary.
EXAMPLE
import java.util.*;
class DictionaryDemo
{
public static void main(String args[])
{
Dictionary d=new Dictionary ();
d.put(101,"Apple");
d.put(102,"Mango");
d.put(103,"Lemon");
d.put(104,"Orange");
d.put(105,"Banana");
d.put(106,"Graps");
d.put(107,"Cat");
d.put(108,"Dog");
d.put(109,"Elephant");
d.put(1010,"Monkey");
System.out.println("Dictionary values are:"+d);
System.out.println("Size of the Dictionary:"+d.size());
System.out.println("\nValue at key = 105 :"+d.get(105));
System.out.println("\nIs the dictionary empty? : "+d.isEmpty());
System.out.println("The removed value is: "+d.remove(106));
System.out.println("\nDictionary keys are: \n");
Enumeration e = d.keys();
while(e.hasMoreElements())
{
System.out.println(e.nextElement());
}
System.out.println("\nDictionary Values are: \n");
Enumeration e1 = d.elements();
while(e1.hasMoreElements())
{
System.out.println(e1.nextElement());
}
}
}
2.HASH TABLE :
1. The underlying data structure for Java Hashtable is a hash table only.
2. Insertion order is not preserved. That means it does not maintain insertion order.
3. Duplicate keys are not allowed but values can be duplicated.
4. Heterogeneous objects are allowed for both keys and values.
5. Null is not allowed for both key and values. If we attempt to store null key or value, we will get a
RuntimeException named NullPointerException.
6. Java Hashtable implements Serializable and Cloneable interfaces but not random access.
7. Every method present in Hashtable is synchronized. Hence, Hashtable object is thread-safe.
8. Hashtable is the best choice if our frequent operation is a retrieval (search) operation.
9. Since Hashtable is synchronized, its operations are slower as compared to HashMap in java.
Hierarchy of Java Hashtable
Hashtable class extends Dictionary class and implements Map, Cloneable, and Serializable interfaces.
HashTable Methods in Java
10. put(Object key, Object value): This method is used To insert the elements or an entry in a
Hashmap.
11. void putAll(Map map): This method is used to insert all the entries of the specified map to
another map.
12. putIfAbsent(K key, V value): This method adds the specified value associated with the
specified key in the map only if it is not already specified.
13. get(Object key): This method is used to retrieve the value associated with a key. Its return type
is Object.
14. Collection values(): This method returns a collection view containing all of the values in the map.
15. remove(Object key): This method is used to delete an entry for the specified key.
16. boolean remove(Object key, Object value): This method removes the specified value
associated with specific key from the map.
17. replace(K key, V value): This method is used to replace the specified value for a specified key.
18. int size(): This method returns the number of entries in the map.
19. boolean isEmpty(): This method is used to check whether the map is empty or not. If there are
no key-value mapping present in the hash map then it returns true, else false.
20. void clear(): It is used to remove entries from the specified map.
21. Set entrySet(): It is used to return a set view containing all of the key/value pairs in this map.
22. Set keySet(): This method is used to retrieve a set view of the keys in this map.
23. boolean containsKey(Object key) : This method tests whether the specified key k is available
in the Treemap.
24. boolean containsValue(Object key) : This method tests whether the specified value is available
in the Treemap.
25. firstKey(): It is used to retrieve key of first entry in the sorted order from the map. If the tree map
is empty, it will throw NoSuchElementException.
26. lastKey(): It is used to retrieve key of last entry in the sorted order from the map. If the tree map
is empty, it will throw NoSuchElementException.
27. Enumeration<V> elements(): This method returns an enumeration of the values in this hashtable.
28. Enumeration<K> keys(): This method returns an enumeration of the keys in this hashtable.
29. boolean equals(Object o): It is used to compare the specified Object for equality, as per the
definition in the Map interface.
EXAMPLE
import java.util.*;
class HashtableDemo
{
public static void main(String[] args)
{
Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
System.out.println("Is hash table empty: " + ht.isEmpty());
ht.put(1, "One");
ht.put(2, "Two");
ht.put(3, "Three");
ht.put(4, "Four");
ht.put(5, "Five");
ht.put(6, "Six");
System.out.println("Displaying entries in hash table: " +ht);
System.out.println("Size of hash table: " +ht.size());
System.out.println("Removed entry: " +ht.remove(6));
System.out.println("Updated entries in hash table: " +ht);
System.out.println("Getting the value of 4: " +ht.get(4));
System.out.println("Getting the value of 2: " +ht.get(2));
System.out.println("Is key 1 in hash table: " +ht.containsKey(1));
System.out.println("Is key 3 in hash table: " +ht.containsValue("Three"));
System.out.println("Iterating keys of hash table:");
Iterator<Integer> itr =
ht.keySet().iterator(); while(itr.hasNext())
{
System.out.println(itr.next());
}
System.out.println("\n");
System.out.println("Iterating values of hash table:");
Iterator<String> itrValue = ht.values().iterator();
while(itrValue.hasNext())
{
System.out.println(itrValue.next());
}
}
}
3. PROPERTIES CLASS
Properties in Java is a class that is a child class (subclass) of Hashtable.
It is mainly used to maintain the list of values in which key and value pairs are represented in the
form of strings.
In other words, keys and values in Properties objects should be of type String.
Properties class extends Hashtable class that extends Dictionary class. It implements Map,
Serializable, and Cloneable interfaces.
METHODS OF PROPERTIES CLASS
1. String getProperties(String key): This method returns the value associated with key. If the key is
neither in the list nor in the default property list, it will return null object.
2. String getProperty(String key, String defaultValue): This method returns the value associated
with key. If the key is neither in the list nor in the default property list, it will return defaultValue.
3. void list(PrintStream streamOut): This method prints the property list streamOut to the specified
output stream.
4. void list(PrintWriter streamOut): This method prints this property list streamOut to the specified
output stream.
5. void load(InputStream inStream): This method loads (reads) a property list (key and element
pairs) from the InputStream.
6. void load(Reader reader): This method loads a property list (key and element pairs) from the input
character stream in a simple line-oriented format.
7. void loadFromXML(InputStream in): This method loads all of the properties represented by the
XML document on the specified InputStream into the properties table.
8. Enumeration propertyNames(): It returns an enumeration of all the keys in this property list,
including distinct keys in the default property list.
9. Object setProperties(String key, String value): It returns value associated with key. It returns null
if value associated with key does not exist.
EXAMPLE
db.properties
1. user=system
2. password=oracle
import java.util.*;
import java.io.*;
public class Test
{
public static void main(String[] args)throws Exception
{
FileReader reader=new
FileReader("db.properties"); Properties p=new
Properties();
p.load(reader);
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}
MORE UTILITY CLASSES
STRING TOKENIZER
1. The StringTokenizer class is available inside the java.util package.
2. StringTokenizer class is useful to break a string into pieces called ‘Tokens’.
3. These Tokens are then stored in the StringTokenizer object from where they can be retrived.
METHODS OF THE STRINGTOKENIZER CLASS
1. int countTokens() : This method counts and returns the number of tokens available in
a StringTokenizer object.
2. boolean hasMoreTokens () : This method tests if there are more tokens available in
the StringTokenizer object or not. If next token is there then it returns true.
3. String nextToken (): This method returns the next token from the StringTokenizer.
EXAMPLE
import java.util.*;
class StringTokenizerDemo
{
public static void main(String args[])
{
System.out.println("StringTokenizer Constructor 1 - ");
StringTokenizer st1 = new StringTokenizer("Hello Geeks How are you", " ");
while (st1.hasMoreTokens())
{
System.out.println(st1.nextToken());
}
}
}
DATE CLASS
The class Date represents a specific instant in time, with millisecond precision.
The Date class of java.util package implements Serializable, Cloneable and Comparable interface.
It provides constructors and methods to deal with date and time with java.
Note : The last 4 constructors of the Date class are Deprecated.
METHODS OF DATE CLASS
1. int getMinutes() : This method returns the minutes part of the current date.
2. int getHours() : This method returns the hours part of the current date.
3. int getDate() : This method returns the date part of the current date.
4. int getYear() : This method returns the year part of the current date. ( It gives Currentyear-1900)
5. int getSeconds() : This method returns the seconds part of the current date.
6. long getTime() : Returns the number of milliseconds since January 1, 1970, 00:00:00
GMT represented by this Date object.
EXAMPLE
import java.util.*;
class DateDemo
{
public static void main(String[] args)
{
Date d1 = new Date();
System.out.println("Current date is " + d1);
Date d2 = new Date(2323223232L);
System.out.println("Date represented is "+ d2
); System.out.println(d1.getHours());
System.out.println(d1.getMinutes());
System.out.println(d1.getSeconds());
System.out.println(d1.getMonth());
System.out.println(d1.getDate());
System.out.println(d1.getDay());
System.out.println(d1.getYear());
System.out.println(d1.getTime());
}
}
CALENDAR CLASS
Calendar class in Java is an abstract super class that is designed to support different kinds
of calendar systems. It is used to know system data and time information.
Java Calendar class provides some specific functionality that is common to most calendar
systems and makes that functionality available to the subclasses.
The subclasses of Calendar class are used to calculate calendar related information (such as
second, minute, hour, day of month, month, year, and so on) of a particular calendar system.
HOW TO CREATE A CALENDAR IN JAVA?
To create an object of Calendar class in java, we need to call getInstance() method. Since this method is
static in nature so we call it using Calendar class name like this:
Syntax : Calendar cl = Calendar.getInstance();
This Calendar object stores the current system date and time by default.
METHODS OF CALENDAR CLASS
1. abstract void add(int field, int amount): This method is used to add or subtract the
specified amount of time to the given calendar field, based on the calendar’s rules.
2. boolean after(Object calendarObj): This method returns true if the invoking calendar
object contains a date that is after (later) than specified calendarObj. Otherwise, it returns false.
3. boolean before(Object calendarObj): This method returns true if the invoking calendar
object contains a date that is before (earlier) than specified calendarObj. Otherwise, it returns
false.
4. final void clear(): It sets zeros all time components in the invoking calendar object.
5. final void clear(int field): It sets zeros the specified time components in the invoking
calendar object.
6. int get(int calendarField): It returns the value of the given calendar field.
7. final Date getTime(): It returns a Date object that is equal to the time of invoking object.
EXAMPLE
import java.util.*;
class CalendarDemo
{
public static void main(String[] args)
{
Calendar cl = Calendar.getInstance();
System.out.print("Current System Date: ");
int dd = cl.get(Calendar.DATE);
int mm = cl.get(Calendar.MONTH);
int yy = cl.get(Calendar.YEAR);
System.out.println(dd+ "-" +mm+ "-" +yy);
System.out.print("Current System Time: ");
int hr = cl.get(Calendar.HOUR);
int min = cl.get(Calendar.MINUTE);
int sec = cl.get(Calendar.SECOND);
int secMilli = cl.get(Calendar.MILLISECOND);
System.out.println(hr+ ":"+min+ ":"+ sec+ ":"+secMilli);
System.out.println("At present Date and Time: " +cl.getTime());
int maximum = cl.getMaximum(Calendar.DAY_OF_WEEK);
System.out.println("Maximum number of days in week: " + maximum);
maximum = cl.getMaximum(Calendar.WEEK_OF_YEAR);
System.out.println("Maximum number of weeks in year: " + maximum);
int minimum = cl.getMinimum(Calendar.DAY_OF_WEEK);
System.out.println("Minimum number of days in week: " + minimum);
minimum = cl.getMinimum(Calendar.WEEK_OF_YEAR);
System.out.println("Minimum number of weeks in year: " + minimum);
cl.add(Calendar.DATE, -20);
System.out.println("20 Days ago, date and time information: " + cl.getTime());
cl.add(Calendar.MONTH, 5);
System.out.println("5 months later, date and time information: " + cl.getTime());
cl.add(Calendar.YEAR, 5);
System.out.println("5 years later, date and time information: " + cl.getTime());
}
}
SCANNER CLASS
The Scanner class implements Iterator interface.
The Scanner class provides the easiest way to read input in a Java program.
The System.in parameter is used to take input from the standard input. It works just like
taking inputs from the keyboard.
We have then used the nextLine() method of the Scanner class to read a line of text from the user.
METHODS OF SCANNER CLASS
nextBoolean() : This method is used to Reads a boolean value from the
user nextByte() : This method is used to Reads a byte value from
the user nextDouble() : This method is used to Reads a double value from
the user nextFloat() : This method is used to Reads a float value from
the user nextInt() : This method is used to Reads a int value from
the user nextLine() : This method is used to Reads a String value
from the user nextLong() : This method is used to Reads a long value from
the user nextShort() : This method is used to Reads a short
value from the user next() : This method is used to reads a word from the
user
close() : This method is used to is used to closes this scanner.
EXAMPLE
import java.util.*;
class ScannerExample
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
BITSET CLASS
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 java.util 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 default value of the BitSet is boolean false with a representation as 0 (off).
BitSet uses 1 bit of memory per each boolean value.
METHODS OF BITSET CLASS
1. void and(BitSet bitSet) : It performs AND operation on the contents of the invoking BitSet
object with those specified by bitSet.
2. void andNot(BitSet bitSet) : For each 1 bit in bitSet, the corresponding bit in the invoking BitSet
is cleared.
3. void or(BitSet bitSet) : It performs OR operation on the contents of the invoking BitSet object with
those specified by bitSet.
4. void xor(BitSet bitSet) : It performs XOR operation on the contents of the invoking BitSet
object with those specified by bitSet.
5. int cardinality( ) : It returns the number of bits set to true in the invoking BitSet.
6. void clear( ) : It sets all the bits to zeros of the invoking BitSet.
7. void clear(int index) : It set the bit specified by given index to zero.
8. void clear(int startIndex, int endIndex) : It sets all the bits from specified startIndex to
endIndex to zero.
9. boolean equals(Object bitSet) : It retruns true if both invoking and argumented BitSets are
equal, otherwise returns false.
10. boolean get(int index) : It retruns the present state of the bit at given index in the invoking BitSet.
11. boolean intersects(BitSet bitSet) : It returns true if at least one pair of corresponding bits within
the invoking object and bitSet are 1.
12. boolean isEmpty( ) : It returns true if all bits in the invoking object are zero, otherwise
returns false.
13. int size( ) : It returns the total number of bits in the invoking BitSet.
14. int length( ) : It returns the total number of bits in the invoking BitSet.
15. void set(int index) : It sets the bit specified by index.
EXAMPLE
import java.util.*;
class BitSetClassExample
{
public static void main(String[] args)
{
BitSet bSet1 = new BitSet();
BitSet bSet2 = new BitSet(16);
bSet1.set(10);
bSet1.set(5);
bSet1.set(0);
bSet1.set(7);
bSet1.set(20);
bSet2.set(1);
bSet2.set(15);
bSet2.set(20);
bSet2.set(77);
bSet2.set(50);
System.out.println("BitSet_1 => " + bSet1);
System.out.println("BitSet_2 => " + bSet2);
bSet1.and(bSet2);
System.out.println("BitSet_1 after and with bSet_2 => " + bSet1);
bSet1.andNot(bSet2);
System.out.println("BitSet_1 after andNot with bSet_2 => " + bSet1);
System.out.println("Length of the bSet_2 => " + bSet2.length());
System.out.println("Size of the bSet_2 => " + bSet2.size());
System.out.println("Bit at index 2 in bSet_2 => " + bSet2.get(2));
bSet2.set(2);
System.out.println("Bit at index 2 after set in bSet_2 => " + bSet2.get(2));
}
}
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 java.util package.
The Formatter class implements Cloneable and Flushable interface.
The Formatter class in java has the following methods.
void flush()
3
It flushes the invoking formatter.
Appendable out()
4 It returns the destination for the output.
Locale locale()
5
It returns the locale set by the construction of the invoking formatter.
String toString()
6
It converts the invoking object to string.
IOException ioException()
7 It returns the IOException last thrown by the invoking formatter's Appendable.
void close()
8
It closes the invoking formatter.
EXAMPLE
import java.util.*;
public class FormatterClassExample
{
public static void main(String[] args)
{
Formatter formatter=new Formatter();
formatter.format("%2$5s %1$5s %3$5s", "Smart", "BTech", "Class");
System.out.println(formatter);
formatter = new Formatter();
formatter.format(Locale.FRANCE,"%.5f", -1325.789);
System.out.println(formatter);
String name = "Java";
formatter = new Formatter();
formatter.format(Locale.US,"Hello %s !", name);
System.out.println("" + formatter + " " + formatter.locale());
formatter = new Formatter();
formatter.format("%.4f", 123.1234567);
System.out.println("Decimal floating-point notation to 4 places: " + formatter);
formatter = new Formatter();
formatter.format("%010d", 88);
System.out.println("value in 10 digits: " + formatter);
}
}
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 java.util package.
The Random class implements Serializable, Cloneable and Comparable interface.
The Random class is a part of java.util package.
The Random class provides several methods to generate random numbers of type integer, double,
long, float etc.
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 methods.
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.
S.No. Methods with Description
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.
EXAMPLE
import java.util.Random;
public class RandomClassExample
{
public static void main(String[] args)
{
Random rand = new Random();
System.out.println("Integer random number - " + rand.nextInt());
System.out.println("Integer random number from 0 to 100 - " + rand.nextInt(100));
System.out.println("Boolean random value - " + rand.nextBoolean());
System.out.println("Double random number - " + rand.nextDouble());
System.out.println("Float random number - " + rand.nextFloat());
System.out.println("Long random number - " + rand.nextLong());
}
}