The Collections FRAMEWORK (Java - Util) : Part-A
The Collections FRAMEWORK (Java - Util) : Part-A
The Collections FRAMEWORK (Java - Util) : Part-A
4
PART-A
SOLUTIONS
SHORT QUESTIONS WITH
AprilMay-18(R16), a1(o)
in collections framework?
Q1 What is the benefit of Generics genencs
implementations. The
Answer the collection interfaces with theircollection. Thus, the compiler
introduced generics and all inside the ClassCastException
The Java 1.5 version provide the object type that is available Hence, this ignores the
permit the user to object. Will be
collection Iramework programmer adds a diferent type of for conversion. So, the code
throw a compile-timc
error when the and casting operators
program. Gencrics do not require any INSTANCEOF
while running a
proper and clean all the time. Model Paper-l, Q1(9)
Define collection interfaces. basically
Q2.
collection interfaces. They are
called
Answer standard set of interfaces framework are as follows,
framework of Java is built on a interface of collection
The collection various
collection mechanism. The
defined for implementing
1. Collection interfacc
2. List interface
3. Queue interface
4. Dequeue interface
5. Set interface
interface.
6.Sortedset example.
a Collection Class? Give an Nov/Doc.-18(R16), a1(h)
What is
collection classes provide full implementa-
Q3.
collection classes. Some of the defined by collections
Answer :
collection interface are called aostract classes. The collection classes
ounes are
The shdnsses of used as it iS, and
so they can be
..
tion to collcction interfaces
framework are,
AbstractCollection
AbstractlList
AbstractSequentiallList
4. LinkedList
. ArrayList
AbstractSet
HashSet
8.
LinkedllashSet
9. TreeSet
10. Priority Queu
. Array Deque
PECTRUM ALLAN-ONE JOURHAL FOR
ENGINEERING STUDENTS
SIA GROUP
Example
import java.util.",
class Colorsl.ist
Output
red
yellow
black
Q4. Writo a short notes on Hashset class. aartetsa 9
Answe
to store the collection created by it imto
The HashSct inherits AbstractSct class and Sct interfacc. The HashSet class used
is
a hashing tcchnique. This hash code
the hash table thal stores the unique key. These kcys are converted into hash code by applying
is then used to rctricve the data associatcd with the key. The hash
table does not store the clements in any sorted order. Hashing
is uscful to perform the operations such as add ), remove( ), sizc) and contains( )._
a5. What are tho constructors usod in TreeMap?
Answer:
constructors which are in TrecMap are as follows.
rohc
1. TreeMap
I creates an cmpty TrecMap sorted as per the key's natura) order(ascending order). nnaaleneni
TreeMap(Map m1)
It creates a TrecMap object with the elements of another Map class as per key's natural order
3. TreeMap(Comparator comp)
I1
creates an cmpty TreeMap object with the sorting order of the Comparator spccified by "eomp".
4. TreeMap(SortedMap ml)
t creates a TrecMap object with the same elements of the SortedMap specified by "ml" with the same sorting order of "ml
This class docs not definc its own methods.
a6. What ls a Java Prdority queue?
Answer (Modol Paper-, a1(o)| Nov./Dec..18(R16). Q1
Priority Qucue
This class is derived from abstract queue class to implement priority based queues
Syntax
class Priority Queue<E>
Censtructor
The following are the constructors defined by priority queue,
Priority Queuc()
(i) Priorty Queue int capacity)
Priority Qucuci comparatorc? super E 1>compt)
Priority Qucuetint capacity, cormparator?super El>compt)
Priorny ucucícoliectian Textends E1>co)
(vi Priority ucucípriority qucue7extends E1>co)
(vi Priotty Queucturtedsetextends El>co)
. LooK for the Sih GROUP LOGO 2 on the TITLE COVER bofore you
buy
o1elePou
UNIT-4 The llections Framework Gava.util)
. Defino Iterator.
Answer
In computer vocabulary, teralor means an object with which
interface that allows programmers to access a collection.
we can travel all through a range of clements. In Java,
Jcta tor
n i
an
Following is the signature of iterator interface,
public Interface lterator
Differontiate between Enumeration and Iterator interfaco.
Answer : ApriiMay-18(R16), Q1(h)
Enumeration Iteratorr
allows to iIerate through a list of sequentially stored programmers to access a collection. It replaces
Itelements 1.it allows
ina data structure. enumeration interface in collecctions framework.
It consists of tow abstract methods such as hasMo- 2. It consists of three abstract methods such as boolean has-
reElements( ), nextElement(). Next( ), objectNext( ). void remove )._
3. It does not consist of remove( ) method. t consists of remove() method. be used
4 Itis a legacy interface and used to transverse a vector, 4. It is not considered as a legacy interfacc but it can
HashSct,
Hashtable. to traverse a hashMap, LinkedList, ArrayList,
TreeMap.
or deletc the elements from the col-
It cannot make changes to collection. 5.t can make changes
lection while iteration.
09. List out the map interfaces.
Answer
There are four map interfaces,
Map
2. Sorted map
3. Navigable map
4. Map.Entry.
010. Write about comparator interface.
Answer: Model Paper-, a1(h)
In general, a comparator compares two items of data. Java also means the same. In Java, Comparator is used to comparec
wO Stored objects in a Set or a Map etc.
data structure
The java.util.Comparator interface is used to dictate in which order we want the sorting of the objects of a
ienerally, Comparator is needed if there's a natural sorting order. Natural sorting order means alphabetical
not order-A before
Or before 2 etc. A TreeSét or a TreeMap, by default, gives a natural sorting order, but if we want a diferent order, then we
Tcquire
comparator.
Q1. What is Arrays class?
Answer
The
rameworkdiala structures introduced with Nov/Dec.-17(R16),
JDK 1.0 version are called legacy classes
and a1(a
interfaces.
AIS ad
far more superior with its rich set of features, the legacy classes
are not deprecated.
Even though, the
Collections
Te-engineered to fit into collection framework. Instead, some more
ECTR methods
dn ALLN-ONE J0URNAL FOR ENGINEERING
STUDENTS
SIA GROUP
J.HYDERABAD
JAVA ROTRAMMING|JNTU.HYDED.
talhle pivn a list »f lenany vlanes and interfaen
win unetdonality
Tpe thhe Clavs
Iegary NUnotune
interace Usel to iterale and print the elenments
memlim
elasinon-atnnmet) Stows all ypes of vbjects
Answert
The two nethats of dictionary aM
elements()
dictionary: Its syntax is,
The clement( ) method retums an cnumeration of values in the
String Tokenirer Class sepuarates string text into tokens delimitod by ls, t, Un, Ir and \f. It takes a string as input and pa
ito token. Thiasmethodis known as parning. StringTokenirer provides lexer/scanner since it is the initial step in the praes
arsing. It provides the following constructors.
Constructor Description
StringTokenirer(String s) lt takes the string to be tokenized as a paramerr and
considers white space as default delimiters
StringTokenizer(String s, String delimiters)
lt takes the string to te tokenized as a paraeter and
spocities a delimiters.
String Tokenizer( String s,
String delimiters, lt takes the string to be tokenizodas a paramcter an
boolean delim AsToken)
also spevities a delimiters.In addition to it, it reams
s tokens the vauc of
if delim AsToken is tnx
RESALook for
the SlA GROUP LoGO on the TITLE COVER
belore you buy
UNIT-4 The Collecti
ctions Framework (java.util)
PART-B
ESSAY QUESTIONS WITH SOLUTIONS
4.1 coLLECTIONS OVERVIEW, COLLECTION INTERFACES
a15. What is Java Collections Framework? List out some benefits of Collections framework and explain.
AprilMay18(Rt8) a)
OR
What are the best practices related to Java Collections Framework? Discuss.
Nov Dect8Rt8) QNa)
Answer
Collection Framework
Jva
provides a standardizevd way tir stv
Java collection framework consist, hierarchy, interfaces and classes. This framework
designed for the fivlhowing reasvs
nd manipulating group of objects defined in a program. The collection framework has been
To increase the performance of collection like dynamic arrays. linked
list. trees and hash tables.
Collection interface
2 List interface
3.Dequeueinterlace
4 Set interface
Sorted set interface.
Collection Interface
lt aiowS Users to Work with dinerent types of obioct
interface is the top most clement of collccton nicrarcny
Thisi
interface.
5. SortedSet Interface
inorder to handle, the sorted set.
This interface is derived from Set interface
Syntax: interface Set<E
LIST, LINKED LIST, HASH SET,
TREE SET
4.2 THE COLLECTION CLASsSES ARRAY
PRIORITY QUEUE, ARRAY DEQUE
Q17. Explain the different types of standard collection classes.
Model Paperd, 0
Answer:
Collection Classes
The subclasses of collection interface are called collection classes.
be used as it is, and oui
Some of the collection classes provide full implementation to collection interfaces so they can
are abstract classes. The collection classes defined by collections framework are,
I. AbstractCollection
2. AbstractList
3. AbstractSequentialList
4. LinkedList
5. ArrayList
6. AbstractSe
HashSet
LinkedHashSet
9. TreeSet
10. PriorityQueue
ArayDeque.
11.
Some of the commonly used collection classes are as follows,
1
ArrayList Class
The ArrayList class inherits the functionalities of AbstractList class and List
arrays. The size of an array needs not to be mentioned while creating the array list.
intrface. The ArrayList createsaica
The size of an array list grows
to accommodate new objects and shrinks when the objects are removed.
Constructors
AmayList(
ArrayList(Collection coll)
ArrayList(int size)
Look for the SIA GROUP LOGO on the TITLE COVER before you buy
UNIT-4 The Collections
Co Framework (java.uti) 4.7
The first form of constructors creates an empty list. The Output
second constr structor creates and initializes an array list with the Initial size of color list : 0
elements ofthe Collection 'coll'.
he third constructor specifies Size of color list after addition:4
Yellow]
initial size of arraylist whi can grow dynamically when Color list is : [Orange, Red, Green,
the
elements are added to
it. Size of color list after deletion:3
[Orange, Green, Yellow]
This class uses variable-length array (dynamic array) to The final Color list is:
objectreferences. This helps in dynamically increasing/ LinkedList Class AbstractScquentialList
the
Aecreasing the size of the collection whenever the elements of The LinkedList class inherits
decreas creates a linked list.
or shrink. class and List interface. It
aTay grow
ArrayList(): This constructor creates an empty list and Constructors
initializes it to 0. LinkedList()
LinkedList(Collection coll) while the
ArrayList(collections co): This constructor creates a constructor creates an empty linked lis
(il)
which the user can add elements from some other The first with the elements
list to initializes the linked list
Second constructor
list.
creates an
ArrayList(ínt capacity): This constructor value. The ofthe Collection 'coll'. addLast(Object obj):
aH)
specified Methods
empty list and initializes it to the void addFirst(Object obj), void inscrts an object
method of this class are as follows, (i) addLast() methods
The addFirst() and the end of the
linked list
to set the valucs to array beginning and at
set( ): This method is used obj at the
elementsS. respectively. ): The getFirst( )
to access/get the array getFirst( ), Object getLast( getLast( ) method
get( ): This method is used (i) Object element and
method returns the first
2.
clements. the linked list.
add elements to the list. returns the last element of removeLast( ): The
3. add(): This method is used removeFirst( ), Object and
remove( ): This method
is used to remove an element (iii) Object the first element the
removeFirst( ) method deletes the last element from
from the list. removeLast( ) method deletes
Methods increases linked list.
void ensureCapacity(int
size): This method Program
size specified by 'size'.an
the size ofan array list to the import java.util.";
method reduces the size of class LListDemo
() void trimToSize(): This
array list.
public static void
main(String args[ ])
Program
mport java.util."; LinkedList color = new
LinkedList();
class ColorsList color.add("Cyan"):
color.add("White");
public static vojd
main(String args[ }) color.addFirst("Yellow");
color.add(2, "Pink");
ArayList color =
new ArrayList(); color.addLast("Blue");
list:"
System.out.println("Initial size of Color color.add("Light green");
+color.size( )); System.out.println("Linked list after
addition:" + color);
color.add("Red"):
color.remove(1);
color.add"Green"): color.removeFirst( )
color.add(Yellow"); color.removeLast( );
color.add(0, "Orange"): after System.out.println("Linked list after
ystem.out.println("Size of color list
color.size( ); deletion:" + color);
addition:" +
color); Object obj = color.get(2);
ystem.out.println("Color list is:" + System.out.println("The color at index-2:"+
color.remove("Red"); (String) obj);
after
ystem.out.println("Size of color list
color.size( )); color.set(2, "Red");
delction:"+ System.out.println("ANer setting the final
is:"+
ystem.out.println(""The final Colorlist color); Linked list is:"+ color);
10URNAL FOR
ENGINEERING STUDENTS SIA GROUP
ANONE
4.8 JAVA PROGRAMMING JNTU-HYDERA
ERABA
Output
List list after addition: [Yellow, Cyan, Pink. White, Blue, Light green]
Linked list aftcr deletion: [Pink, White, Blue]
The color at index-2: Blue
keys are converted into hash code by applying a hashing technigue Tby
the hash table that stores the unique
Is then used to retrieve the data
key. These
associated with the key. The hash table does not store the elements in any soted order. s
hash
Ha
1s uscful to perform the operations such as add(
), remove( ), size() and contains( ).
Constructors
HashSet(
eHashSet(Collection coll)7t/1 ria
HashSet(int size) du
HashSet(int sizc, float fill_ratio)
The first form of constructor creates an empty hash set. The
second form ol constructor inilializes the hash set with t-
the hash set. The last form of constructor speci
elements of collection 'coll"'. The third form of constructor specifies the size of ra
set that can be ful before it is resized. It
both the size and the fill ratio. The fill ratio specifies the allowed capacity of hash
between 0.0 and 1.0. The default value for fill ratio is 0.75.
The HashSet does not define its own methods.
T
Program
import java.util.";
class HSet
Output
The Hash set is: [White, Blue, Black, Green]
4. TreeSet Class
TreeSe
The TreeSet class inherits Set interface. It creates a collection class,
that uses a tree for storage. Unlike the HashSet
5nSetaccessed
Ci and
stores the objects in sorted order i.e., in ascending order. Therefore,
retrieved very fast.
the large amount of sorted information can be a
RSSLook for the SlA GROUP LOGO on the TITLE COVER before you buy
Collections Framework (java.util)
he 4.9
NT4
oestructors
TreeSet()
TreeSet(Collection coll)
TreeSet(Comparator cp)
TreeSet(SortedSet sort)
con-
form ofo
of constructor creates a default tree set whose elements will be sorted in ascending order. he second
The first elements of he Collection 'coll'. The third constructor creates an empty tree sct whosec
initia e tree set with the
xtar corted in the order specified by the Comparator object "Cp. The final constructor initializes the tree setl with the
SortedSet 'sort'.
entsofthe
regrams
java.uti;
chs TSet
Oatput
The1ollowing
ArTay
are the nstructors defined by Array Dequeuc,
Dequeue()
Array
Dequeue(int
size)
ray Dequcue(collection
eSTROM <?extends E1>co)
ALAR
NE JOURNAL FOR NGINEERING STUDENTS SIA GROUP
JAVA PRoGRAMMING JNTU-HYne DERADAD
.10 in collection framework? Explain.
218. What is difference between ArrayList and LinkedList
Aprilt
Answer RI
LinkedlList
ArrayList
1.Aray list is used to store set of elements sequen Linked lst is used to store set of elements
ents scquentialh
using links.
tially using indexes.
Linked list does not provide randonm access lor the
2. Aray list provides random access for the elements e
present in the list. ments present in the list.
3.Aray list isextended by the Abstract list cass. Linked list is extended by the abstract sequential
4 ATay listis implemented by the listintcerface. 4Linked list is implcmented by the list. deque.qucue
The elements are accessed very fastly from the ar- The elements are accessed very slowly from thelinked
lint
ray list. list.
6. The manipulation for the elements of arTay list is 6. The manipulation tor the clements of the linkedlist
l u
slow. fast.
The behaviour of linked list as a list and queue.
The behaviour of aTay list is as a list.
Iterator
In compuner vocabulary, iteratoT means an object with which user can travel all through a range of clements. In Java
System.ounprintln(it.next()) 13 step
ATayList).
HeTe, list is an object of a collection (cg:
E Previous( ): This
NoSuchElement Exception. one. I lowever if there is no previous
of the previous clement, if there is
. Previouslndex( ): This method returms the index
int
clement, it returns -1. no current
clement Irom the list. It throws IllegalStaticExccption if there is
System.out.println0:
Listlterator<String> litr= array_list.listlterator():
while(litr.hasNext))
itrtr array_list.iterator():
whiletitrtr.hasNext))
String ele -
itrtr.next(O:
System.out.print(ele + "
");
System.out.println():
System.out.print(""Afner modifications, the Array List in backwards is:");
while(litr.hasPrevious())
System.out.println):
Output
The contents of Array List are : AB XY CD PQ EF RS
After modifications, the contents of Array List are: AB+ XY+CD+ PQ+ EF+ RS+
After modifications, the Aray List in backwards is RS+ EF+ PQ+ CD+ XY+ AB+
Different ways to Iterate Over a List
List can be iterated by using two methods which are as followS,
(i) iterator
(ii) sor cach loop.
By Using iterator
Iterator it = list.Iterator()
while(it.hasNext( )
System.out.println(it.next( )):
System.out.printin(a)
Q20.Discuss the differences between HashLIst and HashMap, Set and List.
Answert Nov./Dec.-17(R16,C
Differences Between HashList and HashMap
HashList
HashList is a data structure used to store the
objects
HashMap rtace
HashMap is the implementation
in hash table and list
| hash table.
of map inc
Itis the combination of hashmapand doubly linked ist.
It has kcy valuc pairs.
- tis same as that of hash table, but its not Jnchroniz
syn
3.lt also has key value pairs contains values bused oni
theke
It stores the data in array and dictionary/hash-map. 4. Itstores
data into multiple singly linked list of
entres
Ist
Theselists are registered in array
of ent
Look for tho SlA GROUP LOGO Y2 on the TITLE CoVER
before you buy
UNIT-4 The Collections
Framework (java.util) 4.13
Set and List
pifferences Between
List Set
class ForEachExmp
Output
Values are
2468
Sum of all values: 20
iterated in
it, set of objecis are
A Dove example, the for loop used is simple and short than the iterator. By using the
ard direction and the contents of it are not modified.
SPECTRUM
ALANHO
JouRNAL FOR ENGINEERING STUDENTS SIA GROUP I
4.14 CLASSES, COMPAR
INTERFACES AND
MAP
4.5 suitable examples.
map interfaces with value, which may ren
be cated.
Q22. Explain has its
associated
a given key, An i
Som,
unique and value tor
is find a
Answer: key/value pairs. Each key object. Maps allow to 1or-each styie 1or Iloop cannot be be used
wi
that stores value are Thus,
Amap is an object be null. Each key and through a map.
and values tocan to cycle
maps allow keys not obtain an iterator
maps is that, they
point about
maps
map interfaces,
There are four
. Map
2. SortedMap
NavigableMap
3.
Map.Entry. supplied., Map
4
one value. When the key is
. Map Interface
key/value pairs. It will not allow duplicate
keys. Each key
null keys also.
maps to
Ortput
Number of clements in
map:5
Keyvalue pairs are:
4-Four, 5-Five>
<-One, 2-Two, 3-Three, is a Map
contain=
Interface extends Map interface. A SortedMap supplying
SortedMap clements can be sorted. It the ordering also by
Map where User can specify
It is just a sorted version
of natural ordering.
order. They are sortcd based on keys
the elements in ascending
Comparato.
Following is the class signature,
extends Map
public interface SortedMap
below table,
Methods
SortedMap interface are as shown in the
The methods defined by the Description
nu
Method invoking SortedMap object. It returns
comparator of the
Comparator<?super K> comparator() lt retums the ordering.
map objectsis invoked using natural
il invoking Map object.
K firstKey It returns first keyofofinvoking Map object.
key
lastKcy)_ It returns last
SortedMap object that contains a set of key/value
pairs whose
lt retums a
SorledMapK, V> subMap(k star, end)| or equal to 'start' and less than 'end'.
k
KCys are greater than pairs whose
SortedMap object that contains a set of key/value
SortedMap<K, V> tailMap(K start) It returnsa
'starn'.
keys greater than cqual to
or whose
object that contains a set of key/valuc pairs
a SortedMap
t returns
SortedMap<K, V> headMap(K end)
keys are less than 'end'.
Table: Methods in SortedMap Interface
Pregram
pol java.utii
plc class SortedManlDemo
4.16
Tueey Five"k
s p2,
is:smap.firstKey{O):
loaes key n the sortedmap smap.lastKey( ));
Sysiem.opriia"he map is :" +
iy valur in the sorted
System cepriethe highest are :in" smap);
+
Octpot
sortemap is:I
he lorwest key in the
the sorted map is: 9
the bighest ky valoe in order are
che lowest ky values in
the sorted map in increasing
9=Nine>
-One, 25-Twenty Fve. 7-Seven,
closely match
NavigableMap Interface retrieval of (key, value) pairs that matck
is derived fron SortedMap. It supports the
The NavigableMap iterface
1o the given key or ken table,
methods defined by NavigableMap interface are as shown in the below
The
Description
Method for the smallest key, which is greater
than or equal|
Map EntryK, V> ceilingEntry (K object) | Searches the map object it is found
the entry for the smallest key, if
to the given key. Returns
Otherwise, returns null.
which is greater than or equal
Searches the map object for the smallest key,
2. Kceiling key(K object) entry for the smallest key, if it is
found.
to the object. Then, it returns the
Otherwise, returns null.
are in decreasing
Returns a NavigableSet whose descending keySet( keys
)
NavigableSet<K>descending keySet( )
order of the keys in invoking map object.
a NavigableMap whose keys and values are in decreasing
order
NavigablcMapk V> descendingMap() Returns
of the keys and values in invoking map object. one in the map.
Returns the first (key, value) pair whose key is the smallest
5 Map.Entry K, V> firstEntry()
Searches the set for the largest key that is greater than the given object
higherkey (K object)
6.K Returns the largest key if it is found. Otherwise, returns null.
K, V> lastEntry() Returns the entry that has the largest key in the map.
7. Map.Entry a NavigableSet that has the keys of the invoking map.
Returns
NavigableSetK> navigableSetkey() m
Map.EntryK, V> pollFirstEntry() Returns the first entry that has the smallest key and removes it fom the
9.
Retums null if the map is empty.
Returns the last entry that has the largest key and removes it from une
10. Map.Entry<K, V> polllastEntry()
Retums null if the map is empty
It searches the map to find the largest key, K ie., lessthan or equt a
11Map.EntryK, V> floorEntry(K object)
an object (K s object). It returns the entry for the largest key when is
it
Program
mport java.util. ";
java.util.concurrent.";
import
public class
NavigableMapDemo
new
TreeMap<Integer, String>):
lavigableMap<lnteger, String> nmap
=
Output
The Navigable map in descending order is
(5 Fall, 4 Autumn, 3 Rainy, 2 Winter,I = Summer)
Tbe first etry in the Navigable map is: I = Summer
The last entry in
the Navigable map is 5 = Fall
.
Memovingthe first entry: 1 Summer
Peovingthe last cntry:5 Fall
The Navigable
tmap in descending order is,
4 Autumn, 3- Rainy, 2
Winter).
wETROM AUAN-ONE
JoURNAL FOR ENGINEERINO STuDENTS
SIA GROUP
TU-HYDERAA
JAVA PROGRAMMING JNTU-HYDES.
4. Map.Entry Interface
The Map.Entry interfar an inner ckasafMap that alkws programmers to nrk
is
wth eah enty in a map
The methods defined by the Map Entry intertacr arr as shown in theeow ta*
Method Deseription
boolean cquals(Objct objort) Retuns true if the given objvt is a NMarEnry ohjort wdosoe key
matrhes nith the key and vahr ot the imvuking objort.
and
v
k getkeyO Returns the key of the invuding NMap Entr Objort.
getValuc() Returns the vatar of th invukmg NMap Entr Objoct
int hashCode( ) rnuns th hah tomvudr VMapEnuy objnt
. V setValue (V valu*)
lt i
Scts the vahlue of the imuding NMap.Entry objat to the given valuct theous
clast'astExrptin it the given valuc is ot the cornTOe for the in
Map odjort and tlegalArgumentEeeption it thervIs any prtlem u
the given value. A NullPonterExreption is thown it the ginen vahe
null and the invoking Map odjart nstrivts nullvahes. It throus Unemn
OperationEeption if the invoking Map object cannot he chang
3. Wednesday
4. Thursday
5. Friday
6. Saturday
7. Sunday.
Q23. Discuss any two Map classes.
Answer :
There are many Map classes pre-defined in the Java core classes. 1hat i5, any subcarses exisi for Map imerface Some of
the important classes are as follow,
) HashMap
inierface and user can use all the operations
HashMap is like Hashtable which stores key/value pairs. It implements Map
class is aimost similar to Hashtable,
(methods) of Map interface. It allows null values as well as the null keys. The HashMap
except that it is unsynchronized and allows null values. The order of elements is
not guaranteed
Output
Salary key exists : true
Sita valuc exists: false
Valuc of Rana is nul
No of elements 4
Printing the values using Iterators
cxpenditure 8888.88
distance: 350
Jotm Serena
Salary 9999.,99
TreeMap
TreeMap class cxsends AbstractMap and impien ScrtedMap. 1his class stores
Trerap the elements in ascending key
aurdng ko
Dorted the natuzal order based on the keya [he order can be changed by
supplying a comparator a
Tac mebods arr o syDNchronizrd *
Csnstrurters ni eh
eepty
TreeMapt : epty TrecMap sorted sper the key's natural order(ascending
order).
TreMap(Map m1): r creates a TresMap bjas with the ciements af anothet Map class as pet key
Ary natural
orer
TreeMapCemparstur tomp} E Ea py terAtap object with the sortine
ting order of the Coemparatt sp*
e
TrecMapslnteger,String>);
TreeMap<Integer, String> map=new
map-put(100, "Maths");
tf zott
map.put(96, "Science");
map.put(95, "Social");
map.put(93, "English'"); # 1orrtget
for(Map.Entry m:map.entrySet0){
System.out.println(m.getKey()+ *:" +m.get Valuc));
Output
93:English
95 Social
96: Science
100:Maths
why is it used?
Q24. What is Comparator interface and
Answer:
to compare
Comparator Interface
means the same. In Java, Comparator is used
comnpares two items of data. Java also
In general, a comparator
fwo stored objects in a Set or a Map etc. a data structure.
in which order we want the sorting of the objects of beloreC
java.util.Comparator interface is used to dictate sorting order means alphabetical order-A
he a natural sorting order. Natural
we want a dillerent order, then
we
enerally, Comparator is not needed if there's sorting order, but if
2 etc. A TreeSet or a TreeMap, by
default, gives a natural
belore
require comparator. a TreeMap or TreeSet
consiruclor. it
order, as parameter to
which defines the sorting
Oser can pass a Comparator object,
ennes two methods - compare() and equals().
public int compare(Object obj1, Object obj2)
public boolean equals(Object obj).
depending upon the paramcters passed. O is returned winebo
compare( ) method takes two Objects and returns 0, 1,-1
objects are same. If first object is greater than second, returns else -1.
1
we aO no
Oherwise, it returns false. Generally,
2.
method returns boolean value true, if both objects are same.
s
VerTide this method because an implemented concrete method is inherited from
Object class.
025. What is Comparable Comparator interface? Differentiate between them.
and Nov./Dec.-18(R16), Q9(b)
Answer:
Comparable Interface
Comparabie untcta
objects cPrDie interlace allows the comparison of objects ofa class. The class that implements
s can be compared. Comparable interface can be declared as,
interface Comparable
<T>
Where, Trepresents the object
type being compared.
objects ol nc cass
The method
The
nerlace
method is declared
declares a method called compareTo( ). which can be used for ordering the
as follows,
SIA GROUP
ECTRUM ALL-ING
J0uRNAL FOR ENGINEERING STUDENTS
JAVA PNOonAMMING 1JNTUIYD
YDEnAMAD
4,29
nt eompnte ltl olject)
reso, a negntive vnlie of n poeitive vølhe
Thla metinl eompates thhe invoking oject with olect nnd retns
en I the values nte equnl.
Nepative vnlue - If the invoking olject
han a lower value,
P'ositive valve If the invoklg nlbject hne a lorger value.
In Javn, sevetnl claeses inmplement the (umpun abte nternce. 1hey are 11yle, Character, Doilble, Float, hont, Loa
andd Intege. All these elasses delines n compune
l
) metiod tri
Compnrator Internee
Fof answer reler Unit-1V, )24
Differenees between C'omparalble nnd
Compnrntor 1nterface
2.
is available in jnva langfpack.age H avnilableinjavn.utilpackage
contains conpare lof metlod to sort tho ele-|
ments/objects 2.It contains Compare() nethod to sort the elementd
Jecta
. It prrvides a natural ot single sorting onder Itprovides unturnlo multiplonorting order.
|Compnrable type elements can be sorted by using 4, Compatntor typo olecnts can be sorted by uslng collec
collectioms Sorl(Iist) snethod
tions, Sort (1.ist, Comparator) method
It makes changes in the originnl
class, It does not make any chnges in the orlginal clasg.
It isdeclared ns,
tinterface
isdeclarcd as,
interface comparablo <
comparator<
O26. Uslng comparator wrlto a
Java program to sort a troo sot In a rovorso
ordot.
Answer1
immi java.util."
1 Smplermet Comparator interfnce
class MyComparator implements Comparator<Strings
String s1, s2
s str;
2str2
l compareTod ) invoked by s2 reverses the
tree set
return s2.conpareTofsl ),
claes RevireeSet
Output
Shazia
Rubin
Haseena
Ashraf
Ameer
a27. What are collection algorithms? OR
in Collections Framework?
Discuss.
algorithms implemented
What are the common AprillMay-18(R16), Q9(a)
implementation class).
Answer is algorithms (the others are interfaces and
the collections framework Algorithms can be used with
collection
One of the components of provided by the Java collections.
functionality as algorithms. These
The algorithms are
pieces of reusable
many static methods, which are commonly known
classes and map classes. The
Collection class contains manipulations.
collections classes for data generics are added.
staticmethods can be applied to existing algorithms, especially
the already
added many methods (like checked methods) to strings, we can add only
strings to a data structure.
JDK 1.5(J2SE 5) the generic to
in a data structure. That is, if
we set
is to be performed, The
great majority
Gencrics give type-safe elements on which the operation
collection classes.
argument as the collection class them operate on other
The static methods take first on List instances, but a few of
of the algorithms provided by
the Java platform operate collections:
following operations on
The algorithms are helpful for the
(a) Sorting
(b) Shufling
(c) Routine Data Manipulation
(d) Searching
(e) Composition
(0 Finding Extremec Values
collection are as follows,
Some of the operations performed on
(a) Sorting
The sort algorithm arranges a list of elements in ascending order.
Example
program.
command-line argument to the
The following algorithm sorts the list passed as
import java.util.:
public class SortDemo
Output
RaM GROUP
ALLANOME J0URMAL FOR ENGINEERING
STUDENTS S
NTU-HYDERA
JAVA PROGRAMING IJNTU-HY
4.24
Shufling are never sorted but ines.
(b) does. That is, the eiemenis
change. orders the elements randashun
the reverse of whut sort
The shufle algorithm does
lt Nadilen
that is shulling will atd
times, diflerent outputs are obtained;
implemenling games ol chance. For examnle
executedat diflerent useful in
sting solwuld
permutations. This algorithm is lor generaling lest
cases while testing soltware. bese
times. It takes all possible a deck. A lso, it's useful
cards represcnting
to shufllea list of playing
Example
File Name: ShuflleDemo.java
import java.util.":
public class ShulleDemo
=
new Array List( ):
List list
list.add("red"):
list.add("purple");
list.add("yellow");
Collections.shule(list):
System.out.println(list):
Output
C\snr>java ShuffleDemo
Lpurple, red, yel lowj
C:\snr>java shufflepemo
yellow]
[purple, red,
:\snr>java shuffledemo
(yellow, red, purp lej
shuffleDemo
:\snr>javayellow,
[purple, red]
:\snr>java shuffledemo
[purple, red, yellow]
:\snr>javared, shufflepemo
[yellow, purplej
as
oojeCts are taken - red, purple and yellow. When executed at different times,
In the above program, three
string
(vi) min
: finds the minimum element of a list.
Jfinds the maximum clement of a list.
(vii) max
LOo' for the
SIA GROUP LOGO R on the TITLE COVER
before you buy
Framework (java.util) 25
NT-4 The Collections
ample don
reverse of the elements ad minimum and maximum operations are
Ta program,
the following
MinMaxReversejava
e Name:
java.util.":
import
MinMaxReverse
public class
main(String[] args)
public static void
List list=
new ArrayList( ):
list.add(new Integer(10));
list.add(new Integer(20)
operation
list.add(new Integer(30)); /reverse
System.out.println("Original elenments:" + list):
Collections.revese(list);
and maximum of elements
System.out.println("Afer reversing:" + list); // retrieving minimum
+Collections.min(list)):
System.out.println("inMinimum is"
System.out.printin("Maximum is" +
Collections.max(list);
Dutput
C:\snr>javac MinMaxReverse.java
C:\snr>java MinMaxReverse
original elements: [10, 20, 30]
[30, 20, 10]
After reversing:
Minimum is 10
Maximum is 30
package.
Q28. Describe Arrays class in Java.util
Answer nmethods to do operalions
introduced from JDK 1.5 version, which provides many stutic
Arays is a class injava.util package searching. Earlier to the introduction of Amays, these
operations were done from
0n aTays like filling, comparing. sorting and
SCTatch. Now, the coding has become casier with Arrays.
Many static methods are overloaded.
System.out.print(marks[i]+"*")
System.out.print(marks[i]+" ");
Output
CrWINNT Syslem32\cnd.exe
c:\snr>javac ArraysMethods 1.java
C: \snr>java ArraysMethodsl
Both arrays are egua e
Dr1ginava lues: 50 30 20 10 40
va ues Atter sorting: 10 20 30 40 500
Index number of 30 in the sorted array: 2
Look for the SIA GROUP LOGO on the TITLE COVER before you buy
E LEGACY CLASSES AND INTERFACES DiCTIONARY, 427
4 STACK, VECTOR
HASH TABLE, PROPERTIEs
Enumeration Interface
structure(this
The Enumeration interface allows to iterate through a list of sequentially stored elements in a data interface
must be implemented by the data structure). It is replaced with lterator interface in Collections framework.
Methods
It provides two abstract methods using which iteration can be done.
hasMoreElements( ): It returns false when no elements exists
nextElement(): It retrieves the next element in the enumeration.
Method signatures of the above methods defined in the java.util package are as follows
public abstract boolean has MoreElements();
public abstract java.lang.Object nextElemen();
I/Simple snippet of code illustrates how iteration can be done.
Enumeration e = vect.elements( ); isi n
while e.hasMore Elements( )
System.out.println(e.nextElement( ));
iciv.rfurns
elements( ) method of Vector class returns an object of Enumeration interface. The hasMoreElements() returns true as long as
Cetmenis
are in the Enumeration object. Ifal
elements are exhausted it returns false and the loop terminates. nextElement( ) retus
object stored in the Enumeration interface object.
0. What is a Dictionary?3
Answer
3
Dictionary is an abstract class in the java.util package and operates much like Map interface. Like Map. if stores the
ts as a list of key value pairs. It has the following methods,
tlements( ): The element() method returns an enumeration of values in the dictionary:
Syntax
Enumeration < v > clementsO
Where, v is the type of the valucs.
SVECTR
RUM ALLAH-ONE JOURNAL FOR ENGINEERING STUDENTS, SIA GROUP
JAVA PROGRAMMING [JNTU-HYDERABt
28 value of the grven key. It returns null object if the
2. get(): The get() method returns the object that has the kev
in the dictionary.
Syntax
Vget (Object Key)
3. isEmpty(): The isBmpty() method returns true if the dictionary is empty. Otherwise, it returns false.
Syntax
boolean isËmpty (2
Keys(): The keys() method returns an enumeration of keys in the dictionary.
Syntax
Enumcration < k > Kcys()
Where, k is the type of the keys.
5. put(: The put( )method a
inserts key and its coresponding value in the dictionary. It returns the previous vaue of
key if the key is already in the dictionary. It retums null, if the key is not in the dictionary.
Syntax
int size(
From the above methods it is obvious that, a dictionary
object is much like a Map or a List object
Q31. Describe Hashtable with an
example.
Answer : Q8
Model Paper
Hashtable
Hashtable is a concrete implementation of the dictionary
class. It also stores information in the form key val pas
but in a hash table. To store a pair, first a hash
code is determined. After which, the hash of
are stored in the hash table at that index. code is used as an index and un
Constructors
Hashtable( ): It creates a hash table with default size
of 11.
Hashtable(int size): It creates a Hash table with the
specified size.
Hashtable(int size, float fillRatio): It creates a hash
table with the specified size
and fill ratio between 0.0 an1.0
Hashtable(Map m): It creates a Hash table with the
clements in map m.
Hashtable was a part of original java.util package.
However, with the introduction
implement Dictionary as well as map interfaces.
are the legacy methods defined by Hashtable.
Thus, Hashtable has the methods
of collections, Hashtable
of both of these intertace
oe
Methods void clear( ): This mcthod first resets
2.
the hash table and then empties it.
object clone( ): This method duplicates the
invoking object and returns the
thereiss
3. boolean Contains(Object value), boolean same.
value in the hashtable that matches the
contains Value (Object value): These methods return true "i"
given value. Otherwise, they return
boolean containsKey(Object key): This false. g
kcy. Otherwise, it returns false. method returns true if there is some matchesth
key in the hash table that ma
Look for the SIA GROUP LOGO on the TITLE COVER before you buy
Framework (java.util)
.4 The Collections
numeration <V> clements( ): This method retu an enumeration of values in 4.29
the hash table.
V get(Object| Key): This.method returns the object that has the value corresponding to the given
obiect if the key is not found in the hash table. key. It returns a nutl
boolea isEmtpy( ): This thod returns true if the hash table is empty. Otherwise, it
retuns false.
enumeration <K> keys(): This method returns an enumeration of the keys in the hash table
.K kev. V value): This method inserts the given key and vahie in the hash table. Then,
it returns the previous value
of key if the key is already in the hash table. It returms a null object, if the key is not in the hash table.
the
void rehash( ): This method first increnses the size of the hash table and then rehashes all the keys in
the hash table.
y
remove(Object key): This method deletes the given key and its corresponding value from the hash table, and returns
the deleted value. It returns a null object, if the key
is not in the hash table.
Object k e.nextElement( );
Object v ht.get(k);
System.out.println("Key:" +k +"Value:" + v;
5.
that is connected to the inStreanm. This This method takes a property
list as input
method throws 1OException, and InvalidPropertiesFormatExceptno
Enumeration <7> PropertyNames( ): This incthod
retums an enumeration of the keys
from
an an
XML
on e
present in list and delau
Look for the SIA GROUP LOGO on the TITLE COVER belore you buy
NIT-4 The Collections
Framework (java.util) 431
abiect setProeprty(String key, String value): This method associates the given value with the given key, and returns
revious value of the key, if the key is already present. IHowever, it returns mull if the key is not present.
String descp): These
nid store(OutputStream outStream, String desep), void store(OutputStream outStream,
to that is connected to
vde frst write the given string description and
an 1OException on
then wTite
error.
the property list the output stream
String str
Enumeration e = p.keys( );
while(e.hasMoreElements( ))
Output
WIISysten32 cmdene
re\classes java.vendor=sun1crosystems
. Inc. ,3
ri.bug=http://java sun.Comicg-D1nDugrePort.cg
eLittle, sun.cpu.endian=iittle, sun. desktop=wi nd
Niagara
Naga is famous tor Irani Haleem
BawarC isfamous for Biryan
BTueSea 1s.1sfamous
famous for
for Tea
Tea
Adabfor Kaju Roti
Hotel
PECTRUM
ALLIN-ONE JOURNAL FOR ENGINEERING STUDENTS SIA GROUP
TU-HYDERARAO
JAVA PROGRAMMING JNTU-HYDERA
4.32
Constructors in Hashtable Class
1. Hashtable( ): It is a default constructor.
2. Hashtable(int s): This constructor creates a hashtable of size specified by the parameters. Basically,, the the defauh
det.. szx
hashtable is 11.
3. Hahtable(int s, foat fr): This constructor creates a hashtable of size s and a fill ratio specified by fr. The Therrange of
0.0-1.1. The default fill ratio is 0.75. f
Hashtable(map<cextends key,? extends value>k): This constructor creates a hashtable that is initialized with thee
4. elcten
specified in k.
Legacy Methods Defined by Hashtable
In addition to the methods defined by Map interface, hashtable defines the following legacy methods
1. void clear( ): This method is used for resetting and deleting the hashtable values.
2. object clone( ): This method is used for returning duplicate value of the invoked object.
3. boolean contains(Object valuc): This method is used for returning boolean value. It returns true if the given value mata
with the existing value in the hashtable, otherwise it returns false.
4. enumeration svalue>elements( ): This method is used for returning numerical values present within the hashtable
5.
a35.
:
void rehash( This method is used for maximizing the hashtable size, and also for rehashing the corresponding kou
Describe the concept of stack class. Also write an example program.
Model Paper<4, 08
Answer:
Stack Cass
Stack class is a derived class of Vector class. This class inherits all the methods defined by Vector class.
Syntax: class Stack<e i>
In the above statement, el is an object that type of clement contained in a stack. The various methods used by suak
of saa
push). pop(). peek( ) and search(). This class implements the use of Last-in-first-out stack mechanism. The constructor
class.
Stack)
The above constructor is a default constructor that creates an empty stack.
Methods of Stack Class
1. empty( ): This method returns true if the stack is empty.
2. peek( ): This method returns the element which is present at top of stack.
push( ): This method adds an item at the top of the stack.
. pop( ): This method removes and returns the topmost element of stack.
5. search( ): This method searches the desired element from the stack and returns the number of pops operations tobemad
Programn
import java.util.
public class StackEx
Ostpst
clement of tack [1, 2, 3]
rheecnts removed froem stack.
3
Look for the SIA GROUP LOGO O on the TITLE COVER before you buy
UNIT-4 The
Collections Framework (java.util) 433
How an Hashtable
How can change the itorator? Explain.
036.
Nov /Dec 17(R 10), a(
Answer
Hashtable ddepends upon the implementation
of map interface. It provides the optional map operations and even allows
valucesand null key. It will not
assure whetheri the order remains constant. The ilerators that ate returned by this classes
when the map is modified
view methods" are fail fast. The iterator will throw ConcuTentModilicationl'xception
denull a
collection view othe: than its own remove or add mecthods. The ilerator will fail quickly
using the method
STcturally.after the iterator is created while modified concurrently
in future. This happens it is
of going for arbitrary non deterministic behavior
ad cannot be assurcd in the presence of unsynchronized concurrent
modification. The
fast behavior of the iterator
The fail and concurrentModificationException. Such behavior of the iterators must
be used only for deticcting
fast iterators will throw the
fil
bugs.
te
037. Explain about Vector class.
Answer:
Class class. The two
class has similar feature as that of ArrayList
Vector
derived class of AbstractList class. This
Vector class also a
is synchronizcd and it defines some specific
major differences between the vector class
andArrayList class is that the vector class are as follows,
present in Collection framework. The class declaration of Vector class is
hpe methods that are not
class vector<E1>
clement stored.
In theabove statement, the object El defines the type of
size I0.
1. Vector(): The constructor creates a default vector of
the given size.
Vector(int size): This constructor creates a vector with collection co.
contains the clements of the specificd by the
Vector(collection co): This constructor creates a vector that namcly size and
Vector(int size,int increment): This constructor creates a
vector of given size. It takes two paramcters
specilies
ofelements that can be allocated to vector and size
ncrement. The parameter increment specifies the total number
the initial capacity of vector.
Methods of Vectors Class
at of the vector. It also increments the
.addElement(object EL): This method is used to append the given element the end
size of the vector.
Capacity( ): This method is used to return the vector capacity.
object.
Contains(object EL): This method returns true if the vector contains the specified
are contained in the vector.
ContainsAll(collections co): This method returns true if the elements of the given collections
at the specified index.
elementsAt(int index): This method returns the elements that are present
the vector size.
Ensure capacity(int minimumcapacity): This method is used to set he minimum capacity to
at the specified position in the vector.
Get(int index): This method is used to return the object present
at with the specified clement.
setElementsAt(object e, int index): 1his method is used to replacc the clements the givenindex
6, What are similarities and differences betweon ArrayList and Vector? Explain. Nov./Doc.-18(R16), Q8()
OR
Differentiate between ArrayList and a Vector. Why ArrayList is faster than Vector? Explain.
Rder Only Topic: Diferencer berween Arraylist and Vector)
Answer Nov.Doc.-17(R16), Q8(a)
ArrayList Vector
1.ATayL.ist class will inherit the leatures of Abstract 1. Vector class will inherit the features of abstract lis
List class and List interface. class
It is not synchronized. synchronized.
2. T i
can ncrease the size of array upto 50% when num-|
S
ber of elements are more than its capacity.
3. tof can increase the size of arTay upto
elements are more than its capacity
100% when 1
umber
4. I1 is not a legacy class.
4. It is a legacy class.
5. It is fast
because it is not synchronized. 5.|It is slow because it is synchronized.
6.| It makes use of iterator interface for traversing the| 6. |It makes use ol enumeration interiace tor traversing th
elements. nmakes use
elements. It event of iterator.
em
ArrayLSt is faster than vector because it is not synchronized and is added as a choiee in single threaded acces
he
ronment. It can be used in multithreaded environment when multiple threads are reaçding values Irom
ATayList. Vector is slow
compared to ArrayList because it is synchronized. Vector contains other threads in runnable or non runnablc state
in multithreading
environment until the current thread releases the lock of the object.
SiringTokenizer Class
StringTokenizer Class separates string/text into tokens delimited by ls,\t, \n, \r and \f. It takes a string as input and parse
into token. This method is known as parsing Stringlokenizer provIdes lexer/scanner since it is the initial step in the proce
parsing. I1 provides the following constructors,
Constructor Description
SringTokenizcr(String s) t takes the string to be tokenized
as a parameter ana
nsiders
white space as default delimiter.
StringTokenizer(String s, String delimiters) It takes the string to be tokenized as a parameter and pecihes
aiso
delimiter.
StringTokenizer(String s, String delimilers,t takes the string to be tokenized as a parameter and also spi
boolean delimAsToken) a delimiter. In addition
to it, it returns s tokens if the v
delimAstoken is true.
=
StringTokenizer class offers the following methods,
21 3
Method Deseription
countTokens() It is used to return the number of1okens enize
1int objecl. available with Sinus
)
2. boolcan hasmoreTokens( T is used to return irue as long as
object and false when no more more tokens exist with Su*
tokens exist. *
booleard hasmoreElements() It is used to return
3 true elements exist
StringTokenizer object and as long as morere elemc CXIST.
false when no more
4. Object ncxlElement) It is used tokens
to returns the immediate token as objecl.
It is used to returns
String nextloken(O_ theimmediate token as siring:
String nextToken(string delimiters)
It is used to returns
the immediate de
string specilied token asstring
string ana s the
and sets
by the delimiters.
System.out.println(st.nextToken( );
Output
Number of toakens:8
Hello World
How
Do You
Do
All Are
Okay
Thank
You
is the list of
he first parameter of the StringTokenizxr constructor takes the string 1o be parsed and thc second parameter
he list of delimíters used are whitcspace, comma, semicolon and forward slush.
49. Explain about BitSet.
Answer Model Papor-4, a0(a)
DSet class creates an array that can storc the bit values. It implements the Cloncnble interlace.
Constructors
Bite) 13
Bnsed int s)
The bit sct of the sizc specificd by
"S, The sizo
creates a default bit net. The vecond constructor creates a
2y iructor
ow dynamically as needed. By desault all bitd urc initinlizcd to zcro,
time dgtTime ):
System.cutprintin(Number of milliseconds since.
1/1/1970:\n" +time):
Output
Fir Nov 08 11:53:41 IST 20199
11
Oupat
53
date and time is
Tae cure
:
41
F Nov 0s I1:4857 1ST 2019 10
Nuer ofmilliseconds since. 1/1/1970: S
LSI93937349 5
Comparisoa of Dates 119
Two date odjerts canecompard in three ways.
1573194221974
1, 1970 using get-
Fad e me elapsed since Jnuarthen compare their Q42. NWrite about Calendar class.
T ) for both the objacts and Q9(b)
AnsHer : Model Paper.
Us
e methods beforemethod.after(Thisandmethod
). equal ().
)
is defined
Calendar
The calendar is an abstract class. It provides a set of
Using e compareTo)
implemented by Date class. methods to manipulate the date and time. The subclasses of cal-
e cooprable interfece
endar class provides the specific implementation to the abstract
methods defined by calendar to meet their own requirements.
rogan v demonstrate the Date class For example, GregorianCalendar is a subclass of calendar class.
The calendar class will not define its constructor. Thus
an object of the abstract calendar class cannot created. The
puba ciass DaneDem
calendar class has several instance variables. These are declare*d
as protected. They are.
pbic seic void main(String args[) fieldsSet: It is a boolean variable that indicates whether
the time component is set or not.
fields: It is an aray of integers that contains all the time
Dane d= pew Date
components such as year, month, day. hour, time and
Sysemoprintln d: Second.
Fi Nov. os 1153.41 GMT-05 30 isSet: it isa boolean aray that indicates whether a spe
System.caprintn(dgetHours( ); prints II cinc time component is set or notL
time: It is a long variable that contains the curent time
extract mintes for this invoking object.
System.oaprintinídgetMinutes()x prints 53 isTimeSet: It is a boolean variable that indicates whether
extract seccods the curent time is set or not.
RM ALLAN-ONE JOURNAL FOR ENGIMEERING STODENTS SIA GROUP
JAVA PROGRAMMING (JNTU-HYDER
4.38
The Calendar class also defines some integer
constznts used to ening or EETing the components. These are
MARCH SUNDAY DAY_OF_WEEK_IN_MONTH DATE
AM
PM APRIL MONDAY WEEK_OF_MONTH ALL STYLES
MAY TUESDAY WEEK_OF_YEAR LONG
AM_PM
HOUR JUNE WEDNESDAY MONTH SHORT
HOUR_OF_DAY JULY THURSDAY YEAR
Look for the SIA GROUP LOGO V2 on the TITLE COVER before you buy
439
INIT-4 The
Collections Framework (java.util)
Program
Calcndar class
program to illustrate the
dava java.util.Calendar;
inport
DateAndTime
class
}))
main(String args[
public static void
Calendar.getinstance( );
Calendar cal =
Output
BltSet
Class
For answer refer Unit-Iv, Q40.
Calender
Clas
For answer refer Unit-IV, 042.
Q44.
Wite short notos on following collection framowork classes.
(a) Random
(6) Scanner
Anawer
a) Random
andom class generates a sequence of uniformly distributed number called pscudo random numbers.
eBtructors
of Random Class
Om):This constructor uses current time as a starting value to create nand generate number.
R
dom(long s): This constructor generates a random number by taking the value specified by user as the starting value.
RaM ALAM-ONE oURNAL FOR ENGINEERINO STUDENTS SIA GROUP
JAVA PROGRAMMING LJNTU 4HYD
4.40
Methods of Random Claes
returns the nezt boolean rardom number.
boolean nextBrolean(): This mcthod generato
valuel This method fills the values with the values that are randomiy geDeratod
2. void next#ytes(byte |):
double random number.
3. double nertDouble(): This methiod returns the next
float random number.
4 loat nextFloat( ): This method returns the nez!
Cjaussian random number.
5. double nextCaussian( ): This method returns the nez!
number.
6. int nextint( ): This method returns the next int random
int nextnt(int n): This method returns the next int random
number ranging from 0 to n.
B. long nextLong( ): This method returns the next Jong randorn numbers.
9. void setSeed(long newseed): This method sets the newseed specifies.
Example
import java.util.Random;
class Demio
value= ro.neziGaussian( );
total+ value;
doublex-2;
forint j = 0j<10j++)
x+ 0.5,
if(valuex)
arril
break
System.out.println("Average:"+{otal/50);
forint i-0,ic10i+1)
s ua 1dens ceraiat,ro 2s01
Sortint j -
arr|il: j-0j-
System.out.printin(**
System out.printin
Look for the SIA GROUP LOGO on iho TITLE COVER before
you buy
UNIT-4 The Collections Framework java.util)
Scanner
Scanner class is used for reading the formatted imput and then converting it into the binary
lormat. It is capable readingof
n npes of data such as numeric values, strings, data ctc. tTom sey board, click nle ete. lt reads input from the console, or anY
e that implements readable interface. It ts a member java util package and hence must be imported to
ol purposeclass wherever
the
is used. The import statements "import java.util.;" or "import java.util.scanner:" must be used for this
Generally, the steps to use a Scanner class are as follows,
Check whecther any particular type of input data is available or not by using the hasNextX method. Here, X represents the
Ope of data required.
in case ofavailability of input, call any one of the nextX methods of Scanner class and read it.
Repeat the same procedure till the complete input is read.
Scanner elass provides various constructors.that take data source as parameters. Following are some of them.
Constructor Description
1
Scanner (File source) Constructs a neW Scanner that generates values scanned Irom a specified
file.
Scanner (InputStream source) Constructs a new scanner that generates values scanned Irom the specified
input stream.
Seanner (String source) Constructs a new scanner that generates values scanned from the specified
string.
In addition,scanner provides vanous methods. Some of the methods of this class are as follows,
boolean hasNext( ): This method returms true if a token is ready to be read, otherwise returns false.
it
string next( ): This method retums the next token of any ype as input source.
boolean nextBoolean( ): This method returns the next token boolean value.
byte nextByte( ): This method returns the next token as byte value.
foat nextFloat( ): This method returns the next token as float value.
. void close( ): This method is used to close the scanner.
P.
boolean hasNext(Pattern P): This method returms true if the next token matches with the particular or required pattern
boolean has Next(String P): This method returms true if the next token matches with the pattern in the particular string.
value.
boolean hasNextBoolean(): This method returms true if the next token present in the input can be rwritten as boolean
9. a
boolean has NextByte( ): This method netums true only if the next token present in the input can be rewritten as byte value.
10 a
boolean has NextDouble(): This method retums true only if the next token present the input can be rewritten as a double value.
11. i
boolean hasNextFloat( ): This method retuns true only if the next token present in the input can be newritten as float value.
12 a
This method returns true il he next token present in the input can be rewritten as a integer
value.
boolean hasNextlnt():
14 boolean hasNextLine( ): This method returns true if any other line is obiained in the input.
as a long value.
15 boolean hasNextLong( ): This method returns true it the next token present in the input ean be rewritten
value.
boolean hasNextShort( ): This method returns tnue if the next token present in the input can be rewritten as short
16. a
string next(Pattern pattern): This method is used to return the next token if it matches with the required
17. patterm.
18 double nextDouble(O: This method is used to returm the next token double value.
19.
short nertlnt( ): This method is used to retum the next token integer value.
20 parsers the present line.
sbort nextLine( ): This method is used to return the input in the form of string or scanner
21 short nextShort( ): This method is used to return the next token short value.
2 short nextlong( ): This method is used to return the next token long value.
23, for scanning it in the oquired string.
*aDDer UseDelimiter(String pattern): This method is used to set the delimiting patterm
string nextlLinet ): This method is used to return a string as the next linc of input.
default radix value i.e., 10.
DExtLong( ): This method is used to return a long value as the next token. uses the
It
E
BgDecimal nextBigDecimal( ): This method is used to return a BigDecimal objoct as the
nest tOKCn.
the detault radix
object as the next token. uses
It
mainfString args[)
public static void
Scanner(System.in);
Scanner s=new
System.out.print("Enter ID:");
int i-s.ncxtlnt():
System.out.print("Enter Name:"):
String n=s.next);
System.out.print("Enter Department:");
String d=s.next);
System.out.printn(*The entered details are:");
+d);
System.out.println("inlD is:"+i+ *inName is:" + n+*\nDepartment is:"
s.close();
Output
Enter ID:100
Enter Name : Nikhil
Enter Dpartment:CSE
The entered details are
ID is 100
Name is: Nikhil
Department is CSE:
Q45. Explain in detail about formatter.
Answer
Formatter
required format.
Formatter class provides the format conversions to display the numbers, time and date, strings the
in
additional ieau
functioning of formatter class is similar to the C/C++ printf() function with a small differences and some
Formatter Constructors data
To format the output, user must define a formatter object. The formatter will be operated by converting the
Dui
accessed by the prog
used by a program to the formatted data. The formatted data is stored in the buffer, and this can be
accordance with their requirement
The formatter constructors defined by the formatter class are as follows,
Constructor Description
Formatter() It constructs a formatter object.
new
Formatter(Appendable buf) It constructs a formatter with certain.destination.
an Toca
Formatier(Appendable buft, locale locale) constructs a lormatter with a specified destination ption
Formatter( String Filename) throws FileNotfoundException constructs a formatter with a file. It throws an exce
I
"FilcNotFoundException" if the file is unavailabie
Formatter(String Filename, String charset) throws File- It constructs a formatter with a file and charset.
NotFoundEx ception, unsupportcd encoding Exception oult
Formattcs(Filc outF) throws FileNotFoundException construcls a formatter with a specified output ile, s
unavu able
hrows an cxception "FileNotFound" if file is thatui
stream
FoTTnatter(File outstr) t constnucts a ul strc
formatter with a specified output
receive the output.
Look for tho SIA GROUP LOGO on tho TITLE coVER before you buy
INIT-4 The
UNIT Collections Framework (java.util) 4.43
Formntter Methods
The formatter class defines various
formatter methods and they are as follows,
Method Description
Iis used to close the invoking formatter with this resources used
voidclosc) by the object will get released. An attempt to access the elosed
formatterleads to the exception i.c., "FormatterC losedException'"
used to flush the format buffer. When this method is invoked.
It is
void flush()
the data stored in the bufler will be written to the destination
It formats the arguments and retuns the invoking objects.
Formatter lormat(string Imtstring, object.args)
and returns invoking object. It uses the
Formatter format(local loc, string fimtstring, object..args) lt formats arguments
specified loc for the format.
invoking object for output
loException iolException( ) It returns this Exception when the
throws loException otherwise., will returns null.
it
import java.util.";
class format
})
public static void main(String args[
F.close
Output
Java Formatting basic 5 2.5.
The output can also be oblained by calling out( ). It returns a reserence to an Appendable object
Example
f.forma(9%tM", calender):
%tM is used to display the minutes in a two-character field.
Look for the SIA GROUP LOGo on the TITLE COVER before you buy
UNIT-4 The Collections Framework (java.util)
The %n and %% Format Specifiers
The specifier %n is used for inserting a new line and 6% is used for innerting percent nign
Example
f.format("File is copied upto %n %d %%°", 75);
Minimum ficld-width spccisier is an integer that is used in between % sign and format conversion code. This is shown in
is displayed.
the output screen where the result with spaces
Example
.123
10.456
10.789
In the output, the first line is printed with the given value, the second line and third line prints the valuc with the space
provided in the command.
Specifying Precision
The format specifiers %f, %e, %g and %s can be applied with specificr. It contains a period along with an integer. It is
applied on the basis of the type of data. If the precision specifier is applied to floating-point values with %for e then the number
of decimal places are determined. The default value of precision is 6. When %g is used then the precision determines the count
of significant bits.
Example
The value of %5.2f represents the number that is atleast five characters wide with two decimal places.
Format Flags
The formatter identifies the.collection group of format flags that are used for different types of conversion. The format
flags are individual
characters that are represented with the % in the fomat specification.
The following table represents the format flags.
Example
f.format("1%10.2r", 180.01);
floating-point nurmber
right edge of ficld i.e right-justilicd with the numbe withte
The above statement prints the output on the
decimal places in a 10-character ficld.
The + Flag is used to place + sign before any positive numeric valuc.
Example
f.format("%+d", 250)
Exomple
f.format(%d",-258):
f.format(%d".285);
(c) (Flag
that is given by a sign.
(Flag is used to display negative value with the inside parenthesis
Example
f.format(o(d", - 280);:
(d) O Flag
0 flag is used to display the output with zeros instead of spaces.
Example
f.format(%, .2f", 9876543210.12);
The output will be
# Flag that
akes.Sureoug
t
used with the %f, %e, %x and %0 format specifiers. When # is used with %f and %e then
# lag is
it
specifier then
the o
it
number is a decimal point cven though does not have decimal digits. When # is used with %x format specou
Outpu
will be printed with a hexadecimal number that has Ox prefix. When # is used with %0 format specifier then
printed with a number that has zeros.
Look for the SlA GROUP LOGO on the TTLE CovER before you buy
UNIT-4 The Collections Framowork (java.util)
Upperrase Option
Certain fomat specificrs are required to be in uppercase. They are as follows,
ppercase Format Specifier Description
%A This is used to uppercase the hexadecimal digits a to fas A to F. The prefix OX is con
verted to OX and p as P.
%B This is used to uppercase the true and false values.
%E This is used to display the exponent symbol c in uppercase.
%G This is used to display the exponent symbol g in uppercase.
This is uscd to uppercase the hexadecimal digits a to fas A to F.
oS This is used to uppercase the given string.
6T This is used to uppercuse the output which is in alphabetical sequence.
This is used to uppercase the hexadecimal digits a to fas A to F. The optional prefix Ox is
printt) Connection
is created automatically by using a formatter in print) method. The resullant string is displayed on
em.out Sing
which is the default console. The printi ) mcthod is used
by printStreum and
Writer.