0% found this document useful (0 votes)
333 views

Unit 4 Notes

The document discusses the Java Collection Framework which provides classes and interfaces for storing and manipulating collections of objects. It includes interfaces like Collection and Map, classes like ArrayList, LinkedList, HashSet, and TreeSet, and algorithms for searching, sorting, and manipulating collection objects. The key collection interfaces and classes are described along with their features and usage through examples.

Uploaded by

19BD1AO5O3 KMIT
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
333 views

Unit 4 Notes

The document discusses the Java Collection Framework which provides classes and interfaces for storing and manipulating collections of objects. It includes interfaces like Collection and Map, classes like ArrayList, LinkedList, HashSet, and TreeSet, and algorithms for searching, sorting, and manipulating collection objects. The key collection interfaces and classes are described along with their features and usage through examples.

Uploaded by

19BD1AO5O3 KMIT
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Dept.

of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

UNIT – IV
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

A Java collection framework provides an architecture to store and manipulate a group of objects.

A Java collection framework includes the following:

Interfaces

Classes

Algorithm

Interfaces: 

Interface in Java refers to the abstract data types. They allow Java collections to be manipulated
independently from the details of their representation. Also, they form a hierarchy in object-oriented
programming languages.

Classes: Classes in Java are the implementation of the collection interface. It basically refers to the data
structures that are used again and again.

Algorithm: Algorithm refers to the methods which are used to perform operations such as searching and
sorting, on objects that implement collection interfaces.

The Java collection framework provides the developers to access prepackaged data structures as well as
algorithms to manipulate data.

Collection Framework Hierarchy

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 1


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 2


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Java Collection

Iterator interface :

 Iterator is an interface that iterates the elements.

It is used to traverse the list and modify the elements. Iterator interface has three methods which are
mentioned below: 

public boolean hasNext() – This method returns true if the iterator has more elements.

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

public void remove() – This method removes the last elements returned by the iterator. 

Java Collections - List

A List is an ordered Collection of elements which may contain duplicates. It is an interface that extends
the Collection interface. 

1. ArrayList

2.LinkedList

3.Vectors

Array list: 

ArrayList is the implementation of List Interface where the elements can be dynamically added or
removed from the list.

Also, the size of the list is increased dynamically if the elements are added more than the initial size. 

Syntax:

ArrayList object = new ArrayList ();

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 3


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Method Description

 boolean add(Collection c)  Appends the specified element to the end of a list.

   

void add(int index, Object


 Inserts the specified element at the specified position.
element)

 void clear()  Removes all the elements from this list.

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

 Object clone()  Return a shallow copy of an ArrayList.

   

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 4


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

 Object[] toArray()  Returns an array containing all the elements in the list.

 void trimToSize()  Trims the capacity of this ArrayList instance to be the list’s current size.

Example:

import java.util.*;

class DemoArrayList{

public static void main(String args[]){

ArrayList al=new ArrayList(); // creating array list

al.add("kmit"); // adding elements

al.add("Kmec");

al.add("501");

al.add("kmit");

al.set(1,"NGIT");

System.out.println(al.size());

System.out.println(al.indexOf("501"));

al.remove("kmit");

System.out.println(al.lastIndexOf("kmit"));

Iterator itr=al.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Linked List

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 5


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Linked List: Linked List is a sequence of links which contains items. Each link contains a connection to
another link. 

Syntax: Linkedlist object = new Linkedlist();

Java Linked List class uses two types of Linked list to store the elements:

Singly Linked List

Doubly Linked List 

Singly Linked List: In a singly Linked list each node in this list stores the data of
the node and a pointer or reference to the next node in the list.

Linked List Example:


import java.util.*;
public class DemoLinked{
public static void main(String args[]){
LinkedList<String> list=new LinkedList<String>();
//Adding elements to the Linked list
list.add("Sree");
list.add("Ram");
list.add("Raj");
//Adding an element to the first position
list.addFirst("KMIT");
//Adding an element to the last position
list.addLast("Sita");
//Adding an element to the 3rd position
list.add(2, "NGIT");
list.removeFirst();

//Removing Last element


list.removeLast();
list.remove(1);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 6


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

//Iterating LinkedList
Iterator<String> iterator=list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}

Vector:
Vectors : Vectors are similar to arrays, where the elements of the vector object can
be accessed via an index into the vector.
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework

Syntax:
Vector object = new Vector(size,increment);

Hash Set

Java.util.HashSet class is a member of the Java collections framework which


inherits the AbstractSet class and implements the Set interface. It implicitly
implements a hashtable for creating and storing a collection of unique elements.
Hashtable is nothing but an instance of the HashMap class that uses a hashing

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 7


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

mechanism for storing the information within a HashSet.

Hashing is the process of converting the informational content into a unique value
that is more popularly known as hash code. This hashcode is then used for indexing
the data associated with the key. The entire process of transforming the
informational key into the hashcode is performed internally.

features:

A HashSet in Java does not allow duplicate values.


It can contain null values.
HashSet doesn’t follow the insertion order for storing the data rather it
makes use of the hashcode for indexing the values within.
It is non-synchronized which automatically makes it thread-unsafe.
HashSet class also implements Cloneable and Serializable interfaces.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 8


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

HashSet Hierarchy in Java

Constructors of java.util.HashSet Class


Constructor Description
HashSet () This is the default constructor of HashSet class
This constructor is used to initialize the initial capacity of
HashSet (int capacity) the hash set. The capacity can grow dynamically with the
addition of new elements
HashSet (int capacity, This constructor is used to initialize the initial capacity of
float loadCapacity) the hash set along with the load capacity
This constructor is used to initialize the hash set by using
HashSet (Collection c) the elements from Collection c

This method helps in adding a specified element into the


boolean add(Object obj)
HashSet only if it is not present
This method helps in removing all of the elements from
void clear()
HashSet
This method returns a shallow copy of the HashSet
Object clone()
instance rather than clones of the HashSet elements

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 9


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

boolean contains(Object This method returns true if the passed element is present
o) within the HashSet
boolean isEmpty() This method returns true in case the HashSet is empty
This method returns an iterator over the elements present
Iterator iterator()
in the HashSet
This method helps in removing the specified element from
boolean remove(Object o)
the HashSet if it is present
This method returns the total number of elements present
int size()
in the HashSet

Example:
import java.util.HashSet;
import java.util.*;

public class SampleHashSet {


public static void main(String[] args) {
// Creating a HashSet
Set<String> eduCourses = new HashSet<>();

// Adding new elements to the HashSet


eduCourses.add("Big Data");
eduCourses.add("Node.js");
eduCourses.add("Java");
eduCourses.add("Python");
eduCourses.add("Blockchain");
eduCourses.add("JavaScript");
eduCourses.add("Selenium");
eduCourses.add("AWS");
eduCourses.add("Machine Learning");
eduCourses.add("RPA");

// Adding duplicate elements will be ignored


eduCourses.add("Java");
eduCourses.add("RPA");

System.out.println(eduCourses);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 10


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

// Check if the HashSet contains an specific element


String myCourse = "Node.js";
if(eduCourses.contains(myCourse)) {
System.out.println(myCourse + " is in the courses list.");
} else {
System.out.println(myCourse + " is not in the courses list.");
}

// Sorting eduCourses using List


List<String> list = new ArrayList<String>(eduCourses);
Collections.sort(list);

// Printing the sorted elements of the HashSet


System.out.println("Printing the Courses in sorted order using List: "
+ list);

// Removing items from HashSet using remove()


eduCourses.remove("Python");

// Iterating over HashSet items


System.out.println("Iterating over course list after removing Python:");
Iterator<String> i = eduCourses.iterator();
while (i.hasNext())
System.out.println(i.next());

// Creating another object of HashSet


HashSet<String> eduNewCourses = new HashSet<String>();
eduNewCourses.add("Node.js");
eduNewCourses.add("Python");
eduNewCourses.add("Machine Learning");

//Removing all the new elements from HashSet


eduCourses.removeAll(eduNewCourses);
System.out.println("After invoking removeAll() method courses left: "+
eduCourses);

//Removing elements on the basis of specified condition

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 11


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

eduCourses.removeIf(str->str.contains("Java"));
System.out.println("After invoking removeIf() method: "+
eduCourses);

// Removing elements from eduCourses which are specified in


eduNewCourses
eduCourses.retainAll(eduNewCourses);
System.out.println("HashSet after " + "retainAll() operation : " +
eduNewCourses);

//Removing all the elements available in the set


eduCourses.clear();
System.out.println("After invoking clear() method: "+ eduCourses);

}
}

Tree Set:
TreeSet is similar to HashSet except that it sorts the elements in the ascending
order while HashSet doesn’t maintain any order. TreeSet allows null element but like
HashSet it doesn’t allow. Like most of the other collection classes this class is also
not synchronized.

Example:
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String args[]) {
// TreeSet of String Type
TreeSet<String> tset = new TreeSet<String>();

// Adding elements to TreeSet<String>


tset.add("ABC");
tset.add("String");
tset.add("Test");
tset.add("Pen");
tset.add("Ink");
tset.add("Jack");

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 12


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

//Displaying TreeSet
System.out.println(tset);

// TreeSet of Integer Type


TreeSet<Integer> tset2 = new TreeSet<Integer>();

// Adding elements to TreeSet<Integer>


tset2.add(88);
tset2.add(7);
tset2.add(101);
tset2.add(0);
tset2.add(3);
tset2.add(222);
System.out.println(tset2);
}
}

Priority Queue
Java PriorityQueue class is a queue data structure implementation in which objects are processed
based on their priority. It is different from standard queues where FIFO (First-In-First-Out) algorithm is
followed.

In a priority queue, added objects are according to their priority. By default, the priority is determined
by objects’ natural ordering. Default priority can be overridden by a Comparator provided at queue
construction time.

PriorityQueue Features

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 13


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

PriorityQueue is an unbounded queue and grows dynamically. The default initial capacity
is '11' which can be overridden using initialCapacity parameter in appropriate constructor.
It does not allow NULL objects.
Objects added to PriorityQueue MUST be comparable.
The objects of the priority queue are ordered by default in natural order.
A Comparator can be used for custom ordering of objects in the queue.
The head of the priority queue is the least element based on the natural ordering or
comparator based ordering. When we poll the queue, it returns the head object from the
queue.
If multiple objects are present of same priority the it can poll any one of them randomly.
PriorityQueue is not thread safe. Use PriorityBlockingQueue in concurrent environment.
It provides O(log(n)) time for add and poll methods.
2. Java PriorityQueue Example

Example:

Employee.java
public class Employee implements Comparable<Employee> {

private Long id;


private String name;
private LocalDate dob;

public Employee(Long id, String name, LocalDate dob) {


super();
this.id = id;
this.name = name;
this.dob = dob;
}

@Override
public int compareTo(Employee emp) {
return this.getId().compareTo(emp.getId());
}

//Getters and setters

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]";
}
}

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 14


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Array Deque

Interfaces implemented by ArrayDeque


The ArrayDeque class implements these two interfaces:
Java Queue Interface
Java Deque Interface

Creating ArrayDeque
In order to create an array deque, we must import the java.util.ArrayDeque
package.

Here is how we can create an array deque in Java:

ArrayDeque<Type> animal = new ArrayDeque<>();


Here, Type indicates the type of the array deque. For example,

// Creating String type ArrayDeque


ArrayDeque<String> animals = new ArrayDeque<>();

// Creating Integer type ArrayDeque


ArrayDeque<Integer> age = new ArrayDeque<>();

Insert Elements to Deque


1. Add elements using add(), addFirst() and addLast()

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 15


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

add() - inserts the specified element at the end of the array deque
addFirst() - inserts the specified element at the beginning of the array
deque
addLast() - inserts the specified at the end of the array deque (equivalent
to add())
Note: If the array deque is full, all these methods add(), addFirst() and
addLast() throws IllegalStateException.

Example,

import java.util.ArrayDeque;

class Main {
public static void main(String[] args) {
ArrayDeque<String> animals= new ArrayDeque<>();

// Using add()
animals.add("Dog");

// Using addFirst()
animals.addFirst("Cat");

// Using addLast()
animals.addLast("Horse");
System.out.println("ArrayDeque: " + animals);
}
}

More Methods:

offer() - inserts the specified element at the end of the array deque
offerFirst() - inserts the specified element at the beginning of the array
deque
offerLast() - inserts the specified element at the end of the array deque

Access elements using getFirst() and getLast()

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 16


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

getFirst() - returns the first element of the array deque


getLast() - returns the last element of the array deque

Access elements using peek(), peekFirst() and peekLast() method

peek() - returns the first element of the array deque


peekFirst() - returns the first element of the array deque (equivalent to
peek())
peekLast() - returns the last element of the array deque

Remove elements using the remove(), removeFirst(), removeLast()


method

remove() - returns and removes an element from the first element of the
array deque
remove(element) - returns and removes the specified element from the
head of the array deque
removeFirst() - returns and removes the first element from the array deque
(equivalent to remove())
removeLast() - returns and removes the last element from the array deque

Iterator

In Java, Iterator is an interface available in Collection framework in java.util package.


It is a Java Cursor used to iterate a collection of objects.

It is used to traverse a collection object elements one by one.


It is available since Java 1.2 Collection Framework.
It is applicable for all Collection classes. So it is also known as Universal
Java Cursor.
It supports both READ and REMOVE Operations.
Compare to Enumeration interface, Iterator method names are simple and
easy to use.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 17


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Java Iterator Class Diagram

As shown in the Class Diagram below, Java Iterator has four methods. We are
already familiar with first four methods. Oracle Corp has added fourth method to this
interface in Java SE 8 release.

Java Iterator Methods


In this section, we will discuss about Java Iterator methods in-brief. We
will explore these methods in-depth with some useful examples in the
coming section.

boolean hasNext():Returns true if the iteration has more elements.


E next(): Returns the next element in the iteration.
default void remove(): Removes from the underlying collection the last
element returned by this iterator.
default void forEachRemaining(Consumer action): Performs the given action for
each remaining element until all elements have been processed or the action throws
an exception.

Example-1
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ExternalIteratorDemo


{
public static void main(String[] args)
{
List<String> names = new LinkedList<>();

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 18


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

names.add("Rams");
names.add("Posa");
names.add("Chinni");

// Getting Iterator
Iterator<String> namesIterator = names.iterator();

// Traversing elements
while(namesIterator.hasNext()){
System.out.println(namesIterator.next());
}

}
}
Example-2:-

import java.util.LinkedList;
import java.util.List;

public class InternalIteratorDemo


{
public static void main(String[] args)
{
List<String> names = new LinkedList<>();
names.add("Rams");
names.add("Posa");
names.add("Chinni");

for(String name: names){


System.out.println(name);
}

}
}

Map interfaces and classes:


A Map is an object that maps keys to values, or is a collection of attribute-value pairs. It models

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 19


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

the function abstraction in mathematics. The following picture illustrates a map:

Characteristics of a Map:
Because a Map is not a true collection, its characteristics and behaviors are different than the other
collections like List or Set.

A Map cannot contain duplicate keys and each key can map to at most one value. Some
implementations allow null key and null value (HashMap and LinkedHashMap) but some does
not (TreeMap).

1.Why and When Use Maps:


Maps are perfectly for key-value association mapping such as dictionaries.
Use Maps when you want to retrieve and update elements by keys, or
perform lookups by keys. Some examples:
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).
This tutorial provides code examples around the three major
implementations of Map which are described below.

2. Implementations of Map
In the inheritance tree of the Map interface, there are several
implementations but only 3 major, common, and general purpose

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 20


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

implementations - they are HashMap and LinkedHashMap and TreeMap.


Let’s see the characteristics and behaviors of each implementation:
HashMap: this implementation uses a hash table as the underlying data
structure. It implements all of the Map operations and allows null values
and one null key. This class is roughly equivalent to Hashtable - a legacy
data structure before Java Collections Framework, but it is not
synchronized and permits nulls. HashMap does not guarantee the order of
its key-value elements. Therefore, consider to use a HashMap when order
does not matter and nulls are acceptable.
LinkedHashMap: this implementation uses a hash table and a linked list
as the underlying data structures, thus the order of a LinkedHashMap is
predictable, with insertion-order as the default order. This implementation
also allows nulls like HashMap. So consider using a LinkedHashMap
when you want a Map with its key-value pairs are sorted by their insertion
order.
TreeMap: this implementation uses a red-black tree as the underlying data
structure. A TreeMap is sorted according to the natural ordering of its
keys, or by a Comparator provided at creation time. This implementation
does not allow nulls. So consider using a TreeMap when you want a Map
sorts its key-value pairs by the natural order of the keys (e.g. alphabetic
order or numeric order), or by a custom order you specify.
So far you have understood the key differences of the 3 major Map’s
implementations. And the code examples in this tutorial are around them.
Now, let’s see how to use Map for your daily coding.

3. Creating a new Map


Creating a HashMap:
Always use interface type (Map), generics and diamond operator to
declare a new map. The following code creates a HashMap:

Map<Integer, String> mapHttpErrors = new HashMap<>();

mapHttpErrors.put(200, "OK");
mapHttpErrors.put(303, "See Other");
mapHttpErrors.put(404, "Not Found");
mapHttpErrors.put(500, "Internal Server Error");

System.out.println(mapHttpErrors);
This maps HTTP status codes to their descriptions.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 21


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Map<Integer, String> mapErrors = new HashMap<>(mapHttpErrors);


The map mapErrors is created with initial elements copied from the map
mapHttpErrors.

Creating a LinkedHashMap:
The following code creates a LinkedHashMap that maps phone numbers
with contact names:

Map<String, String> mapContacts = new LinkedHashMap<>();

mapContacts.put("0169238175", "Tom");
mapContacts.put("0904891321", "Peter");
mapContacts.put("0945678912", "Mary");
mapContacts.put("0981127421", "John");

System.out.println(mapContacts);

Creating a TreeMap:
The following code creates a TreeMap that maps file extensions to
programming languages:
Map<String, String> mapLang = new TreeMap<>();

mapLang.put(".c", "C");
mapLang.put(".java", "Java");
mapLang.put(".pl", "Perl");
mapLang.put(".cs", "C#");
mapLang.put(".php", "PHP");
mapLang.put(".cpp", "C++");
mapLang.put(".xml", "XML");

System.out.println(mapLang);
Output:
1
{.c=C, .cpp=C++, .cs=C#, .java=Java, .php=PHP, .pl=Perl, .xml=XML}
As you can see, the TreeMap sorts its keys by their natural ordering,
which is the alphabetical order in this case.

4. Performing Basic Operations on a Map

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 22


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

The basic operations of a Map are association (put), lookup (get),


checking (containsKeyand containsValue), modification (removeand
replace) and cardinality (size and isEmpty).

Associating a value with a key:


The put(K, V) method associates the specified value V with the specified
key K. If the map already contains a mapping for the key, the old value is
replaced by the specified value:

Map<Integer, String> mapHttpErrors = new HashMap<>();


mapHttpErrors.put(400, "Bad Request");
mapHttpErrors.put(304, "Not Modified");
mapHttpErrors.put(200, "OK");
mapHttpErrors.put(301, "Moved Permanently");
mapHttpErrors.put(500, "Internal Server Error");

Getting a value associated with a specified key:


The get(Object key) method returns the value associated with the
specified key, or returns null if the map contains no mapping for the key.
Given the map in the previous example:
1
2
String status301 = mapHttpErrors.get(301);
System.out.println("301: " + status301);
Output:
1
301: Moved Permanently

Checking if the map contains a specified key:


The method containsKey(Object key) returns true if the map contains a
mapping for the specified key. For example:
1
2
3
if (mapHttpErrors.containsKey("200")) {
System.out.println("Http status 200");
}
Output:

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 23


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

1
Found: Http status 200

Checking if the map contains a specified value:


The method containsValue(Object value) returns true if the map contains
one or more keys associated with the specified value. For example:
1
2
3
if (mapHttpErrors.containsValue("OK")) {
System.out.println("Found status OK");
}

Removing a mapping from the map:


The remove(Object key) method removes the mapping for a key from the
map if it is present (we care about only the key, and the value does not
matter). This method returns the value to which the map previously
associated the key, or null if the map doesn’t contain mapping for the key.
Here’s an example:

String removedValue = mapHttpErrors.remove(500);

if (removedValue != null) {
System.out.println("Removed value: " + removedValue);
}

Removed value: Internal Server Error


Similarly, the remove(Object key, Object value) method removes the
mapping of a specified key and specified value, and returns true if the
value was removed. This method is useful in case we really care about the
key and value to be removed.
I recommend you to read this well-know Java collection book to learn in-
depth about Java collections framework.

Replacing a value associated with a specified key:


The replace(K key, V value)method replaces the entry for the specified

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 24


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

key only if it is currently mapping to some value. This method returns the
previous value associated with the specified key.

System.out.println("Map before: " + mapHttpErrors);

mapHttpErrors.replace(304, "No Changes");

System.out.println("Map after: " + mapHttpErrors);

Map before: {400=Bad Request, 304=Not Modified, 200=OK, 301=Moved


Permanently}
Map after: {400=Bad Request, 304=No Changes, 200=OK, 301=Moved
Permanently}
Similarly, the replace(K key, V oldValue, V newValue) method replaces
the entry for the specified key only if it is currently mapping to the specified
value. This method returns true if the value was replaced. Useful in case
we want to replace exactly a key-value mapping.

Getting the size of the map:


The size()method returns the number of key-value mappings in this map.
For example:
1
int size = mapHttpErrors.size();
Output:
1
Number of HTTP status code: 5

Checking if the map is empty:


The isEmpty() method returns true if the map contains no key-value
mappings. For example:
1
2
3
4
5
if (mapHttpErrors.isEmpty()) {
System.out.println("No Error");
} else {

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 25


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

System.out.println("Have HTTP Errors");


}
Output:
1
Have HTTP Errors

5. Iterating Over a Map (using Collection views)


As a Map is not a true collection, there is no direct method for iterating
over a map. Instead, we can iterate over a map using its collection views.
Any Map’s implementation has to provide the following three Collection
view methods:
keySet(): returns a Set view of the keys contained in the map. Hence we
can iterate over the keys of the map as shown in the following example:

Map<String, String> mapCountryCodes = new HashMap<>();

mapCountryCodes.put("1", "USA");
mapCountryCodes.put("44", "United Kingdom");
mapCountryCodes.put("33", "France");
mapCountryCodes.put("81", "Japan");

Set<String> setCodes = mapCountryCodes.keySet();


Iterator<String> iterator = setCodes.iterator();

while (iterator.hasNext()) {
String code = iterator.next();
String country = mapCountryCodes.get(code);

System.out.println(code + " => " + country);


}

values(): returns a collection of values contained in the map. Thus we can


iterate over values of the map like this:

Collection<String> countries = mapCountryCodes.values();

for (String country : countries) {


System.out.println(country);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 26


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

}
Set<Map.Entry<String, String>> entries = mapCountryCodes.entrySet();

for (Map.Entry<String, String> entry : entries) {


String code = entry.getKey();
String country = entry.getValue();

System.out.println(code + " => " + country);


}

mapCountryCodes.forEach(
(code, country) -> System.out.println(code + " => " + country));

6. Performing Bulk Operations with Maps


There are two bulk operations with maps: clear() and putAll().
The clear() method removes all mappings from the map. The map will be
empty after this method returns. For

The putAll(Map<K, V> m) method copies all of the mappings from the
specified map to this map. Here’s an example:
Map<Integer, String> countryCodesEU = new HashMap<>();

countryCodesEU.put(44, "United Kingdom");


countryCodesEU.put(33, "France");
countryCodesEU.put(49, "Germany");

Map<Integer, String> countryCodesWorld = new HashMap<>();

countryCodesWorld.put(1, "United States");


countryCodesWorld.put(86, "China");
countryCodesWorld.put(82, "South Korea");

System.out.println("Before: " + countryCodesWorld);

countryCodesWorld.putAll(countryCodesEU);

System.out.println("After: " + countryCodesWorld);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 27


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Comparators

Java Comparator interface used to sort a array or list of objects based on custom order. Custom
ordering of elements is imposed by implementing Comparator.compare() method in the objects.

We can use Comparator interface in following situations.

Sort the array or list of objects, but NOT in natural order.


Sort the array or list of objects where we can not modify the object’s source code to
implement Comparable interface.
Sort same list or array of objects on different fields.
Using group by sort on list or array of objects on different fields.

Comparator.compare()
To enable total ordering on objects, we need to create class which implements
Comparator interface. Then we need to override it’s compare(T o1, T o2) method.

It compares its two arguments for order. It returns a negative integer, zero, or a
positive integer as the first argument is less than, equal to, or greater than the second.

The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) &&
(compare(y, z)>0)) implies compare(x, z)>0.

Example:
import java.time.LocalDate;

public class Employee implements Serializable {

private static final long serialVersionUID = 1L;

private Long id;


private String name;
private LocalDate dob;

//Getters and Setters

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]";
}
}

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 28


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Using Comparator

import java.util.Comparator;
 
public class NameSorter implements Comparator<Employee>
{
    @Override
    public int compare(Employee e1, Employee e2) {
        return e1.getName().compareToIgnoreCase( e2.getName() );
    }
}

Collections.sort() and Arrays.sort()


Use Collections.sort(list, Comparator) method sort a list of objects in order
imposed by provided comparator instance.
Use Arrays.sort(array, Comparator) method sort an array of objects in order
imposed by provided comparator instance.
Collections.comparing()
This utility method accepts a function that extracts a sort key for the class. This is
essentially a field on which the class objects will be sorted.

Comparator examples
//Order by name
Comparator.comparing(Employee::getName);

//Order by name in reverse order


Comparator.comparing(Employee::getName).reversed();

//Order by id field
Comparator.comparing(Employee::getId);

//Order by employee age


Comparator.comparing(Employee::getDate);
Collections.thenComparing()
This utility method is used for group by sort. Using this method, we can chain
multiple comparators to sort the list or array of objects on multiple fields.

It is very similar to SQL GROUP BY clause to order rows on different fields.

Comparator thenComparing() examples

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 29


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

//Order by name and then by age


Comparator.comparing(Employee::getName)
.thenComparing(Employee::getDob);

//Order by name -> date of birth -> id


Comparator.comparing(Employee::getName)
.thenComparing(Employee::getDob)
.thenComparing(Employee::getId);
Using above syntax, we can create virtually any sorting logic.

Collections.reverseOrder()
This utility method returns a comparator that imposes the reverse of the natural
ordering or total ordering on a collection of objects that implement the Comparable
interface.

Comparator reversed() examples


//Reverse of natural order as specified in
//Comparable interface's compareTo() method

Comparator.reversed();

//Reverse of order by name

Comparator.comparing(Employee::getName).reversed();

Collection Algorithms

Algorithms:

The Collections and Arrays classes, available as a part of the Collections


Framework, support various algorithms. The Java platform provides great majority of the
algorithms to perform different kind of operations such as sorting and searching.

I. Sorting Algorithm:

The sort algorithm reorders a List such that its elements are in ascending order
according to an ordering relationship. The sort operation uses a slightly optimized merge
sort algorithm which is fast and stable. TreeSet and TreeMap classes offers a sorted
version of sets and maps, there is no sorted List collection implementation. Sorting of a
List is done with the sort( ) method.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 30


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

For example, the following program prints the arguments (the arguments, given
through command line) of a List in an alphabetical order.

import java.util.*;

public class SortDemo {


public static void main(String[] args) {
List<String> list = Arrays.asList(args);
Collections.sort(list);
System.out.println(list);
}
}

Searching Algorithm :

Besides sorting, the Collections and Arrays classes provide a mechanism to


search a List or an array, as well as to find the first and last values within a Collection.
The binarySearch algorithm searches for a specified element in a sorted List. This
algorithm takes a List and an element to search for the search key. This form assumes
that the List is sorted in ascending order according to the natural ordering of its elements.

Before searching an element, the List must be sorted, Once you have sorted the
List, using Collection.sort( ) method, you can perform a quickly binary search operation
using the overridden binarySearch( ) method.

For example, the following program prints the sorted arguments list (the
arguments, given through command line) and then search the position of a specified key
value.

import java.util.*;

public class SearchDemo {


public static void main(String[] args) {
try{
List<String> list = Arrays.asList(args);
Collections.sort(list);
System.out.println("The sorted list is: "+list);
int pos = Collections.binarySearch(list, list.get(2));
System.out.println("The position of the searched element is : "+pos
+" and the element is:"+list.get(2));
}
catch(Exception e){}

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 31


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

}
}

Dictionary:

Dictionary is an abstract class representing a key/value storage repository that


operates like Map. You can store the value in a Dictionary object and once it is stored,
you can retrieve it by using its key.

Declaration:
public abstract class Dictionary extends Object

Constructor:
Dictionary() constructor

Methods of util.Dictionary Class


Let us have a look at a few different methods of Dictionary Class.

Check the size of the dictionary


size() : java.util.Dictionary.size() returns the number of key-value pairs in the
Dictionary

Syntax:
public abstract int size()
Add/ put values in dictionary
put(K key, V value) : java.util.Dictionary.put(K key, V value) adds key-value pair
to the dictionary

Syntax:
public abstract V put(K key, V value)

Return values present in the dictionary


elements() : java.util.Dictionary.elements() returns value representation in
dictionary

Syntax:
public abstract Enumeration elements()

Get method to fetch the values mapped with the key


get(Object key) : java.util.Dictionary.get(Object key) returns the value that is
mapped with the key in the dictionary

Syntax:

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 32


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

public abstract V get(Object key)

Check if dictionary is empty


isEmpty() : java.util.Dictionary.isEmpty() checks whether the dictionary is empty
or not.

Programming & Frameworks Training


Syntax:
public abstract boolean isEmpty()

Return true, if there is no key-value relation in the dictionary; else return false.

Removing key value from dictionary in Java

remove(Object key) : java.util.Dictionary.remove(Object key) removes the key-


value pair mapped with the key.

Syntax:
public abstract V remove(Object key)

Example:

import java.util.*;
public class My_Class
{
public static void main(String[] args)
{
// Initializing a Dictionary
Dictionary edu = new Hashtable();
// put() method
edu.put("1000", "Edureka");
edu.put("2000", "Platfrom");
// elements() method :
for (Enumeration i = edu.elements(); i.hasMoreElements();)
{
System.out.println("Value in Dictionary : " + i.nextElement());
}
// get() method :
System.out.println("nValue at key = 3000 : " + edu.get("2000"));

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 33


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

System.out.println("Value at key = 1000 : " + edu.get("2000"));


// isEmpty() method :
System.out.println("nThere is no key-value pair : " + edu.isEmpty() + "n");
// keys() method :
for (Enumeration k = edu.keys(); k.hasMoreElements();)
{
System.out.println("Keys in Dictionary : " + k.nextElement());
}
// remove() method :
System.out.println("nRemove : " + edu.remove("1000"));
System.out.println("Check the value of removed key : " + edu.get("1000"));
System.out.println("nSize of Dictionary : " + edu.size());
}
}

Hashtable:

This class implements a hash table, which maps keys to values. Any non-null
object can be used as a key or as a value. Hashtable is similar to HashMap except it is
synchronized. There are few more differences between HashMap and Hashtable class,
you can read them in detail at: Difference between HashMap and Hashtable.

In this tutorial we will see how to create a Hashtable, how to populate its entries
and then we will learn how to display its key-value pairs using Enumeration. At the end of
this article we will see Hashtable tutorials and methods of Hashtable class.

Example
import java.util.Hashtable;
import java.util.Enumeration;

public class HashtableExample {

public static void main(String[] args) {

Enumeration names;
String key;

// Creating a Hashtable
Hashtable<String, String> hashtable =
new Hashtable<String, String>();

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 34


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

// Adding Key and Value pairs to Hashtable


hashtable.put("Key1","Chaitanya");
hashtable.put("Key2","Ajeet");
hashtable.put("Key3","Peter");
hashtable.put("Key4","Ricky");
hashtable.put("Key5","Mona");

names = hashtable.keys();
while(names.hasMoreElements()) {
key = (String) names.nextElement();
System.out.println("Key: " +key+ " & Value: " +
hashtable.get(key));
}
}
}

Methods of Hashtable class:


1) void clear(): Removes all the key-value mappings from Hashtable and makes
it empty. Clears this hashtable so that it contains no keys..

2) Object clone(): Creates a shallow copy of this hashtable. All the structure of
the hashtable itself is copied, but the keys and values are not cloned. This is a relatively
expensive operation.

3) boolean contains(Object value): Tests if some key maps into the specified
value in this hashtable. This operation is more expensive than the containsKey method.
Note that this method is identical in functionality to containsValue, (which is part
of the Map interface in the collections framework).

4) boolean isEmpty(): Tests if this hashtable maps no keys to values.

5) Enumeration keys(): Returns an enumeration of the keys contained in the


hash table.

6) Object put(Object key, Object value): Maps the specified key to the specified
value in this hashtable.

7) void rehash(): Increases the size of the hash table and rehashes all of its keys.

8) Object remove(Object key): Removes the key (and its corresponding value)
from this hashtable.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 35


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

9) int size(): Returns the number of key-value mappings present in Hashtable.

10) String toString(): Returns the string equivalent of a hash table.

11) boolean containsKey(Object key): Tests if the specified object is a key in this
hashtable.

12) boolean containsValue(Object value): Tests if the specified object is a value


in this hashtable. Returns true if some value equal to value exists within the hash table.
Returns false if the value isn’t found.

13) Enumeration elements(): Returns an enumeration of the values contained in


the hash table.

14) Object get(Object key): Returns the value to which the specified key is mapped, or null if
this map contains no mapping for the key.

Properties:

The Properties class represents a persistent set of properties. The Properties can be saved to a
stream or loaded from a stream. Each key and its corresponding value in the property list is a string.
Because Properties inherits from Hashtable, the put and putAll methods can be applied to a
Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose
keys or values are not Strings. The setProperty method should be used instead. If the store or save
method is called on a "compromised" Properties object that contains a non-String key or value, the
call will fail. Similarly, the call to the propertyNames or list method will fail if it is called on a
"compromised" Properties object that contains a non-String key.

Java properties file is used to store project configuration data or settings. In this tutorial, we will show
you how to read and write to/from a .properties file.

Properties prop = new Properties();

// set key and value


prop.setProperty("db.url", "localhost");
prop.setProperty("db.user", "mkyong");
prop.setProperty("db.password", "password");

// save a properties file


prop.store(outputStream, "");

// load a properties file


prop.load(inputStream)

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 36


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

// get value by key


prop.getProperty("db.url");
prop.getProperty("db.user");
prop.getProperty("db.password");

// get all keys


prop.keySet();

// print everything
prop.forEach((k, v) -> System.out.println("Key : " + k + ", Value : " + v));

String Tokenizer:

StringTokenizer class is used for creating tokens in Java. It allows an application to break or split into
small parts. Each split string part is called Token.

A  StringTokennizer in Java, object keeps the string in the present position as it is to


be tokenized. By taking a substring of the string a token can return that utilize to
make the StringTokenizer protest.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 37


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

StringTokenizer Constructors

(String str)

str is a string to be tokenized and it considers default delimiters like newline, space, tab, carriage return
and form feed which can be further tokenized.

StringTokenizer(String str, String delim)

delim is set of delimiters that are used to tokenize the given string.

StringTokenizer(String str, String delim, boolean flag)

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 38


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Example:

import java.util.*;
public class StringTokenizerDemo {
public static void main(String args[])
{
System.out.println("StringTokenizer Constructor 1 - ");
StringTokenizer st1 =
new StringTokenizer("Hello Readers, Welcome to DataFlair", " ");
while (st1.hasMoreTokens())
System.out.println(st1.nextToken());
System.out.println("StringTokenizer Constructor 2 - ");
StringTokenizer st2 =
new StringTokenizer("JAVA : Code : String", " :");
while (st2.hasMoreTokens())
System.out.println(st2.nextToken());
System.out.println("StringTokenizer Constructor 3 - ");
StringTokenizer st3 =
new StringTokenizer("JAVA Code String", " : ", true);
while (st3.hasMoreTokens())
System.out.println(st3.nextToken());
}
}

BitSet:

Bitsets represents fixed size sequence of N bits having values either zero or one. Zero
means value is false or unset. One means value is true or set. Bitset size is fixed at
compile time. Bitset is a class defined in java.util package. It is a special type of array
which holds bit values. It implements a vector of bits. Its size grows automatically as
more bits are needed.

This class provides us two types of constructors to form bitset from integers as well as
from strings. Those two are:

Bitset( ): It is a no-argument constructor to create a default object.


Bitset(int size): It is a one-constructor having integer arguments to form an instance of the
bitset class with an initial size of the integer argument representing the no. of bits.

Example:

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 39


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

import java.util.BitSet;
public class BitSetJavaExample
{
public static void main(String args[])
{
int n=8;
BitSet p = new BitSet(n);
for(int i=0;i<n;i++)
p.set(i);
System.out.print("Bits of p are set as : ");
for(int i=0;i<n;i++)
System.out.print(p.get(i)+" ");
BitSet q = (BitSet) p.clone();
System.out.print("nBits of q are set as : ");
for(int i=0;i<n;i++)
System.out.print(q.get(i)+" ");
for(int i=0;i<3;i++)
p.clear(i);
System.out.print("nBits of p are now set as : ");
for(int i=0;i<n;i++)
System.out.print(p.get(i)+" ");
System.out.print("nBits of p which are true : "+p);
System.out.print("The Bits of q which are true : "+q);
BitSet r= (BitSet) p.clone();
p.xor(q);
System.out.println("Output of p xor q= "+p);
p = (BitSet) r.clone();
p.and(q);
System.out.println("Output of p and q = "+p);
p = (BitSet) r.clone();
p.or(q);
System.out.println("Output of p or q = "+p);
}
}

Date:

Date class
Specify the desired pattern while creating the instance of SimpleDateFormat.
Create an object of Date class.
Call the format() method of DateFormat class and pass the date object as a parameter to
the method.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 40


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

/* This will display the date and time in the format of


* 12/09/2017 24:12:35. See the complete program below
*/
DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Date dateobj = new Date();
System.out.println(df.format(dateobj));

Getting current date and time in other timezone


The example we have seen above shows the date and time in local timezone. However
we can get the date and time in different time zone as well such as UTC/GMT etc. In the
following example we are displaying the time in GMT time zone.

import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class Example {
public static void main(String[] args) {
//"hh" in pattern is for 12 hour time format and "aa" is for AM/PM
SimpleDateFormat dateTimeInGMT = new SimpleDateFormat("yyyy-MMM-dd
hh:mm:ss aa");
//Setting the time zone
dateTimeInGMT.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateTimeInGMT.format(new Date()));
}
}

Calendar

Calendar class
Specify the desired pattern for the date and time. Similar to the step 1 of above method.
Create an object of Calendar class by calling getInstance() method of it.
Call the format() method of DateFormat and pass the Calendar.getTime() as a parameter
to the method.
DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Calendar calobj = Calendar.getInstance();
System.out.println(df.format(calobj.getTime()));
Complete java code for getting current date and time
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class GettingCurrentDate {


public static void main(String[] args) {

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 41


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

//getting current date and time using Date class


DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Date dateobj = new Date();
System.out.println(df.format(dateobj));

/*getting current date time using calendar class


* An Alternative of above*/
Calendar calobj = Calendar.getInstance();
System.out.println(df.format(calobj.getTime()));
}
}

Random

Java provides the Math class in the java.util package to generate random numbers.

The Math class contains the static Math.random() method to generate random numbers
of the double type.

The random() method returns a double value with a positive sign, greater than or equal to
0.0 and less than 1.0. When you call Math.random(), under the hood, a java.util.Random
pseudorandom-number generator object is created and used.

You can use the Math.random() method with or without passing parameters. If you
provide parameters, the method produces random numbers within the given parameters.

The code to use the Math.random() method:

public static double getRandomNumber(){


double x = Math.random();
return x;
}

The getRandomNumber() method uses the Math.random() method to return a positive


double value that is greater than or equal to 0.0 and less than 1.0.

The output of running the code is:

Double between 0.0 and 1.0: SimpleRandomNumber = 0.21753313144345698

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 42


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Random Numbers Within a Given Range


For generating random numbers between a given a range, you need to specify the range.
A standard expression for accomplishing this is:

(Math.random() * ((max - min) + 1)) + min

Let us break this expression into steps:

First, multiply the magnitude of the range of values you want to cover by the result that
Math.random() produces.

Math.random() * ( max - min ) returns a value in the range [0, max – min] where max is
excluded. For example, if you want [5,10], you need to cover 5 integer values so you can
use Math.random()*5. This would return a value in the range [0,5], where 5 is not
included.
Next, shift this range up to the range that you are targeting. You do this by adding the min
value.
(Math.random() * ( max - min )) + min

But this still does not include the maximum value.

To get the max value included, you need to add 1 to your range parameter (max - min).
This will return a random double within the specified range.
double x = (Math.random()*((max-min)+1))+min;

There are different ways of implementing the above expression. Let us look at a couple of
them.

Random Double Within a Given Range


By default, the Math.random() method returns a random number of the type double
whenever it is called. The code to generate a random double value between a specified
range is:

public static double getRandomDoubleBetweenRange(double min, double max){


double x = (Math.random()*((max-min)+1))+min;
return x;
}

You can call the preceding method from the main method by passing the arguments like
this.

System.out.println("Double between 5.0 and 10.00: RandomDoubleNumber =


"+getRandomDoubleBetweenRange(5.0, 10.00));

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 43


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

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

Formatter Construction

Formatter(): It is a no-argument constructor to create a Formatter object. It operates on a


default buffer created from a StringBuilder. It is the commonly used constructor of all of
its type.
Formatter(Appendable a): Here, the Appendable object specifies a buffer for formatted
output. If, however, the value is null, the object automatically creates a Stringbuilder to
hold the formatted output.
Formatter(Appendable a, Locale loc): The Locale object regionalizes the output format
according to the specified locale. If unspecified, the default locale is used. Sometimes, a
locale is necessary to tailor the output according to Geo-political or culturally sensitive
data, such as formatting the date and time, substituting a locale-specific decimal
separator, and the like.
Formatter(File file): The file parameter of this constructor designates a reference to a open file where
the output will be streamed.

%S or %s: Specifies String


%X or %x: Specifies hexadecimal integer
%o: Specifies Octal integer
%d: Specifies Decimal integer
%c: Specifies character
%T or %t: Specifies Time and date
%n: Inserts newline character
%B or %b: Specifies Boolean
%A or %a: Specifies floating point hexadecimal
%f: Specifies Decimal floating point

Example:

Formatter f=new Formatter();


f.format("%3$3s %2$3s %1$3s", "fear",
"strengthen", "weakness");
System.out.println(f);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 44


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Regionalize Output
StringBuilder builder=new StringBuilder();

Formatter f=new Formatter(builder);


f.format(Locale.FRANCE,"%.5f", -1325.789);
System.out.println(f);

Formatter f2=new Formatter();


f2.format(Locale.CANADA, "%.5f", -1325.789);
System.out.println(f2);
Regionalize Date
Formatter f3=new Formatter();
f3.format(Locale.FRENCH,"%1$te %1$tB, %1$tY",
Calendar.getInstance());
System.out.println(f3);

Formatter f4=new Formatter();


f4.format(Locale.GERMANY,"%1$te %1$tB, %1$tY",
Calendar.getInstance());
System.out.println(f4);
Using %n and %% Specifiers
Formatter f = new Formatter();
f.format("Format%n %.2f%% complete", 46.6);
System.out.println(f);

Scanner

The Scanner class of the java.util package is used to read input data from different sources like input
streams, users, files, etc.

Example:

Read a Line of Text Using Scanner


import java.util.Scanner;

class Main {
public static void main(String[] args) {

// Creates an object of Scanner


Scanner input = new Scanner(System.in);

System.out.print("Enter your name: ");

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 45


Dept. of Computer Science Engineering, KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

// Takes input from the keyboard


String name = input.nextLine();

// Prints name
System.out.println("My name is " + name);

// Closes the scanner


input.close();
}
}

Scanner Methods to Take Input


The Scanner class provides various methods that allow us to read inputs of different types.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 46

You might also like