Professional Documents
Culture Documents
CS405PC JP Unit-4
CS405PC JP Unit-4
Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
Constructor Description
Ravi
Vijay
Ravi
Ajay
ArrayList and Vector both implements List interface and maintains insertion order.
But there are many differences between ArrayList and Vector classes that are given below.
ArrayList Vector
2)ArrayList increments 50% of Vector increments 100% means doubles the array
current array size if number of size if total number of element exceeds than its
element exceeds from its capacity. capacity.
5) ArrayLis tuses Iterator interface Vector uses Enumeration interface to traverse the
to traverse the elements. elements. But it can use Iterator also.
Let's see a simple example of java Vector class that uses Enumeration interface.
1. import java.util.*;
2. class TestVector1{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();//creating vector
5. v.add("umesh");//method of Collection
6. v.addElement("irfan");//method of Vector
7. v.addElement("kumar");
8. //traversing elements using Enumeration
Output:
umesh
irfan
kumar
Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class and implements List and Deque interfaces.
In the case of a doubly linked list, we can add or remove elements from both sides.
44.7M
993
OOPs Concepts in Java
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output: Ravi
Vijay
Ravi
Ajay
Constructor Description
Hashtable(int size) It is used to accept an integer parameter and creates a hash table
that has an initial size specified by integer value size.
Hashtable(int size, float It is used to create a hash table that has an initial size specified by
fillRatio) size and a fill ratio specified by fillRatio.
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and
implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order.
47.1M
Department of CSE Page 10 of 70
938
Exception Handling in Java - Javatpoint
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable
Constructors of Java TreeSet class
Constructor Description
TreeSet(Collection<? extends It is used to build a new tree set that contains the
E> c) elements of the collection c.
import java.util.*;
class TreeSet1{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ajay
Ravi
Vijay
Department of CSE Page 11 of 70
Java TreeSet Example 2:
Let's see an example of traversing elements in descending order.
import java.util.*;
class TreeSet2{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ajay");
System.out.println("Traversing element through Iterator in descending order");
Iterator i=set.descendingIterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Output:
PriorityQueue class:
The PriorityQueue class provides the facility of using queue. But it does not orders the elements in FIFO
manner. It inherits AbstractQueue class.
Output:head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
ArrayDeque Hierarchy
The hierarchy of ArrayDeque class is given in the figure displayed at the right side of the page.
45.2M
906
C++ vs Java
ArrayDeque class declaration
Let's see the declaration for java.util.ArrayDeque class.
import java.util.*;
public class DequeExample {
public static void main(String[] args) {
Deque<String> deque=new ArrayDeque<String>();
deque.offer("arvind");
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
System.out.println("After offerFirst Traversal...");
for(String s:deque){
System.out.println(s);
}
//deque.poll();
//deque.pollFirst();//it is same as poll()
deque.pollLast();
System.out.println("After pollLast() Traversal...");
for(String s:deque){
System.out.println(s);
}
}
}
Output:
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class ArrayDequeExample {
public static void main(String[] args) {
Deque<Book> set=new ArrayDeque<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to Deque
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing ArrayDeque
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
o hasNext()
o next()
o remove()
o forEachRemaining()
The forEachRemaining() method was added in the Java 8. Let's discuss each method in detail.
boolean hasNext(): The method does not accept any parameter. It returns true if there are more elements left in
the iteration. If there are no more elements left, then it will return false.
If there are no more elements left in the iteration, then there is no need to call the next() method. In simple
words, we can say that the method is used to determine whether the next() method is to be called or not.
E next(): It is similar to hasNext() method. It also does not accept any parameter. It returns E, i.e., the next
element in the traversal. If the iteration or collection of objects has no more elements left to iterate, then it
throws the NoSuchElementException.
default void remove(): This method also does not require any parameters. There is no return type of this
method. The main function of this method is to remove the last element returned by the iterator traversing
through the underlying collection. The remove () method can be requested hardly once per the next () method
call. If the iterator does not support the remove operation, then it throws the UnSupportedOperationException.
It also throws the IllegalStateException if the next method is not yet called.
default void forEachRemaining(Consumer action): It is the only method of Java Iterator that takes a
parameter. It accepts action as a parameter. Action is nothing but that is to be performed. There is no return
type of the method. This method performs the particularized operation on all of the left components of the
collection until all the components are consumed or the action throws an exception. Exceptions thrown by
action are delivered to the caller. If the action is null, then it throws a NullPointerException.
Now it's time to execute a Java program to illustrate the advantage of the Java Iterator interface. The below
code produces an ArrayList of city names. Then we initialize an iterator applying the iterator () method of the
ArrayList. After that, the list is traversed to represent each element.
JavaIteratorExample.java
cityNames.add("Delhi");
cityNames.add("Mumbai");
cityNames.add("Kolkata");
cityNames.add("Chandigarh");
cityNames.add("Noida");
while (iterator.hasNext())
System.out.print(iterator.next() + " ");
System.out.println();
}
}
Output:
CityNames elements:
Delhi Mumbai Kolkata Chandigarh Noida
The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order. Here, you do not
have the option to skip any element because it does not work on an index basis. Moreover, you cannot traverse
the odd or even elements only.
But, it is recommended to use the Java for-each loop for traversing the elements of array and collection because
it makes the code readable.
Syntax
The syntax of Java for-each loop consists of data_type with the variable followed by a colon (:), then array or
collection.
The Java for-each loop traverses the array or collection until the last element. For each element, it stores the
element in the variable and executes the body of the for-each loop.
Output:
12
12
14
44
The map interface is present in java.util package represents a mapping between a key and a value. The Map
interface is not a subtype of the Collection interface. Therefore it behaves a bit differently from the rest of the
collection types. A map contains unique keys.
Geeks, the brainstormer should have been why and when to use Maps?
Maps are perfect to use for key-value association mapping such as dictionaries. The maps are used to perform
lookups by keys or when someone wants to retrieve and update elements by keys. Some common scenarios are
as follows:
A map of error codes and their descriptions.
A map of zip codes and cities.
A map of managers and employees. Each manager (key) is associated with a list of employees (value) he
manages.
A map of classes and students. Each class (key) is associated with a list of students (value).
Since Map is an interface, objects cannot be created of the type map. We always need a class that extends this
map in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict
the type of object that can be stored in the Map.
Syntax: Defining Type-safe Map
Map hm = new HashMap();
// Obj is the type of the object to be stored in Map
This method is used to check if a map is having any entry for key
isEmpty() and value pairs. If no mapping exists, then this returns true.
This method is used to copy all of the mappings from the specified
putAll(Map) map to this map.
This method is used to remove the mapping for a key from this map
remove(Object) if it is present in the map.
getOrDefault(Object key, V Returns the value to which the specified key is mapped, or
defaultValue) defaultValue if this map contains no mapping for the key.
import java.util.*;
// Main class
class GFG {
Map<String, Integer> hm
hm.entrySet()) {
// Printing keys
System.out.print(me.getKey() + ":");
System.out.println(me.getValue());
Output:
a:100
b:200
c:300
d:400
Classes that implement the Map interface are depicted in the below media and described later as follows:
Class 1: HashMap
HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface
of Java. It stores the data in (Key, Value) pairs. To access a value one must know its key. This class uses a
technique called Hashing. Hashing is a technique of converting a large String to a small String that represents
the same String. A shorter value helps in indexing and faster searches. Let’s see how to create a map object
using this class.
Example
Department of CSE Page 25 of 70
Java
import java.util.*;
// Main class
map.put("vishal", 10);
map.put("sachin", 30);
map.put("vaibhav", 20);
+ e.getValue());
Output
vaibhav 20
vishal 10
sachin 30
Class 2: LinkedHashMap
LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted
into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the
track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their
insertion order. Let’s see how to create a map object using this class.
Example
Java
import java.util.*;
// Main class
map.put("vishal", 10);
map.put("sachin", 30);
map.put("vaibhav", 20);
+ e.getValue());
Output:
vishal 10
sachin 30
vaibhav 20
Class 3: TreeMap
The TreeMap in Java is used to implement the Map interface and NavigableMap along with the Abstract Class.
The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation
time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-
value pairs. The storing order maintained by the treemap must be consistent with equals just like any other
sorted map, irrespective of the explicit comparators. Let’s see how to create a map object using this class.
Example
Java
import java.util.*;
// Main class
map.put("vishal", 10);
map.put("sachin", 30);
map.put("vaibhav", 20);
+ e.getValue());
Output:
sachin 30
vaibhav 20
vishal 10
A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of
comparing two objects of the same class. Following function compare obj1 with obj2.
Syntax:
public int compare(Object obj1, Object obj2):
Method 1: One obvious approach is to write our own sort() function using one of the standard algorithms. This
solution requires rewriting the whole sorting code for different criteria like Roll No. and Name.
Method 2: Using comparator interface- Comparator interface is used to order the objects of a user-defined
class. This interface is present in java.util package and contains 2 methods compare(Object obj1, Object obj2)
and equals(Object element). Using a comparator, we can sort the elements based on data members. For
instance, it may be on roll no, name, age, or anything else.
Method of Collections class for sorting List elements is used to sort the elements of List by the given
comparator.
public void sort(List list, ComparatorClass c)
To sort a given List, ComparatorClass must implement a Comparator interface.
Internally the Sort method does call Compare method of the classes it is sorting. To compare two elements, it
asks “Which is greater?” Compare method returns -1, 0, or 1 to say if it is less than, equal, or greater to the
other. It uses this result to then determine if they should be swapped for their sort.
Example
Java
// Comparator Interface
import java.io.*;
import java.lang.*;
import java.util.*;
// Class 1
class Student {
int rollno;
// Constructor
this.rollno = rollno;
this.name = name;
this.address = address;
// Class 2
// Method
// Class 3
// Method
return a.name.compareTo(b.name);
// Class 4
// Main class
class GFG {
System.out.println("Unsorted");
System.out.println(ar.get(i));
System.out.println("\nSorted by rollno");
System.out.println(ar.get(i));
System.out.println("\nSorted by name");
System.out.println(ar.get(i));
Output
Unsorted
111 Mayank london
131 Anshul nyc
121 Solanki jaipur
101 Aggarwal Hongkong
Sorted by rollno
101 Aggarwal Hongkong
111 Mayank london
121 Solanki jaipur
131 Anshul nyc
Sorted by name
101 Aggarwal Hongkong
131 Anshul nyc
111 Mayank london
121 Solanki jaipur
By changing the return value inside the compare method, you can sort in any order that you wish to, for
example: For descending order just change the positions of ‘a’ and ‘b’ in the above compare method.
Department of CSE Page 36 of 70
Sort collection by more than one field
In the previous example, we have discussed how to sort the list of objects on the basis of a single field using
Comparable and Comparator interface But, what if we have a requirement to sort ArrayList objects in
accordance with more than one field like firstly, sort according to the student name and secondly, sort
according to student age.
Example
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
// Class 1
class Student {
// Attributes of student
String Name;
int Age;
this.Name = Name;
this.Age = Age;
// Method
return "Customer{"
// Class 2
implements Comparator<Student> {
// Method 1
// To compare customers
@Override
Student customer2)
// Comparing customers
customer2.getName());
: NameCompare;
// Method 2
// to store Student
al.add(obj1);
al.add(obj2);
al.add(obj3);
al.add(obj4);
al.add(obj5);
al.add(obj6);
// Display message
System.out.println("Before Sorting:\n");
// remaining in List
System.out.println(custIterator.next());
Collections.sort(al,
new CustomerSortingComparator());
System.out.println("\n\nAfter Sorting:\n");
System.out.println(customer);
Output
Before Sorting:
Customer{Name=Ajay, Age=27}
After Sorting:
Customer{Name=Ajay, Age=22}
Customer{Name=Ajay, Age=27}
Customer{Name=Ajay, Age=29}
Customer{Name=Simran, Age=37}
Customer{Name=Sneha, Age=22}
Customer{Name=Sneha, Age=23}
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
All these algorithms are highly efficient and make coding very easy. It is better to use them than trying to re-
implement them.
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 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, 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.
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 according to c,
Comparator c) or -1 if value is not found.
int indexOfSubList(List list, List subList) Returns the index of the first match of subList in the list, or -1
if no match is found.
int lastIndexOfSubList(List list, List subList) Returns the index of the last match of subList in the list, or -1
if no match is found.
Object max(Collection c, Comparator comp) Returns the largest element from the collection c as
determined by Comparator comp.
Object min(Collection c, Comparator comp) Returns the smallest element from the collection 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, Object Replaces all occurrences of old with new in the list.
new)
ArrayList list(Enumeration enum) Returns an ArrayList that contains the elements of enum.
Example
import java.util.*;
Collections.sort(list);
System.out.println("List in ascending order => " + list);
Collections.reverse(list);
System.out.println("List in reverse order => " + list);
Collections.shuffle(list);
System.out.println("List after shuffle => " + list);
}
}
All the legacy classes are synchronized. The java.util package defines the following legacy classes:
1. HashTable
2. Stack
Vector Class
Vector is a special type of ArrayList that defines a dynamic array. ArrayList is not synchronized
while vector is synchronized. The vector class has several legacy methods that are not present in the collection
framework. Vector implements Iterable after the release of JDK 5 that defines the vector is fully compatible
with collections, and vector elements can be iterated by the for-each loop.
44.7M
993
OOPs Concepts in Java
1) Vector()
It is used when we want to create a default vector having the initial size of 10.
2) Vector(int size)
It is used to create a vector of specified capacity. It accepts two parameters size and increment parameters to
specify the initial capacity and the number of elements to allocate each time when a vector is resized for the
addition of objects.
4) Vector(Collection c)
It is used to create a vector with the same elements which are present in the collection. It accepts the collection
as a parameter.
VectorExample.java
import java.util.*;
public class VectorExample
{
public static void main(String[] args)
{
Vector<String> vec = new Vector<String>();
vec.add("Emma");
vec.add("Adele");
vec.add("Aria");
vec.add("Aidan");
vec.add("Adriana");
vec.add("Ally");
Enumeration<String> data = vec.elements();
while(data.hasMoreElements())
{
System.out.println(data.nextElement());
}
}
}
Output:
1) Hashtable()
2) Hashtable(int size)
It is used to create a HashTable of the specified size. It accepts size as a parameter to specify the initial size of
it.
It creates the Hashtable of the specified size and fillratio. It accepts two parameters, size (of type int) and
fillratio (of type float). The fillratio must be between 0.0 and 1.0. The fillratio parameter determines how full
the hash table can be before it is resized upward. It means when we enter more elements than its capacity or
size than the Hashtable is expended by multiplying its size with the fullratio.
It is used to create a Hashtable. The Hashtable is initialized with the elements present in m. The capacity of the
Hashtable is the twice the number elements present in m.
HashtableExample.java
import java.util.*;
class HashtableExample
{
public static void main(String args[])
{
Department of CSE Page 50 of 70
Hashtable<Integer,String> student = new Hashtable<Integer, String>();
student.put(new Integer(101), "Emma");
student.put(new Integer(102), "Adele");
student.put(new Integer(103), "Aria");
student.put(new Integer(104), "Ally");
Set dataset = student.entrySet();
Iterator iterate = dataset.iterator();
while(iterate.hasNext())
{
Map.Entry map=(Map.Entry)iterate.next();
System.out.println(map.getKey()+" "+map.getValue());
}
}
}
Output:
Properties Class
Properties class extends Hashtable class to maintain the list of values. The list has both the key and the value of
type string. The Property class has the following two constructors:
1) Properties()
2) Properties(Properties propdefault)
It is used to create the Properties object using the specified parameter of properties type for its default value.
The main difference between the Hashtable and Properties class is that in Hashtable, we cannot set a default
value so that we can use it when no value is associated with a certain key. But in the Properties class, we can
set the default value.
PropertiesExample.java
Department of CSE Page 51 of 70
import java.util.*;
public class PropertiesExample
{
public static void main(String[] args)
{
Properties prop_data = new Properties();
prop_data.put("India", "Movies.");
prop_data.put("United State", "Nobel Laureates and Getting Killed by Lawnmowers.");
prop_data.put("Pakistan", "Field Hockey.");
prop_data.put("China", "CO2 Emissions and Renewable Energy.");
prop_data.put("Sri Lanka", "Cinnamon.");
Set< ?> set_data = prop_data.keySet();
for(Object obj: set_data)
{
System.out.println(obj+" is famous for "+ prop_data.getProperty((String)obj));
}
}
}
Output:
Stack Class
Stack class extends Vector class, which follows the LIFO(LAST IN FIRST OUT) principal for its elements.
The stack implementation has only one default constructor, i.e., Stack().
1) Stack()
There are the following methods can be used with Stack class:
StackExample.java
import java.util.*;
class StackExample {
public static void main(String args[]) {
Stack stack = new Stack();
stack.push("Emma");
stack.push("Adele");
stack.push("Aria");
stack.push("Ally");
stack.push("Paul");
Enumeration enum1 = stack.elements();
while(enum1.hasMoreElements())
System.out.print(enum1.nextElement()+" ");
stack.pop();
stack.pop();
stack.pop();
System.out.println("\nAfter removing three elements from stack");
Enumeration enum2 = stack.elements();
while(enum2.hasMoreElements())
System.out.print(enum2.nextElement()+" ");
}
}
Output:
The Dictionary class operates much like Map and represents the key/value storage repository. The Dictionary
class is an abstract class that stores the data into the key/value pair. We can define the dictionary as a list of
key/value pairs.
1. The put(K key, V value) method is used to add a key-value pair to the dictionary.
2. The elements() method is used to get the value representation in the dictionary.
3. The get(Object key) method is used to get the value mapped with the argumented key in the dictionary.
4. The isEmpty() method is used to check whether the dictionary is empty or not.
5. The keys() method is used to get the key representation in the dictionary.
6. The remove(Object key) method removes the data from the dictionary.
7. The size() method is used to get the size of the dictionary.
DictionaryExample.java
import java.util.*;
public class DictionaryExample
{
public static void main(String[] args)
{
// Initializing Dictionary object
Dictionary student = new Hashtable();
}
}
Output:
In order to create a stack, we must import java.util.stack package and use the Stack() constructor of this class.
The below example creates an empty Stack.
Stack<E> stack = new Stack<E>();
Here E is the type of Object.
Example:
Java
Department of CSE Page 57 of 70
// Java code for stack implementation
import java.io.*;
import java.util.*;
class Test
stack.push(i);
System.out.println("Pop Operation:");
System.out.println(y);
if(pos == -1)
else
stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
Output:
Pop Operation:
4
3
2
1
0
Element on stack top: 4
Element is found at position: 3
Element not found
Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains
components that can be accessed using an integer index.
They are very similar to ArrayList, but Vector is synchronized and has some legacy methods that the
collection framework does not contain.
It also maintains an insertion order like an ArrayList. Still, it is rarely used in a non-thread environment as it
is synchronized, and due to this, it gives a poor performance in adding, searching, deleting, and updating its
elements.
The Iterators returned by the Vector class are fail-fast. In the case of concurrent modification, it fails and
throws the ConcurrentModificationException.
Syntax:
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
Here, E is the type of element.
It extends AbstractList and implements List interfaces.
It implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess interfaces.
The directly known subclass is Stack.
Important points regarding the Increment of vector capacity are as follows:
If the increment is specified, Vector will expand according to it in each allocation cycle. Still, if the increment
is not specified, then the vector’s capacity gets doubled in each allocation cycle. Vector defines three protected
data members:
int capacityIncreament: Contains the increment value.
int elementCount: Number of elements currently in vector stored in it.
Object elementData[]: Array that holds the vector is stored in it.
Department of CSE Page 61 of 70
Common Errors in the declaration of Vectors are as follows:
Vector throws an IllegalArgumentException if the InitialSize of the vector defined is negative.
If the specified collection is null, It throws NullPointerException.
Constructors
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to
break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc.
Each component of bit set contains at least one Boolean value. The contents of one BitSet may be changed by
other BitSet using logical AND, logical OR and logical exclusive OR operations. The index of bits of BitSet
class is represented by positive integers.
Each element of bits contains either true or false value. Initially, all bits of a set have the false value. A BitSet is
not safe for multithreaded use without using external synchronization.
Constructors :
import java.util.*;
Output:
Calendar class in Java is an abstract class that provides methods for converting date between a specific instant
in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object class and
implements the Comparable, Serializable, Cloneable interfaces.
As it is an Abstract class, so we cannot use a constructor to create an instance. Instead, we will have to use the
static method Calendar.getInstance() to instantiate and implement a sub-class.
Calendar.getInstance(): return a Calendar instance based on the current time in the default time zone with
the default locale.
Calendar.getInstance(TimeZone zone)
Calendar.getInstance(Locale aLocale)
Calendar.getInstance(TimeZone zone, Locale aLocale)
Java program to demonstrate getInstance() method:
import java.util.*;
Calendar c = Calendar.getInstance();
Output:
The Current Date is:Tue Aug 28 11:10:40 UTC 2018
// using java.util.Random;
import java.util.Random;
Output:
Random Integers: 547
Java formatter:
Java Formatter is a utility class that can make life simple when working with formatting stream output in Java.
It is built to operate similarly to the C/C++ printf function. It is used to format and output data to a specific
destination, such as a string or a file output stream. This article explores the class and illustrate some of its
utility in everyday programming in Java.
Using argument_index
"strengthen", "weakness");
System.out.println(f);
Regionalize Output
f.format(Locale.FRANCE,"%.5f", -1325.789);
System.out.println(f);
System.out.println(f2);
Regionalize Date
Calendar.getInstance());
System.out.println(f3);
Department of CSE Page 67 of 70
Formatter f4=new Formatter();
Calendar.getInstance());
System.out.println(f4);
System.out.println(f);
Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc.
and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input
method for scenarios where time is a constraint like in competitive programming.
To create an object of Scanner class, we usually pass the predefined object System.in, which represents the
standard input stream. We may pass an object of class File if we want to read input from a file.
To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read
a value of type short, we can use nextShort()
To read strings, we use nextLine().
To read a single character, we use next().charAt(0). next() function returns the next token/word in the input
as a string and charAt(0) function returns the first character in that string.
Let us look at the code snippet to read data of various data types.
import java.util.Scanner;
// String input
// Character input
System.out.println("Name: "+name);
System.out.println("Gender: "+gender);
System.out.println("CGPA: "+cgpa);
Input :
Geek
F
40
9876543210
9.9
Output :
Name: Geek
Gender: F
Age: 40
Mobile Number: 9876543210
CGPA: 9.9