Unit 4
Unit 4
LinkedList Class:
The Java LinkedList class uses doubly linked lists (we can add or remove
elements from both sides) to store the elements. It provides a linked-list data
structure. It inherits the AbstractList class and implements List and Deque
interfaces.
The important points about Java LinkedList are:
● Java LinkedList class can contain duplicate elements.
● Java LinkedList class maintains insertion order.
● Java LinkedList class is non synchronized.
● In Java LinkedList class, manipulation is fast because no shifting needs
to occur.
● The Java LinkedList class can be used as a list, stack or queue.
All of the operations perform as could be expected for a doubly-linked
list. Operations that index into the list will traverse the list from the beginning
or the end, whichever is closer to the specified index.
In case of doubly linked lists, we can add or remove elements from both
side.
LinkedList implements the Deque interface, you have access to the methods
defined by Deque.
● To add elements to the start of a list you can use addFirst( ) or
offerFirst( ) for the Deque process.
● To add elements to the end of the list, use addLast( ) or offerLast( ) for
the Deque process.
● To obtain the first element, you can use getFirst( ) or peekFirst( ) for the
Deque process.
● To obtain the last element,use getLast( ) or peekLast( ) for the Deque
process.
● To remove the first element, use removeFirst( ) or pollFirst( ) for the
Deque process.
● To remove the last element, use removeLast( ) or pollLast( ) for Deque
process
Constructors:
LinkedList() It is used to construct an empty list.
LinkedList(Collection It is used to construct a list containing the elements of
c) the specified collection, in the order they are returned by
the collection's iterator.
Example:
import java.util.*;
class LinkedList1
{
public static void main(String[] args)
{
LinkedList a1=new LinkedList();
LinkedList a2=new LinkedList();
a1.add("M");
a1.add("R");
a1.add("C");
a1.add("E");
a1.add("W");
a1.add("M");
System.out.println("In Array: "+a1);
a1.addFirst("CAMPUS3");
a1.addLast("MAISAMMAGUDA");
System.out.println("After Adding Last: "+a1);
System.out.println("Size of an Array: "+a1.size());
//Converting collections into array
Object a[]=a1.toArray();
String str="";
for(int i=0;i<a.length;i++)
//converting array of elements into String
str+=a[i];
System.out.println("After Conversion of Collection into Array:-
"+str);
System.out.println("In Array: "+a1);
Object obj=a1.get(0);
System.out.println(""+a1.set(0,obj.toString()+"Changed to 9"));
System.out.println("After setting in a1 List: "+a1);
//Removing first and last Elements
a1.removeFirst();
a1.removeLast();
a1.removeLast();
System.out.println("Final List of a1 "+a1);
}
}
Output:
In Array: [M, R, C, E, W, M]
After Adding Last: [CAMPUS3, M, R, C, E, W, M, MAISAMMAGUDA]
Size of an Array: 8
After Conversion of Collection into Array:-
CAMPUS3MRCEWMMAISAMMAGUDA
In Array: [CAMPUS3, M, R, C, E, W, M, MAISAMMAGUDA]
CAMPUS3
After setting in a1 List: [CAMPUS3Changed to 9, M, R, C, E, W, M,
MAISAMMAGUDA]
Final List of a1 [M, R, C, E, W]
The Legacy Classes and Interfaces
● Vector class
● Stack class
Vector:
● Vector Class is the resizable-array implementation of the List interface.
● Implements all optional list operations, and permits all elements,
including null.
● The ArrayList class is synchronized (Hence the vector Objects are Thread
safe).
● Vector Class contains Duplicate Values.
● Vector Class Insertion Order is Allowed
● Heterogeneous Objects are allowed (Except in TreeSet class and
TreeMap Every where Heterogeneous Objects are allowed)
Constructors:
SN Constructor Description
1) vector() It constructs an empty vector with the default
size as 10.
It constructs an empty vector with the
2) vector(int initialCapacity) specified initial capacity and with its capacity
increment equal to zero.
3) vector(int initialCapacity, int Itspecified
constructs an empty vector with the
initial capacity and capacity
capacityIncrement) increment.
4) Vector(
E> c)
Collection<? extends It constructs a vector that contains the
elements of a collection c.
vector class methods:
Method Description
addElement() It is used to append the specified component to the end of
this vector. It increases the vector size by one.
capacity() It is used to get the current capacity of this vector.
elementAt() It is used to get the component at the specified index.
elements() It returns an enumeration of the components of a vector.
firstElement() It is used to get the first component of the vector.
insertElementAt() It is used to insert the specified object as a component in
the given vector at the specified index.
isEmpty() It is used to check if this vector has no components.
iterator() It is used to get an iterator over the elements in the list in
proper sequence.
lastElement() It is used to get the last component of the vector.
It is used to get the index of the last occurrence of the
lastIndexOf() specified element in the vector. It returns -1 if the vector
does not contain the element.
removeAllElements() Ittheissize
used to remove all elements from the vector and set
of the vector to zero.
removeElement() Ittheisargument
used to remove the first (lowest-indexed) occurrence of
from the vector.
removeElementAt() It is used to delete the component at the specified index.
replaceAll() It is used to replace each element of the list with the result
of applying the operator to that element.
retainAll() It is used to retain only that element in the vector which is
contained in the specified collection.
setElementAt() It is used to set the component at the specified index of the
vector to the specified object.
Example:
import java.util.*;
class VectorEx
{
public static void main(String args[])
{
Vector v=new Vector(); // Default initial capacity is 10.
to initialize the particular buckets
for particular elements capacity there we can
use this constructor as
Vector v =new Vector(10,1);
System.out.println(“Default element Vector Capacity:”+v.capacity());
for(int i=1;i<=10;i++)
{
v.addElement(i);
}
System.out.println(“Initial element Vector Capacity:”+v.capacity());
v.addElement(“A”);
System.out.println(“after adding element Vector Capacity:”v.capacity());
//here the Capacity is increased by initialcapacity* 2
System.out.println(“final Elements in vector:”+v);
}
}
OUTPUT:
Default element Vector Capacity:10
Initial element Vector Capacity:10
after adding element Vector Capacity:20
[1,2,3,4,5,6,7,8,9,10,A]
STACK:
It is a child class of Vector.
Stack is a specially designed class for LAST IN FIRST OUT order(LIFO).
Stack only defines the default constructor, which creates an empty stack
Constructor:
Stack s=new Stack();
Methods:
Method & Description
boolean empty()
Tests if this stack is empty. Returns true if the stack is empty, and returns false
if the stack contains elements.
Object peek( )
Returns the element on the top of the stack, but does not remove it.
Object pop( )
Returns the element on the top of the stack, removing it in the process.
Object push(Object element)
Pushes the element onto the stack. Element is also returned.
int search(Object element)
Searches for elements in the stack. If found, its offset from the top of the stack
is returned. Otherwise, -1 is returned.
Example:
import java.util.*;
class VectorEx
{
public static void main(String args[])
{
Stack s=new Stack();
s.push(“A”);
s.push(“B”);
s.push(“F”);
s.push(“J”);
System.out.println(s);
System.out.println(s.search(“A”));
System.out.println(s.search(“Z”));
}
}
OUTPUT:
[A,B,F,J]
4 //HERE the output will be as an offset of the stack.
-1 // if search element not there then the output
will be as offset of the stack is -1.
Set Interface:
Set is a collection that cannot contain duplicate elements. This interface
models the mathematical set abstraction and is used to represent sets, such as
the deck of cards.
The Java platform contains three general-purpose Set implementations:
HashSet, TreeSet, and LinkedHashSet. Set interface doesn’t allow
random-access to an element in the Collection. You can use an iterator or
foreach loop to traverse the elements of a Set.
Set is a generic interface that has this declaration:
interface Set<E>
Here, E specifies the type of objects that the set will hold.
SortedSet Interface
SortedSet is a Set that maintains its elements in ascending order. Several
additional operations are provided to take advantage of the ordering. Sorted
sets are used for naturally ordered sets, such as word lists and membership
rolls.
SortedSet is a generic interface that has this declaration:
interface SortedSet<E>.
Here, E specifies the type of objects that the set will hold.
HashSet class
Java HashSet class is used to create a collection that uses a hash table for
storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
● HashSet stores the elements by using a mechanism called hashing.
● HashSet contains unique elements only.
In hashing, the informational content of a key is used to determine a unique
value, called its hash code. The hash code is then used as the index at which
the data associated with the key is stored. The transformation of the key into
its hash code is performed automatically—you never see the hash code itself.
Also, your code can’t directly index the hash table. The Advantage of hashing is
that it allows the execution time of add( ), contains( ), remove( ), and size( ) to
remain constant even for large sets.
The following constructors are defined:
Constructor Description
It is used to construct a default HashSet. (default
HashSet() capacity is 16 elements)
It is used to initialize the capacity of the hash set to
HashSet(int capacity) the given integer value capacity. The capacity grows
automatically as elements are added to the HashSet.
It is used to initialize the capacity of the hash set to
HashSet(int capacity, the given integer value capacity and the specified load
float loadFactor) factor. (default load factor or fillRatio is 0.75 )
Java TreeSet class implements the Set interface that uses a tree for
storage. It inherits AbstractSet class and implements NavigableSet interface.
The objects of the TreeSet class are stored in ascending order.
The important points about Java TreeSet class are:
● Contains unique elements only like HashSet.
● Access and retrieval times are quite fast.
● Maintains ascending order (Default Natural Sorting order(in case of
Numbers Ascending Order, in case of Strings Alphabetical Order).
● By sorting Collection Elements in Ascending Order internally JVM will
Process with Comparable Interface and compare the Elements with
compareTo() method for Sorting Ascending Order.
● By Using Customized Order we have to call Comparator Interface
through TreeSet class ,the Comparator Interface compares the Elements
with compare() method for customizing Sorting Order.
● TreeSet implements the NavigableSet interface (which was added by
Java SE 6),
Constructors of Java TreeSet class
Constructor Description
It is used to construct an empty tree set that will be
TreeSet() sorted in an ascending order according to the natural
order of the tree set.
TreeSet(Collection c) Itelements
is used to build a new tree set that contains the
of the collection c.
TreeSet(Comparator Itsortedis used to construct an empty tree set that will be
according to a given comparator (customized
comp) sorting order).
TreeSet(SortedSet ss) Itof istheused to build a TreeSet that contains the elements
given SortedSet.
Methods of Java TreeSet class
Method Description
boolean It is used to add all of the elements in the specified
addAll(Collection c) collection to this set.
boolean contains(Object It is used to return true if this set contains the
o) specified element.
boolean isEmpty() It is used to return true if this set contains no
elements.
boolean remove(Object It is used to remove the specified element from this set
o) if it is present.
void add(Object o) It is used to add the specified element to this set if it is
not already present.
void clear() It is used to remove all of the elements from this set.
Object first() It is used to return the first (lowest) element currently
in this sorted set.
Object last() It is used to return the last (highest) element currently
in this sorted set.
int size() It is used to return the number of elements in this set.
Examples
Queue:
Java Queue interface orders the element in FIFO(First In First Out)
manner. In FIFO, the first element is removed first and the last element is
removed at last.
● JDK1.5 Version Enhancements (Queue Interface)
● It is the Child Interface of Collection.
● If we want to represent a group of individual objects prior to processing
this we should go for Queue.
For example:
● Before sending an SMS message, all mobile numbers we have to store in
some data Structures, in which order we added mobile no’s in the same
order will be delivered, for this First in First (FIFO) Requirement Queue is
the best Choice.
● Usually Queue follows FIFO order but based on our Requirement we can
implement our own Priority order also (PriorityQueue class).
● From JDK1.5 version onwards LinkedList class also implements Queue
Interface.
● LinkedList class based implementation of Queue always follows FIFO
order
Specific Methods:
Method Description
boolean add(object) It is used to insert the specified element into this queue
and return true upon success.
boolean It is used to insert the specified element into this
offer(object) queue.
It is used to retrieves and removes the head of this queue,
Object remove() , or returns Runtime Exception
NoSuchElementException
Object poll() It is used to retrieve and remove the head of this
queue, or returns null if this queue is empty.
It is used to retrieves, but does not remove, the head
Object element() of this queue, or returns Runtime Exception
NoSuchElementException
Object peek() It is used to retrieve, but does not remove, the head of
this queue, or returns null if this queue is empty.
PriorityQueue:
● If we want to represent a group of individual objects prior to processing
according to some Priority ,Then we should go for PriorityQueue class
● The Priority can be either Default natural sorting order(integers like
Ascending order and Strings like Alphabetical Order) or customized
sorting order defined by Comparator Interface.
● Insertion Order is not allowed and it is based on some Priority.
● Duplicated objects are not allowed.
● If we are depending on Default natural sorting order compulsory the
objects should be Homogeneous and comparable otherwise we will get
Runtime Exception i.e ClassCastException.
● If we are defining customized sorting order by comparator the objects
need not be Homogeneous and comparable.
● Null is not allowed even as the first element also.
Constructors:
// default 11 elements capacity and Default natural Sorting order (integers like
Ascending order and Strings like Alphabetical Order)
PriorityQueue pq=new PriorityQueue();
PriorityQueue pq=new PriorityQueue(int initialcapacity);
PriorityQueue pq=new PriorityQueue(int initialcapacity,Comparator c);
PriorityQueue pq=new PriorityQueue(SortedSet s);
PriorityQueue pq=new PriorityQueue(Collection c);
Example: Example2:
import java.util.*; //customized order
class ProiorityQueueEx import java.util.*;
{
public static void main(String args[]) class ProiorityQueueEx2
{ {
PriorityQueue pq=new PriorityQueue(); public static void main(String args[])
//System.out.println(pq.peek()); {
//null PriorityQueue pq=new
//System.out.println(pq.element()); PriorityQueue(15,new
//Runtime Exception MyComparator());
for(int i=0;i<=10;i++) q.offer(“A”);
{ q.offer(“Z”);
pq.offer(i); q.offer(“L”);
} q.offer(“B”);
System.out.println(pq); System.out.println(pq);
System.out.println(pq.peek()); {
System.out.println(pq.element()); }
} Class MyComparator implements
} Comparator
Output: {
[0,1,2,3,4,5,6,7,8,9,10] public int compare(Object obj1,Object
0 obj2)
[1,2,3,4,5,6,7,8,9,10] {
String s1=(String)obj1;
String s2=obj2.toString();
return –s1.compareTo(s2);
}
}
Output:
[Z,L,B,A]
Deque Interface
The ArrayDeque class provides the facility of using deque and resizable-array.
It inherits AbstractCollection class and implements the Deque interface.
The important points about ArrayDeque class are:
● Unlike Queue, we can add or remove elements from both sides.
● Null elements are not allowed in the ArrayDeque.
● ArrayDeque is not thread safe, in the absence of external
synchronization.
● ArrayDeque has no capacity restrictions.
● ArrayDeque is faster than LinkedList and Stack.
Methods
Method Description
boolean It is used to insert the specified element into this deque and
add(object) return true upon success.
boolean It is used to insert the specified element into this deque.
offer(object)
Object remove() It is used to retrieve and remove the head of this deque.
Object poll() It is used to retrieve and remove the head of this deque, or
returns null if this deque is empty.
Object element() Itdeque.
is used to retrieve, but does not remove, the head of this
Map Interface:
Java Map is an object that maps keys to values. A map
cannot contain duplicate keys: Each key can map to at most one value.
The Java platform contains three general-purpose Map implementations:
HashMap, TreeMap, and LinkedHashMap.
⮚ Map doesn't allow duplicate keys, but you can have duplicate values.
⮚ HashMap and LinkedHashMap allow null keys and values but TreeMap
doesn't allow any null key or value.
⮚ If we want to represent a group of objects with keys and value pairs then
we should go for Map Interface.
⮚ Both keys and values are objects only.
⮚ Each key value pair is called Entry, hence Map is considered as a
collection of Entry Objects.
Methods Description:
Object put(Object key, Object value):
⮚ To add one key value pair to the map,if the key is already present then
old value will be replaced with new value and returns Old value.
For Example:
m.put(102,”siva”);
m.put(102,”ggg”);
then output will be {102,”ggg”}.
Collection views of Map:
⮚ Set keySet(): It is used to return the Set view containing all the keys.
⮚ Collection values() : It is used to return the Collection of view containing
all the values.
⮚ Set entrySet() : It is used to return the Set view containing all the keys
and values.
Entry Interface:
⮚ A Map is a Group of Key Value pairs and Each Key value pair is called
Entry, hence Map is considered as collection of Entry Objects.
⮚ Without an existing Map object there is no chance of an Existing Entry
Object,hence Entry Interface is defined inside Map Interface.
⮚ Entry Specific Methods and we can apply only Entry Objects
● Object getKey(): to get of specified Entry Key
● Object getValue():to get of specified Entry value
● Object setValue():to set of specified Entry Value
HashMap Class
Example:
import java.util.*;
public class HashMapEX {
public static void main(String args[])
{
HashMap m=new HashMap();
m.put("101","A");
m.put("102","B");
m.put("103",1000);
m.put("104",'v');
System.out.println(m);
m.put("101",455);
System.out.println(m);
Set s=m.keySet();
System.out.println(s);
Collection c=m.values();
System.out.println(c);
Set s1=m.entrySet();
System.out.println(s1);
Iterator itr=s1.iterator();
while(itr.hasNext())
{
Map.Entry m1=(Map.Entry)itr.next();
System.out.println(m1.getKey());
if(m1.getKey().equals("101"))
{
m1.setValue(500000);
}
}
System.out.println(m);
}
}
Output:
{101=A, 102=B, 103=1000, 104=v}
{101=455, 102=B, 103=1000, 104=v}
[101, 102, 103, 104]
[455, B, 1000, v]
[101=455, 102=B, 103=1000, 104=v]
101
102
103
104
{101=500000, 102=B, 103=1000, 104=v}
LinkedHashMap:
It is the Child class of Hash Map it is exactly same as HashMap including
Methods and Constructors except the following
The important points about Java LinkedHashMap class are:
● LinkedHashMap class is a combination of Hash table and Linked list
(Hybrid DataStructure) implementation of the Map interface
● It maintains Insertion order.
Constructors of Java LinkedHashMap class
Constructor Description
LinkedHashMap() It is used to construct a default
LinkedHashMap.
LinkedHashMap(int capacity) It is used to initialize a LinkedHashMap with the
given capacity.
LinkedHashMap(int capacity, It is used to initialize both the capacity and the
float fillRatio) fillRatio.
LinkedHashMap(Map m) It is used to initialize the LinkedHashMap with
the elements from the given Map class m.
SortedMap Interface:
⮚ SortedMap is the Child Interface of Map Interface.
⮚ If we want to represent a group of key value pairs according to some
sorting order of keys then we should go for SortedMap.
⮚ Sorting is based on the key but not based on Value.
⮚ Sorted map defines the following specific methods
Examples:
//DefaultNatureSorting order for //customized order for Homogenous
Hetrogenous keys keys
import java.util.*; import java.util.*;
class TestCollection15{ public class TreeMapEX2 {
public static void main(String public static void
args[]){ main(String args[])
TreeMap<Integer,String> hm=new {
TreeMap<Integer,String>(); TreeMap m=new
hm.put(100,"Amit"); TreeMap(new MyComparator());
hm.put(102,"Ravi");
hm.put(101,"Vijay"); m.put("eca","B");
hm.put(103,"Rahul"); m.put("eae",1000);
for(Map.Entry m:hm.entrySet()){ m.put("cse","A");
System.out.println(m.getKey()+" m.put("mech",'v');
"+m.getValue()); System.out.println(m);
}
}
} }
Output:
}
100 Amit class MyComparator
101 Vijay implements Comparator
102 Ravi {
103 Rahul public int compare(Object
obj1,Object obj2)
{
String s1=obj1.toString();
String s2=obj2.toString();
return s2.compareTo(s1);
}
}
Output:
{mech=v, eca=B, eae=1000, cse=A}
//DefaultNatureSorting order for //customized order for Hetrogenous
Hetrogenous keys keys
import java.util.*; import java.util.*;
public class TreeMapEX { public class TreeMapEX2 {
public static void main(String args[]) public static void main(String
{ args[])
TreeMap m=new TreeMap(); {
TreeMap m=new
m.put("eca","B"); TreeMap(new MyComparator());
m.put("eae",1000);
m.put("cse","A"); m.put(12,"B");
m.put("mech",'v'); m.put(55,1000);
System.out.println(m); m.put("A","A");
m.put("cse",455); m.put("45",'v');
System.out.println(m); System.out.println(m);
Set s=m.keySet();
System.out.println(s);
Collection c=m.values(); }
System.out.println(c);
Set s1=m.entrySet(); }
System.out.println(s1); class MyComparator implements
Iterator itr=s1.iterator(); Comparator
while(itr.hasNext()) {
{ public int compare(Object
Map.Entry obj1,Object obj2)
m1=(Map.Entry)itr.next(); {
String s1=obj1.toString();
System.out.println(m1.getKey()); String s2=obj2.toString();
return s2.compareTo(s1);
if(m1.getKey().equals("cse")) }
{ }
m1.setValue(500000); Output:
} {A=A, 55=1000, 45=v, 12=B}
}
System.out.println(m);
}
}
Output:
{cse=A, eae=1000, eca=B, mech=v}
{cse=455, eae=1000, eca=B, mech=v}
[cse, eae, eca, mech]
[455, 1000, B, v]
[cse=455, eae=1000, eca=B, mech=v]
cse
eae
eca
mech
{cse=500000, eae=1000, eca=B,
mech=v}
Example:
//may take the values in buckets as Top to Bottom.
//if any bucket having 2 or more elements then
// it will take from right to left
import java.util.*;
public class HashTableEx {
public static void main(String args[])
{
Hashtable h=new Hashtable();
h.put(new Temp(5),"d");
h.put(new Temp(2),"f");
h.put(new Temp(6),"g");
h.put(new Temp(15),"e");
h.put(new Temp(23),"w");
h.put(new Temp(16),"hhh");
System.out.println(h);
}
}
class Temp
{
int i;
Temp(int i)
{
this.i=i;
}
public int hashCode()
{
return i;
}
public String toString()
{
return i+"";
}
}
Output:
{6=g, 16=hhh, 5=d, 15=e, 2=f, 23=w}
For-each is another array traversing technique like for loop, while loop,
do-while loop introduced in Java5.
● It starts with the keyword for like a normal for-loop.
● Instead of declaring and initializing a loop counter variable, you declare a
variable that is the same type as the base type of the array, followed by a
colon, which is then followed by the array name.
● In the loop body, you can use the loop variable you created rather than
using an indexed array element.
● It’s commonly used to iterate over an array or a Collections class (eg,
ArrayList)
Syntax:
for (type var : array)
{
statements using var;
}
is equivalent to:
for (int i=0; i<arr.length; i++)
{
type var = arr[i];
statements using var;
}
Example:
// Use the for-each for loop to cycle through a collection.
import java.util.*;
class ForEachDemo {
public static void main(String args[]) {
// Create an array list for integers.
ArrayList<Integer> vals = new ArrayList<Integer>();
// Add values to the array list.
vals.add(1);
vals.add(2);
vals.add(3);
vals.add(4);
vals.add(5);
// Use for loop to display the values.
System.out.print("Original contents of vals: ");
for(int v : vals)
System.out.print(v + " ");
System.out.println();
// Now, sum the values by using a for loop.
int sum = 0;
for(int v : vals)
sum += v;
System.out.println("Sum of values: " + sum);
}
}
The output from the program is shown here:
Original contents of vals: 1 2 3 4 5
Sum of values: 15
String Tokenizer
The java.util.StringTokenizer class allows you to break a string into
tokens. It is a simple way to break strings.
It doesn't provide the facility to differentiate numbers, quoted strings,
identifiers etc. like the StreamTokenizer class. We will discuss the
StreamTokenizer class in the I/O chapter.
Constructors of StringTokenizer class
There are 3 constructors defined in the StringTokenizer class.
Constructor Description
StringTokenizer(String str) creates a StringTokenizer with a specified string.
StringTokenizer(String str, creates StringTokenizer with specified string and
String delim) delimiter.
StringTokenizer(String str, creates StringTokenizer with specified string,
String delim, boolean delimiter and returnValue. If the return value is
returnValue) true, delimiter characters are considered to be
tokens. If it is false, delimiter characters serve to
separate tokens.
Methods of StringTokenizer class
The 6 useful methods of StringTokenizer class are as follows:
Public method Description
boolean hasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the StringTokenizer
object.
String nextToken(String returns the next token based on the delimiter.
delim)
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type is Object.
int countTokens() returns the total number of tokens.
Simple example of StringTokenizer class
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:my
name
is
khan
Example of nextToken(String delim) method of StringTokenizer class
import java.util.*;
public class Test {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,khan");
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
}
}
Output:Next token is : my
BitSet Class
The Java BitSet class implements a vector of bits. The BitSet grows
automatically as more bits are needed. The BitSet class comes under the
java.util package. The BitSet class extends the Object class and provides the
implementation of Serializable and Cloneable interfaces.
Each component of the bit set contains at least one Boolean value. The
contents of one BitSet may be changed by another BitSet using logical AND,
logical OR and logical exclusive OR operations. The index of bits of the BitSet
class is represented by positive integers.
Each element of bits contains either true or false value. Initially, all bits
of a set have a false value. A BitSet is not safe for multithreaded use without
using external synchronization.
The BitSet class creates a special type of array that holds bit values. This
array can increase in size as needed. This makes it similar to a vector of bits.
The BitSet constructors are shown here:
BitSet( )
BitSet(int size)
The first version creates a default object. The second version allows you to
specify its initial
size (that is, the number of bits that it can hold). All bits are initialized to zero.
Example:
Here is an example that demonstrates BitSet:
// BitSet Demonstration.
import java.util.BitSet;
class BitSetDemo {
public static void main(String args[]) {
BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);
// set some bits
for(int i=0; i<16; i++) {
if((i%2) == 0) bits1.set(i);
if((i%5) != 0) bits2.set(i);
}
System.out.println("Initial pattern in bits1: ");
System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);
// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
The output from this program is shown here. When toString( ) converts a
BitSet object to its
string equivalent, each set bit is represented by its bit position. Cleared bits are
not shown.
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
Initial pattern in bits2:
{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}
bits2 AND bits1:
{2, 4, 6, 8, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 XOR bits1:
{}
Date:
The Date class encapsulates the current date and time. The Date class
encapsulates the current date and time. Before beginning our examination of
Date, it is important to point out that it has changed substantially from its
original version defined by Java 1.0. When Java 1.1 was released, many of the
functions carried out by the original Date class were moved into the Calendar
and DateFormat classes, and as a result, many of the original 1.0 Date
methods were deprecated. Since the deprecated 1.0 methods should not be
used for new code, they are not described here.
Date supports the following constructors:
Date( )
Date(long millisec)
The first constructor initializes the object with the current date and time. The
second constructor
accepts one argument that equals the number of milliseconds that have
elapsed since midnight,
January 1, 1970.
Date also
implements the Comparable interface.
Constructors
No. Constructor Description
1) Date() Creates a date object representing current date and
time.
2) Date(long
milliseconds)
Creates a date object for the given milliseconds since
January 1, 1970, 00:00:00 GMT.
java.util.Date Methods
No. Method Description
1) boolean after(Date date) tests if the current date is after the given
date.
2) boolean before(Date date) tests if the current date is before the given
date.
3) Object clone() returns the clone object of the current date.
4) int compareTo(Date date) compares the current date with the given
date.
5) boolean equals(Date date) compares current date with the given date for
equality.
8) int hashCode() returns the hash code value for this date
object.
9) void setTime(long time) changes the current date and time to a given
time.
10) Instant toInstant() converts current date into Instant object.
11) String toString() converts this date into an Instant object.
Example:
import java.util.Date.*;
public class UtilDateExample1{
public static void main(String args[]){
java.util.Date date=new Date();
System.out.println(date);
}}
Output:
Mon Nov 05 15:06:04 IST 2018
Example2:
import java.util.Date.*;
public class UtilDateExample1{
public static void main(String args[]){
java.util.Date date=new Date();
System.out.println(date);
}}
Output:
Mon Nov 05 15:05:41 IST 2018
Calendar Class:
Random:
The Random class is a generator of pseudorandom numbers. These are
called pseudorandom numbers because they are simply uniformly distributed
sequences. Random defines the following constructors:
Random( )
Random(long seed)
The first version creates a number generator that uses the current time as the
starting, or seed,
value. The second form allows you to specify a seed value manually.
Methods Description
doubles() Returns an unlimited stream of pseudorandom double values.
ints() Returns an unlimited stream of pseudorandom int values.
longs() Returns an unlimited stream of pseudorandom long values.
next() Generates the next pseudorandom number.
nextByte() Generates random bytes and puts them into a specified byte
array.
nextDouble() Returns the next pseudorandom Double value between 0.0 and
1.0 from the random number generator's sequence
Returns the next uniformly distributed pseudorandom Float
nextFloat() value between 0.0 and 1.0 from this random number
generator's sequence
Returns the next pseudorandom Gaussian double value with
nextGaussian() mean 0.0 and standard deviation 1.0 from this random number
generator's sequence.
setSeed() Sets the seed of this random number generator using a single
long seed.
Example:
import java.util.Random;
public class JavaRandomExample1 {
public static void main(String[] args) {
//create random object
Random random= new Random();
//returns unlimited stream of pseudorandom long values
System.out.println("Longs value : "+random.longs());
// Returns the next pseudo random boolean value
boolean val = random.nextBoolean();
System.out.println("Random boolean value : "+val);
byte[] bytes = new byte[10];
//generates random bytes and put them in an array
random.nextBytes(bytes);
System.out.print("Random bytes = ( ");
for(int i = 0; i< bytes.length; i++)
{
System.out.printf("%d ", bytes[i]);
}
System.out.print(")");
}
}
Output:
Longs value : java.util.stream.LongPipeline$Head@50cbc42f
Random boolean value : false
Random bytes = ( -127 74 73 -22 -49 -38 -103 15 -27 -64 )
Formatter
● With the release of JDK 5, Java added a capability long desired by
programmers.
● Java has offered a rich and varied API, but it has not always offered an
easy way to create formatted text output, especially for numeric values.
● Classes such as NumberFormat, DateFormat, and MessageFormat
provided by earlier versions of Java do have useful formatting
capabilities, but they were not especially convenient to use.
● At the core of Java’s support for creating formatted output is the
Formatter class. It provides format conversions that let you display
numbers, strings, and time and date in virtually any format you like. It
operates in a manner similar to the C/C++ printf( ) function, which
means that if you are familiar with C/C++, then learning to use
Formatter will be very easy. It also further streamlines the conversion of
C/C++ code to Java. If you are not familiar with C/C++, it is still quite
easy to format data.
Constructors
The Formatter class defines many constructors, which enable you to construct
a Formatter in a variety of ways. Here is a sampling:
Formatter( )
Formatter(Appendable buf)
Formatter(Appendable buf, Locale loc)
Formatter(String filename)
throws FileNotFoundException
Formatter(String filename, String charset)
throws FileNotFoundException, UnsupportedEncodingException
Formatter(File outF)
throws FileNotFoundException
Formatter(OutputStream outStrm)
Formatter Methods
Method Description
Closes the invoking Formatter. This
causes any resources used by the
object to be released. After a
void close( ) Formatter has been closed, it cannot
be reused. An attempt to use a closed
Formatter results in a
FormatterClosedException.
Flushes the format buffer. This causes
any output currently in the buffer to
void flush( ) be written to the destination. This
applies mostly to a Formatter tied to a
file.
Formatter format(String fmtString, Formats the arguments passed via
Object ... args) args according to the format specifiers
contained in fmtString. Returns the
invoking object.
Formats the arguments passed via
Formatter format(Locale loc, args according to the format specifiers
String fmtString, contained in fmtString. The locale
Object ... args) specified by loc is
used for this format. Returns the
invoking object.
If the underlying object that is the
destination for output throws an
IOException ioException( ) IOException, then this exception is
returned. Otherwise,
null is returned.
Locale locale( ) Returns the invoking object’s locale.
Returns a reference to the underlying
Appendable out( ) object that is the destination for
output.
String toString( ) Returns a String containing the
formatted output.
Formatting Numbers
● To format an integer in decimal format, use %d. To format a
floating-point value in decimal format, use %f.
● To format a floating-point value in scientific notation, use %e. Numbers
● represented in scientific notation take this general form:
● x.dddddde+/–yy
● The %g format specifier causes Formatter to use either %f or %e,
whichever is shorter.
● The following program demonstrates the effect of the %g format specifier:
Example:
// Demonstrate the %g format specifier.
import java.util.*;
class FormatDemo2 {
public static void main(String args[]) {
Formatter fmt = new Formatter();
for(double i=1000; i < 1.0e+10; i *= 100) {
fmt.format("%g ", i);
System.out.println(fmt);
}
}
}
It produces the following output:
1000.000000
1000.000000 100000.000000
1000.000000 100000.000000 1.000000e+07
1000.000000 100000.000000 1.000000e+07 1.000000e+09
Scanner
● Scanner is the complement of Formatter. Added by JDK 5, Scanner
reads formatted input and converts it into its binary form.
● Although it has always been possible to read formatted input, it required
more effort than most programmers would prefer. Because of the
addition
● of Scanner, it is now easy to read all types of numeric values, strings,
and other types of data,
● whether it comes from a disk file, the keyboard, or another source.
● Scanner can be used to read input from the console, a file, a string, or
any source that implements the Readable interface or
ReadableByteChannel.
For example,
You can use Scanner to read a number from the keyboard and assign its
value to a variable. As you will see, given its power, Scanner is surprisingly
easy to use.
Constructors
In general, a Scanner can be created for a String, an InputStream, a File, or
any object that implements the Readable or ReadableByteChannel interfaces.
Here are some examples.
The following sequence creates a Scanner that reads the file Test.txt:
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
This works because FileReader implements the Readable interface. Thus, the
call to the constructor resolves to Scanner(Readable).
Java Scanner class comes under the java.util package. Java has various ways
to read input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter that is
whitespace by default. It provides many methods to read and parse various
primitive values.
Java Scanner class is widely used to parse text for string and primitive types
using a regular expression.
Java Scanner class extends Object class and implements Iterator and
Closeable interfaces.
Examples:
Some Scanner Examples
The addition of Scanner to Java makes what was formerly a tedious task into
an easy one.
To understand why, let’s look at some examples.
The following program averages a list of numbers entered at the keyboard:
// Use Scanner to compute an average of the values.
import java.util.*;
class AvgNums {
public static void main(String args[]) {
Scanner conin = new Scanner(System.in);
int count = 0;
double sum = 0.0;
System.out.println("Enter numbers to average.");
// Read and sum numbers.
while(conin.hasNext()) {
if(conin.hasNextDouble()) {
sum += conin.nextDouble();
count++;
}
else {
String str = conin.next();
if(str.equals("done")) break;
else {
System.out.println("Data format error.");
return;
}
}
}
System.out.println("Average is " + sum / count);
}
}
The program reads numbers from the keyboard, summing them in the process,
until the user enters the string “done”. It then stops input and displays the
average of the numbers.
Here is a sample run:
Enter numbers to average.
1.2
2
3.4
4
done
Average is 2.65