Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

The Collections FRAMEWORK (Java - Util) : Part-A

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

UNIT THE COLLECTIONS

FRAMEWORK (java.util) SIA GROUP

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

public static void main(string args[ D

ArrayList color new ArrayList( ):


Collections.addALLColors, "red". "ycllow", "black");
Colors.forench(system.oul: iprintln);

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

Arays is a class in java.util package introducearOm


I.
Vcision, which provides many static methods
ons on arrays like filling, comparing, sorting ana searcning: Earier to the introduction
done from scratch. Now,
to do
of Arrays, these operations
the coding has become easier wiun Arays. Many static methods are overloaded.
Following is the
class signature,
012. Public class Arrays extends Object
What is
Answer the ssignificance of Legacy class? ve example.

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

clasnon-absiavt) Stoms all types at ojoots(l.IFO onder)


Staok
abstmot vlass Soes keywae pains
Dictionary
Stoms keyAale paiN
Nashtabte olason ahstact)
classqnon altnact) Stores keyalue pais
ortios
Q13, Wrtte any two methoda of dlctonary.

Answert
The two nethats of dictionary aM
elements()
dictionary: Its syntax is,
The clement( ) method retums an cnumeration of values in the

inumerat ion< v > elements()


Where, r is the tyye of the valhues.

key is not found in the


he pet )methad retuns the objoct that has the valuc of the given key.
IU
etums null object if the
dictionary Its syntar is,
V gotodjecthey)

a14. What is the purposo of StringTokenlzer class ? Explaln.


Answer (Model PapeNt, Q1h)I NovDac-17R18), CIA

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.

2 To allow group of collections to work in a similar manner.


To easily extend the collection mechanism.
This ackage detiws
collection framework is defined in most commonly used package called Java.util.pacakage. iuntertiac is a *
The Java
interfaces and also a set of classes called collection classes. The collertions
set of interface called collection this, the Java
are usually defined for implementing collection classes. Beside
onwhich collection framework is build. They They are statie methoxds detinai
collection framework also consists of an important
collection mechanism called algorithms.
imside collection classes for manipulating collection.
a special type of intertace called
lteratr iuntertaee. This
collections framework consists of
In addition to algorithm, a class.
nterface provides a standardized way to
manipulate the element of collection
Benefits Collections Framework
of Java
Following are the benefits of java
collections framework

0 t reduces programming effort.


APls.
(i) It reduces effort for designing new
It allows inter operability among unrelated APl
lt increases program speed and quality
(1)
lt increases software reusability.
new APIS.
reduces cffort for learning and using
,Explain in detail about collection intertaceos. Model PaenN, Q8(a)
Answer:
Collection
Interfaces caled collection intertaces. Ther aw basicall
The collection framework of Java is built So ncces
on a standard
ot collcction framework are as tollow
ica
Some or ne mierces
implementing collection mechanism.
defimed
fo
1Or
1

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

Syntax: interface collection <E1>


void clear(
int size, boolcanadd(E
object) are some O1,he methods of Colleetion interface.
ECTRUM
STUDENTS
6HuAN-ONE JOURMAL FOR ENdINEERING SIA GROUP
JAVA PROGRAMIMING IJNTU-HYDED
ERABAD
4.6 List Interface 1i
2. collection interface and is used to handin a
is generic interface which is derived from list hClemen
This interface a
on the location where they cxist within the
in qucue. These elements
undergo processing based ha
zero-bee
elements.
index. It involves all the copies of
Syntax: interface list<E
objects.
Where, E indicates the type of the list interface.
Epeek( ) are some of the methods defined by the
Element( ),
Dequeue Interface the double ended queue.
3.
from Queue interface and is used to handle
This interface is derived
Syntax: interface Dequeue<E> methods defined by the Dequeue
interface.
first( ), Epop() are some of the
void push(e object) Eremove
hand
4. Set Interface called Collection interlace. They are usually defined for
topmost interface
This interface is derived from the
unique elements present in the set.
Syntax: interface Set<El> index-val) are some of the methods
defined by the Se
index - val) Eremove(int
E get(int
add(int indcx -val E object),
1

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

Atersetting the final Linked list is: Pink, White, Red]


HashSet Class
HashSet class S used to store the collectionn creat.
The HashSet inherits AbstractSet class and Set interface. The e

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

public static void main(String args[ })

HashSet color = new HashSet();


color.add("White");
color.add("Green'");
color.add("Black");
color.add("Blue");
System.out.println("The Hash set is:"+ color);

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

public static void main(String


args[

TreeSet color = new TreeSet( ):


color.add("Brown");
color.add("White");"
color.add("Yellow");
color.add(Cyan");
System.out.println("The tree set is" + color); 9ai, me

Oatput

The tree set is : [Brown, Cyan, White, Yellow]


Priority Queue
priority based queues.
This class is derived from abstract queue class to implement
Syntax
class Priority Queue<E1>
Coastructor

Ihe following are the constructors defined by priority queue,


Priority Queue()
Priority Queue(int capacity)
Priority Queue(comparator<? super E1>comp)

oity Queue(int capacity, comparator<?super El>compl)


fiority Queue(collection<?extends El>co)
Priority Queue(priority
queue<?extends E1>co)
. Fhority Queue(sortedset<?2extends
Array Dequeue
El>co)
This cla
s is derived from abstract collection class for implementing Dequeue Interlace
Syntax
class
ConstructorDequeue<E1>

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.

4.3 ACCESssING A COLLECTION VIA AN ITERATOR, USING AN ITERATOR


219. What is Iterator and Listlterator?
OR
What is different between-Iterator and Listiterator? Explain different ways to iterate over a list.
Answer Nov/Dec.18(R16), QS)

Iterator
In compuner vocabulary, iteratoT means an object with which user can travel all through a range of clements. In Java

lterator is an interíace that allows programmerS to access a collection.


Following is the signature of iterator interface.
Publie Interface Iterator
Enumeration interface is replaced by Iterator in collections framework. The advantages of iterator over Enumeration art
It makes the caller to delete the elements from collection while performing iteration by using well-defined semantiecS
Method names are improved.
Any index number can be printed.
it includes three abstract methods. They are as follows,
boolean hasNext( ): It returns true if the collection has more elements.
Object neit( ): It retums the next element in the collection.
void removel ): It removes the current element in the collection.
In order to use iterator the following steps should be performed.
Step 1:Obtain an object of Iterator on the collection class by callin iterator( )
on the first element so Inat au uie ciccls method on the collection. pont
(by default, the print
is placed dC prea.
But, user can choose
Step 2: Create a control loop to iterate through all the elements by using hasNext(O the number of elemets to
methad
od.
Step 3: Exiract each element bý calling next( ) method.
The following code illustrates these steps.
step
Jterator it-list.Iterator( ): /1"
whilethasNext()) |I 2d step

System.ounprintln(it.next()) 13 step

ATayList).
HeTe, list is an object of a collection (cg:

Look for the SIA oUP LOGO


2 0n the TITLE
COVER
before you buy
(java.util)
INIT-4 The Collections Framework
Listlterator 4.11
.
Listlterator is an
mn interface that allows programmers to loop through the collection
odify the element in collection. t is uscd only ior those collections in both forward and backward directions
modify
also allows to that implement List. It has the following
h
methods.
O): This method inseris the given element before the clement retuned by neste
. id ndd(Object
lean hasNext( ): This method returns true il there is an element after the current clement in the collection Orhenvin
false.
it returns
hasPrevious( ): This method returnis true i1 there 1s an elctnent beore the current clement. (Otherwise, it returns
3
false
the current element, if there is one. Otherwise, it throws
. Object next( This method returns the clement after
NoSuchElementException.
the index of the next elcment. IHowever, if there is no next clement, it returns the
nt nertlndex( ): This method returns
5.
size of the list. If there no previous element, throws
method returns the clement beforc the curent clement. is it

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

& void remove(): This method deletes the current


clement. the current clement in the list.
set(Object O): This method assigns the given object to
9. void
Program
iterators
Java program to illustrate
mport java.util.";
class lteratorEx

public static void main(String


args[])

ArrayList<String> array_list = new ArrayList<String>0:


aray_list.add("AB");
array_list.add("XY"):
array_list.add("CD");
aray_list.add("PQ");
aray_list.add("EF");
array_list.add("RS");
System.out.print("The contents of Array List are:");
Iterator<String> itrtr = array_list.iterator():
while itrtr.hasNext0)

String ele = itrtr.next); " a niesH b.


System.out.print(ele +* *);

System.out.println0:
Listlterator<String> litr= array_list.listlterator():
while(litr.hasNext))

Suing ele litr.next);


litr.set(ele+**");
te
ETRUM ALLIN-ONE JOURNAL FOR ENGINEERING STuDENTS SAGROUP
JAVA PROGRAMMING IJNTU-HYDER
4.12 System.out.print("A fter modifications, the contents of Array List are:"):
RABAD

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())

String ele- litr.previous0;


System.out.print(cle+ "):

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( )):

(i) By Using for-each L0op


for(int a: val) STa

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

collection of data. Set is the unordered collection of data.


List is the ordered They docs not contain duplicate values.
They can duplicate
values. 2.
values.
3.
It allows atmost one nullvalue.
It allows null
order of elements. 4. Only few implementations of it maintains insertion order.
maintains the insertion
4. It 5. It does not have any legacy class.
legacy class.
5. It has one implementations of it are ArrayList, | 6.| Various implementations
of it are HashSet, Linked-
Various HashSet, TreeSet etc.
=
LinkedList etc.
ALTERNATIVE
4.4 THE FOR-EACH
alternative.
a21. Write a short notes on for-each
Answer:
Iterators iterator. It is mostly used
For-each Alternative to the set of objects instead of using an the
to iterate modified. 'For' can be used on
for-each version of the for loop is very simple reverse order can not
The access the elements in
contents of a set of objects or to
modify the
implements iterable interface.
to
collection that
using for loop,
Example
calculate the sum of the set of elements by
to
The following is the example
import java.util.";

class ForEachExmp

public static void main(String args[)

ArrayListsInteger> val = new ArrayList<Integer>();


val.add(2);
val.add(4);
val.add(6);
val.add(8);
System.out.println("Values are:");
for(int a: val)
System.out.print(a +" ");
System.out.println( );
int total = 0;
fortint a: val)
total +a
System.out.println("sum of all values:" + total);

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

AMap stores maps allow null values and


value associated with it. A few
retuns the
signature,
Following is the class interface
not implement terator
public interface Map. because Map does
retrieve the clements any Java class,
subclasses cannot use Iterator to Keys and values must be objects of
Map and its duplicate keys.
unique i.e., map does not allow
Keys must be
Methods below table,
Map interface are as given in the
the
The methods defined by Description
Method invoking Map objecC.
Deletes all key/value pairs of the object. Otherwise,
found in the invoking Map
void clear() Returns true if the given key is
key)
boolean containsKey(Object returns false. object. Otherwise,
Returms ifthe given value is found in the invoking Map
Value(Object value) true
boolean contains returns false.
pairs in the invoking Map object in the 1orm
a Set of (key, value)
4. SetMap.Entry<K, V>> entrySet()Returns
Map.Entry objects.
of has same (key, valuej
Returns
|
true if the given object is a Map object and
boolean equals (Object 0) Otherwise, returns
false._
pairs as those in the invoking Map object.
Returns the value corresponding to the given key.
Return null if the key s|
get(Object key)
6. V notfound.
Returns the hash code for the invoking Map object.
7. int hashCode( ) false.
Retuns true the invoking Map object is empty. Otherwise, returm
if
8. boolean isEmpty() Retums aSet of keysthat are present in theinvoking Map objec.
9. SetcK> keySet()
key, V value)
dy
Inserts the given key/value pair in the invoking Map object. Ifthe key auethe
10. V put(K ns
exist then he put( ) overwrites the value with the given value and retu
null.
overwritten value. However, the key is not
if present itthen returns a
Map
void putAIl (Map«?extends K, | Inserts the key/value pairs of the given Map object into the invoking
2extends V map) object.
12. V remove (Object key) Removes that key, value pair whose key matches with the given Ke
13. int size() Returns the number of elements in
the invoking Map object.
14. Collection <V> values() Retums a collection of values present in the invoking Map
object.
Table: Methods in Map Intorface

Look for the SIA GROUP LOGO


2 on the TITLE COVER before you buy
FrameworK (Javä.util
T4 The Collections 415
gram
java.util. ";
ortMapExample
des })
main (String argEs[
public static void
HashMap<Object, String>():
String> map = new
Map 0bject, "Three"):
map.put(new Integer (3),
"Four");
map.put(new Integer (4).
(5). "Five"):
map putnew Integer
"One"):
map.put(new Integer (1).
"Two");
map.put(new Integer (2), map:" + map.size( );
System.out.println("Number of elements in
System.out.println("Key/value pairs are:"):
System.out.println(map):

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

pblic etstic void main(String args )

ScrtedMap smap new TrecMap( ):


Ntar some (key, value) pairs in smap
EOM MLARONE JoURNAL FOR ENGINEERINO STUDENTS SIA GROUP
JAVA PROGRAMMING JNTU-HYDERA
DERABAD

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);
+

values in the sorted map ip increasing order


lowest key
Syme caprintinthe

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

obtained. Else, it returns null.


|
| to
an
It searches the map to find a largest key K
12. K floorKcy(K object) i.e., less than or ey n
object (K s object). It returns largest key, when it is found. Else,
i
null value
kinE
13.Navigable Map K, V> headMap(K|lt returmsa NavigableMap object whichinvolves each entry at theinvoinc
upperlsound, boolcan incl) map having keys which can be less
than an uppderBound. When erBoune
is set true, it involves the clement
that is equivalent to an up m
Therefore, the map which is found
can be backed using an invO

Look for tho S1A GROUP LOGO S2 on the TITLE COVER


before you buy
Collections Framework (java.util) 4.17
T-4 The
V>higherEntry(K object) It searches the set object to find a largest key K ie.. greater than an object
(K object). It returns the entry for largest key when it is found. Else.
a
Map. Entry<k,
4. It returns null. K i.e., less than an object
V>lowerEntry(K object) It searches the' set object to find a largest key
entry for a largest key when it is found. Else,
Map.Entry<K, (K object). It returns the
returns 'null".
i K i.e., less than an object
searches the set object to find a largest key
It it
a particular key when it is found. Else,
K
lowerKey(K object) (K < object). Then, it returms
6. returns 'null"'.
ch involve each entry at the invoking
which
It retums a NavigableMap object lowerBound as well
be greater than
NavigableMap<K, V> subMap(K| map which consists of key's that can
cases, when lowlncl is set to
true.}
eround. boolean lowlncl, K| as less than the upperBound. In certainlowerBound. Where as, it involves
highlncl) elemnent that is equal to
upperBound, boolean then it adds an when highlncl is set true. The
equal to highlncl is added
an element can that is
through an invoking
map.
resultant map be backed every at the invoking
NavigableMap object which consists of Whenever incl is set
lt returms a than lowerBound.
NavigableMap<K, V>tailMap(K|map having keys that are grater the lowerBound. The resultant map can
elements with
lowerBound, boolean incl) true, it equates the invoking map.
an
be backed through
NavigableMap Interface
Table: Methods in

Program
mport java.util. ";
java.util.concurrent.";
import
public class
NavigableMapDemo

public static void main


(String args[ )

new
TreeMap<Integer, String>):
lavigableMap<lnteger, String> nmap
=

IAnsert some elements


nmap.put(0, "Summer"):
nmap.put(2, "Winter");
nmapput(3, "Rainy");:
nmap.put(4, "Autumn'"):
nmap.put(5, "Fall");| nmap.descendingMap( ));
descending order is :In"+
System.out.println("The Navigable map in
+nmap.firstEntry();
System.out.println("The first entry in the Navigable map :n"
is
+ nmap.lastEntry))%
System.outprintln("The last entry in the Navigable map is :n"
)):
System.out.println("Removing the first entry:\n" + nmap.pollFirstEntry
System.out.printtn("Removing the last entry:In" + nmap.pollLastEntry ): ))%
nmap.descendingMap(
System.outprintn("The Navigable map in descending order is:n" +

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

Table: Methods in Map.Eatry lnterface


Programn
import java.util.HashMap;
import java.util.Map;
import java.util.lterator:
import java.util. Set;
import java.util."
public class MapEntryDemo

public static void main (String angs[ })

Map map = new HashMap( ):


I/Ansertsome elements in the map
map.put( 7", "Sunday"):
map.put("3". "Wednesday ");
map put(" i", "Monday"):
map.put(-2". "Tuesday");
map.put(4", "Thursday"):
map.put("6", "Saturday"):
map.puts", "Friday"):
Sets = map.entry Set( )
Iterator i s.iterator( :
=

System.out.println("The key/value pairs are"):


while(i.hasNext( ))

Map.Entry e =(Map. Entry)i.next( );


System.out.println(e.getKey() + **
c.getValue( );

the SlA GROUP LOGO


2 on the TITLE COVER
before you buy
Output
The key/value pairs are,
4.19
Monday
. Tuesday

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,

Class Name Functionality


AbstractMap It implements Map interface and a super class formany classes.
HashMap It works like Hashtable, storing key value pairs
TreeMap It gives the elements as nodes comprising a tre
WeakHashMap It is like HashMap where weak keys are used

) 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

The class signature of HashMap class is,


Serializable
public class HashMap extends AbstractMap implements Map. Cloneable,
The capacity() of HashMap gives the
HashMap constructor can be specified with initial capacity and load factor.
-

The initial capacity gves the saring Capacity


sorage capacity and the size( ) gives the actual elements present in the HashMap. gets
gives at what rate the capacity must be increased when the eristing capacity'
1 HashMap when it is created. The load factor
exhausted. The default load factor is 0.75.
time). 1Ibe
values decrease the space overhead but increaše the lookup cost (searching takes long
Higher load factor
HashMap methods are not synchronized.
Constructors
of l6.
HashMap): of 10 and a defzult load capacity
It creates an empty HashMap object with an initial capacity
and default load capacity 1.
2. HashMap(int cap): It creates an empty HashMap object with capacity "cap"
an initial capacity specined
3.
HashMap(int cap, float loadfac): It creates empty HashMap object with an
load capacity specified as "loadcap".
another Map class specthed oy
HashMap(Map m1): It creates a HashMap object with the elements of
Methods
. boolean containsKey(Object key): It returns true if the key is found
2
boolean containsValue(Object value): It returns true if the value is found.
3.
Object get(Object key): It returns the value associated with the kes
boolean isEmpty( ): It returns true if this map does not contains no key-value mappings
3.
Object remove(Object key): It removes the entry that matches key.
6.
Int size(): it returns the number of key-value pairs.
7. void clear(): It removes the entries.
GROUP
VECTRUM ALL-IN-ONE
JOURNAL FOR ENGINEERING STUDENTS
SIA
DERABAJ
-HYDE
4.20
Programn
importjava.util."
public class HashMapDemo

public static void main(String args[ })

HashMap hm new HashMap(10,0.5f):


hm.put("John", "Screna"),
hm.put"salary", new Double(9999 99):
hm put("distance", new Integer(3S0):
hm put("eapenditure". "88E8 88
Systen.outprintln(Salary key exists:" hm.containsKey ("salary")
System.out.println("Sita value exists:" hm.contains Value ("Sita))%
System.out.printlnVaue of Rama is hmgetRama)
System.out.printin("No. of elements:hmsize )%
System.out.printin("nPrinting the values using iterator:"x
Set aliKeys - hm.keySet t, (Retuns a set of krys contained in HashMap
Iterator It- allKeys.iterator ): //Returns an object of iterator
while (lthasNext( ))

Object obj - Itnext{ ).


System.out println( obj " hm.get(obj):

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

Trecisp oject wtdh the sarme


ckements ef the SortedMap peaiod by
atng ceder "n
ha natte ef pect
This clans doea t detass t ra cthods
ctuns i
Th sigrstute od IracMay
prdtalas cieas 1roehfap cukrnads AtuatMag
ienpacxzrermds
SortndiMap. Choncahle,
Seriatirable
ok for the SiA GROUP LOGO
U2 on the TmLe covER betore you buy
INIT-4 The Collections Framework (java.util)
4.21
Prograin
java.util."
inport
classmarksMap

public static void main(String args[])

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

Comparnble lnterfnce Compnrntur Interfnee

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

verrido umpare( ) method to reverse the oder


public int compare(String str), String str2)

String s1, s2
s str;
2str2
l compareTod ) invoked by s2 reverses the
tree set
return s2.conpareTofsl ),

claes RevireeSet

pobsic static void main(Stringaryal

H Creste a tree set of strings


TreesesString treenew Treeset<Stringtnew
MyComparator(
Add elements )
tree addl"Ashraf"y
tres ad"shasiay
tree sdd"Ameery
troe addl"Rahin",

the 5IA GAOUP


Coo 1ot LO00
on the tTitc
Framework (java.util)
NIT-4 The Collections
tree.add(Haseena");: 4.23
I Display the treeSet
System.out.println(TreeSet in a reverse order is")
for(String element: tree) I/Display the elements
System.out.println(element);

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

public static void main(Stringl] args)

List list- Arrays.asList(args);


Collections.sort(list);
System.oul.println(list);

Output

nrjava SortDemo cost ly red apple


app ve COst y, rej

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

publie static void main(Stringl] args)

=
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

above output, it gives diflerent orders.

(c) Routine Data Manipulation


five algorithms for pertorming routine data manipulation on List objects. They te
The Collections class provides
reverse: reverses the order of the elements in a List.
fill It overwrites all the elements of LISt with given value. lt is used to re-initializea List.
(i)
It accepts two arguments, namely a destination List and a source List.
(ii) copY It copies the source e
destination by overwriting its contents.
a
t swaps the specified clements of List.
(iv swap individu
adds all the specilied elements to a Collection. The clements to
(v)addAll: or as an urray.
be added may be specified
s.

(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.

Following is the class signature,


public class Arrays extends Object
Methods
Following are some static methods with their description.
static int binarySearch(double myarrayl], double num) NESTi
method should be Uscd wil
I is used to find a specificd number (num) in the array (myarray) using binary scarch. This
sorted arrays. This method is overloaded that can take a byte array, char amiy, int array ctc.
static void equals(double myarray1|1. double myarray21)
can taken byte aity, Cnnr
lt is used to check whether two arrays havc the same elements. This method is overloaded that
array, int array etc.
SPECTRUM AUIN-ONE JouRMAL FOR ENGINEERINa STUDENTS
-SIA GROUP
4.26 JAVA PROGRAMMING JNTU-HYDERA.
3. static void fill(double myarray1|], double num)
t is used to fill all the array elements of the array (myarray 1) with the specifeid value (num). hodis
This method is oveoa
that can take a byte array, char array, int array etlc.
4. statie void sort(double myarray1|)
that can take a byte array, char
It is used to sort the elements in the ascending order. This method is overloaded
aray etc.
Example
The following program illustrates the use of Arrays class.
import java.util.";
public class ArraysMethods

public static void main(String[] args)

intmarks[1= { 50,30, 20, 10, 40 );integer array


int price[]={ 50,30, 20, 10, 40 ); / to compare two arrays whether their elements are same
System,out.println("Both amays are equal:"+ Arrays.equals(marks, price));
System.out.print("Original values:");
forint i 0; i < marks.length; it+)

System.out.print(marks[i]+"*")

System.out.println( ) sorting the elements of the array in ascending order

Arrays.sort(marks); l elements in the original array itself are changed


System.out.print("Values After sorting: ");
for(int i=0; i<marks.length;it+

System.out.print(marks[i]+" ");

int k= Arrays.binarySearch(marks, 30); I/ to find the index number of an element


System.out.println("unlndex number pf 30 in the sorted array:"+k);

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

029. Explain about legacy classes and interfaces.


Answer: Model Paper-41. QB()
Interfaces
Legacy Classes and
Thedata structures introduced with JDK 1.0 version arc caled legacy classes and interfaces. Even though, the Collectios
amework is far more superior with its rich set of features, the legacy classes are not deprecated. Instead,
some more methess
fram
added and re-engncered to fit into collection framework.
art
Following table gives a list of legacy classes and interlaces

Legacy Structure Type of the Class Functionality


Enumeration interface Used to iterate and print the elements
|Vector class(non-abstract) Stores all types of objects
|
Stack class(non-abstract) Stores all types of objects(LIFO order)
Dictionary abstract class Stores key/valuc pairs
Hashtable class(non-abstract) Stores key/value pairs
Properties class(non-abstract) Stores key/value pairs

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

put (kkey, Vvalue)


6. remove( ): The remove( ) method deletes a key and its corresponding value from
the dictionary, and returns the deletd
value. It returns null the key is not in the dictionary..
if
Syntax
Vremove (Object key
7. size(): The size() method will return the number of (key, value) pairs
of 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.

int Size( ): This method will returm number of key/value


pairs of hash table.
String toString( ): This method will return string representation of hash table.
gram
port java.util.*

blic class HashDemo

publicstatic void main(String args[)

Hashtable ht = new Hashtable( );


System.out.println("Before adding elements:" + ht.isEmpty());
Integeril new Integer(5);
ht.put("hello", il); /insert a key/value pair
System.out.println("After adding elements:" + ht.isEmpty( ):
hi.put("world", new Integer(10);
ht.put("apple", new Double(20.5);
ht.put("banana", new Boolean(true));
ht.put("world", new Integer(10);
HashDemo hdl= new HashDemo( :
ht.putthd1, il);
ht.put("sure", "abids"):
ht.put("date", "12th March, 20001");
StringBuffer sb = new StringBuffer( ):
ht.put(sb, "Config Software Solutions");
System.out.printin("Before removing size:"+ ht.size():
ht.remove("apple");
System.out.printin("Afer removing size:" + ht.size( ):
System.out.println("hello object in ht:" + ht.containsKey("hello");
ystem.out.println("il object in ht:" + ht.contains(il);
System.out.println("sb is associated with:" + ht.get(sb)):
Enumeration e = ht.keys( );
while e.hasMoreElements( )

Object k e.nextElement( );
Object v ht.get(k);
System.out.println("Key:" +k +"Value:" + v;

oNE JOURNAL FOR ENGINEERING STUDENTS


- SIAGRoUP
JAVA PROGRAMMING (JNTU-HYDERAABAD
4.30
Output
Before adding elements: rue
After adding clements: false
tb g y u a
Bcfore renoving size:8
Ater removing size: 7
hello object in ht: true
il object in ht : truc
sb is associated with: Config Software Solutions
:
Key: Valte Config Software Solutions
Key: banana Value : Tie
Key: HashDemo@1db9742 Value: 5
Key:date Value: 12th March, 20001
Key : hcllo Value: 5
Key: sure Value : abids
Key: world Value: 100
Q32. What is the importance of hashCode() and equals( ) methods?
Answer:
ApriUMay-18(R16). QB
hashCode()
The hashCode( ) method is used to generate hashcode
for a specific object. It might either be a signature or checksum fax
the object. If the objects data is similar, according
to the equals( ) method then objects should posses same hashcode. If the object
contain distinct data, then the hashcode values can be
In hashtable, cach object is assigned
diflerent. The hasheode values are used in storing the object in hash tahle
with an identifier (hashcode values) that helps in storing
casily. By default, hashcode( ) method assigns and determining the object location
each object with a unique number known as hash
the hashCode( ) method then cach object code. Ifa class does not ovemie
contains a unique hashcode.
equals()
cquals( ) method is used to compare the two
objects. It determines the equality of two objects.
method compares the references of the By default, the equalst
given object. The two objects are said to be
Some of the conditions to be satisfied for
equal if they have same memory address
implementing equals( ) and hashCode( )
two objects are cqual by using equals() methods are as follows,
If method then the both the objects should
have same hashcode.
(11) If two objccts consists of same hashcode, then not mandatory that
033. Write about Properties of data it is the objects to be equal.
structure.
Answer
P'rortie
P'ro rti
s
instance abic defauts,ofliashtable class. It has a list of values that represent keys and values as String objecus. It has E
ich hold a iiaiti ch properiy objecl. n
Construciors to
l'ropeitics) it creales a properties object
yithout any default values.
Properties(Properiies default Values)
It creales a properties object
Methods with the given default values.
Properties class inherits all methods
of Hashtable. In addition cthads
String getProperty(String key) to Hashtable methods,
it defines the following "
String getProperty(String
of the given key. Howevcr, the first key, String defautlValue):
method returns null if the These methods retty
in the list. Whereas, the second
method retums the given
given key is not present either
in the detau
i
2 void List (PrintStream outStream), def ult value ifthe key is not available
in both ne
t
ists.
void List(PrintWriter ist to
output stream that is connected to the
outStream.
outStream): These methods send the prop
3, void load(InputStream inStrenm), void
lond(Reader inStream): These from
input stream that is connected to the methods take as input
inStream. These methods throw a property list
an 1OException on error.
4. void loadFromXML(lnputStream inputStrenm): docu

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

outStream. These methods throw


nid storeToXML(OutputStream Outputstream,that String descp): This method first writes the given string description and
is connccted to thec outstream. This method throws an 1OException
then writes the property list to the XML document
on error.
This method returns a set of keys.
set<String> string PropertyNames( ):
Elample
Fle Name:
PropertiesDemo.java
mport java.util.";
ublic class PropertiesDemo

public static void main(String argsl )


134
Properties p = new Properties(); ne
P-put("Bawarchi", "Biryani"); :a7x#
P.put("Blue Sea", "Tea");
P.put"Niagara", "Irani Haleem");
System.out.println(p.getProperty*Blue Sea")
System.out.println(p.getProperty("Hotel Adab") );

String str
Enumeration e = p.keys( );
while(e.hasMoreElements( ))

str= (String) e.nextElement():


System.out.println( str + "
is famous for" +p-getProperty(str); au
m

String strl p.getProperty("Hotel Adab", "Kaju Roti");


=
System.out.println("Hotel Adab is famous for" + strl);

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

4. Explain in detail about Hashtable class.


Answer
Hashtable
Class
in which the pair(key, value) are stored in a Hash table. However, the
only
di ashtables are very much similar to HashMap in hashtable the
Detween these two collection classes is that, in HashMap, key and
values can take a null value whereas
tey an object which
Values can not be null. Whencver, a hashtable is being used, it is necessary for a programmer to specity
a key, and the value that must be linked with that key.
S
he declaration of generic hashtable is,
class hashtable<key.value>
defined by object class.
hashtable can store objects that have the capability of overriding hashcode( and equals(). Methods
)

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

public stutic void main(String args[ )

Stack s-Tw Steck


1-push)
spesh2)
psb3,
Systemouprinttn("element of stack:"+s);
ytemoa print!n"elements at the top of the stack"+s.push( ));
sytemcnaprintink"elements removed from stack:"+s.pop(
)):

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)

imlarities between Arrayl.ist and Vector


imilarities between ArrayList arndvector are as follows,
structures.
ayl.ist and vector classes are considered as index based
both ArrayList and classes follows insertion order. So the elements
can be displaycd in the same order.
fail-fast by design in java.
both the classes, the iterator implementations are considered as
Ee classes can store null and duplicate valucs.
n with the help of index number
4yist and vector classes an element can be accessed randomly
wECTm
ALAN-ONE JOuRNAL FOR ENGIMEERINO STUDENTS SIA GROUP
4.34 JAVA PROGRAMMING [JNTU-HYDER
HYDERABAG
Differences between ArryList and Vector

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.

MORE UTILITY CLASSES STRINGTOKENIzER, BITSET, DATE, CALENDAR, RANDOM,


FORMATTER, SCANNER
Q39. Discuss about StringTokenizer class.
OR
Describe the important methods of StringTokenizer class.
(Refer Only Topic: Merhods)
Answer : May-19(R16). a

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.

RALOok for the 5IA dROUP LOGO


A on the TiITLE COVED
IT-4 The Collections Frarnowork (java.util)
The class java.util.String'Tokenizcr is a sinpler version ol a claas Stringlokenizer( of java.io packinge), but R workx esdy
h strings. The set of delimiters(the charactern that separate tokens) may be specified at creation tine
Cametimcs, it is necessary to decomposc a ull ine ol data into tokena as required by a procensor and etc. Fach
interpreter
ken
is word. Delimiters are specificd based on which the string
a isto
be tokenized The default delimiter whitespace ike
owhich will be taken by default when any delimiler is omitted. Moreover, it is ponsible to specify group of delimiters
Program
String'Tokenizer class
ava program to illustráte the concept of
importjava.util."
java.util.String'Tokenizer;
mport
ublic class
StringTokenizerClassDemo

public static void main(String args[ })

String strl "Hello World;How,Do You/Do,All Arc/Okay;Thank/You":


=

StringTokenizer st new StringTokenizer(str l, "/"):


System.out.println("Number of tokens:" +st.countTokens( ):
while(st.has MorcTokens( ))

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,

shd ANDBitSet bs): This meth00 tlhe invoking BitSet


object and the object specified
rloms the AND operntion on
.The revul of AND operation is stored in the invoking objeci. spcciflcd by
BitSet objoct and tho object
bn ie e ba): "This method performs the OR operation on the invoking
.The result ís storcd in the invoking obJect.
GROuP
"
BLANOKE JOURHAL FOR ENGIMEERING STUDENTS SIa
JAVA PROGRAMMING IJNTU-HYDERABAD
36 performs the XOR Output
void XOR(BitSet bs): This mcthod
operation on the invoking BitSet object and the
object
invoking
BSI= 1 2, 3,4, 5, 7, 8, 9, 10, 11

specified by "bs'. The result is stored in the BS2 4,8, 12)


object.
form of, ANDSet 8
=
{4,
vold clear(), void clear(int index): The first
clear() method assigns all bit values to zero. The second ORset {1,2, 3, 4, 5, 7, 8, 9, 10, 11}
form of clear( ) method assigns the list value
specified XORSet= (3,4, 5,7,8, 10, 11
by index to zero. Q41. Write notes on Date class with an example.
boolean get(int index), BitSet get(int start, int end):
bit value at Answer
The first form of get() method returns the
the specificd index. The second form retums the subset Date
of BitSet spccificd by start and end index. The date class contains the current date and time.
void set(int indcx). void set(int index, boolean bit): Constructors
This method sets the value of a bit at the specified index. Date(
The boolean value "bit' specifies the value to be set the
bit can be cither true or falsc. Date(long mseconds)
void set(int start, int end), void set(int start, int end, The first form of constructor creates a default Date objet
takes
boolean bit) This method sets the subset of bits from and with the current date and time. Second constnuctor
milliseconds that have
start to end-1. The boolean value 'bit' specifies the value an argument that equals the number of
to be set It can be cither true or false. elapsed since midnight 1" January, 1970.
String toString( ): This method returns the equivalent Methods
string representation of the BitSet object. Some of the methods defined by Date class are moved
methods
Example into calendar and DateFormat classes and remaining
to the Data
import java.util.BitSet; are deprecated. The new methods added by Java
class Bset class are as follows.
number
1. long getTime(): This method is used to retrieve
midnight 1"Jamu
public static void main(String args[ }) of milliseconds that got elapsed from
ary. 1970.
the time
2. void setTime(long time): This method is used to set
BitSet bs1= ncw BitSet(12):
3. String toString( ): This method returns the strie
BitSet bs2 = new BitSet(12): equivalent to the invoking Date object.
for(int i-1; i =12; it+) au
Object clone( ): This method is used to create the
plicate of the invoking Date object
is useu
if%6) 1- 0) 5. boolean equals(Object date): This method
bs1.sct(i); determine whether the two objects the invoking cqu
if(i%4)-0) object and the object specified by date are
bs2.sct(i): retuns true if they are equal, otherwise returms ia true
O. boolean before(Date date): This method will return
than the
ifthe invoking Date object contains a date Iess
System.oul.printin("BSI="+bs1);
date' object. Otherwise it returms false.
Systen.out.println("BSs2-" + bs2)
bs2 and(bs1):
. boolean after(Date date): This method will ret tha
tru
ifthe invoking Date object contains a date gres
System.out.println("ANDSet" bs2) the 'date' object. Otherwise, it retums false.
bs2.ortbs1):
3. int hashCode( ): This method is used to returm u
ehash
Systcm.out.println("ORSet="+ bs2);
bslcleart 9.
code for invoking object.
int compareTo(Date date): This method conhit
res te
bn2.clear(2). invoking Date object with the specified by "d
be2clear1 The value returned by this method are as to
b2.clear(9)
Return value Meaning
b2 xortbs 1). If both objects are equal.
Syten.ce printin("XORSet bs2);
Positive value the invoking objacts comes alt
f comes efore
Negative value
the invoking object
ALOoK for the SA GROUP LOG0 on the TITLE COVER before you buy
UNIT The Col System.out.printinid getSeconds } "grint
regram
toextract hours
nprt jarautil.Date Systern.ont.printin(dgetMonthi ).prints 10tior Nov)
cias ate Time ito extract date
System.out.printin(d.getDatet )): prints 8
})
putlic static void main(String args[ to extract day
System.out println(d getDay( ). /prints 5 (for Friday)

vrg tim to extract year


Date d new Date System.out.println(d.getYear0):
System.out.printin("The current date and time
is:in"+d): toextract time
System.out. println(d.getTime ):

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

MINUTE AUGUST FRIDAY ERA


SECOND SEPTEMBER SATURDAY UNDECIMBER
MILLISECOND oCTOBER DAY_OF_WEEK DST_OFFSET
JANUARY NOVEMBER DAY_OF_MONTH FIELD_CoUNT
FEBRUARY DECEMBER DAY OF_YEAR zONE_OFFSET
The Calendar class defines several methods. Some commonly used methods are as follos,
1. static Calendar getinstancef ): This method returns the object of calendar class for the default location and time
zne
2. int getfint const): This method will return the value of the requested component of the
invoking object. This comporet
is specified by "const'. It can be any one of the integer constants. For
example CalendarDATE, Calendar.HOUR et
3. int getfint cal_Field): This method is used to retun the value of the
given component of the invoking object. For exrçe
Calendar.YEAR, Calendar.MINUTE, Calendar. HOUR and so on
void set(int const, int value): This method will set the value
of the date or time component as specified by const 1
const must be defined by calendar class. FoT example Calendar. HOUR.
. final boolean isSet(int cmpnt): This method is used to return to when the provided
component is set. Else, it retuTs
D. final void setlint year, int month, int dayOMonth): This method is
used to set the different components like dee
time of the invoking object.
7. final void set(int year, int month, int dayOfMonth, int hours,
int minutes): This method is used to set the dinr
components (like year, month, dayOfMonth, hours, minutes) of the invoking object
8. final void setTime(Date d): This method is used to set the different
date and time components of the invoking ooj*
uSing the given Date object d.
9. void setTimeZone(TimeZone t): This method is used to set the time zone
of the invoking object provided by L
10. TimeZone getTimeZonef ): This method is used to return the time zone for the
invoking object.
1. abstract void add(int cmpnt, int val): This method is used to add or subtract
the time or date provided by cmp
12. boolean equals(Object calObj): This method will return true
calobj contains. Otherwise it returns false. if both the invoking calendar object is similar
13. boolean after(Object calObj): This method will returm true if the invoking greater
calendar object contains a date
date gr
calObj' object. Otherwise it returns false.
14. boolean before(Object calObj): This method will return true if the ca les
invoking calendar object contains a date
c
calObj' object. Otherwise it returms false.
15. final void clear( ): This method is used to make the values
of all he components in the invoking object to z*To.
16. nnal void clear(int cmpnt): This method is used to make the values of the given kingoja
component in the invo
17. object clone(): This method used to return the copy of invoking object.
is
18. fini Date getTime( ): This method is used to return a Date
object that is equivalent to the invoking obj
19 statie Locale() grtAvailableLocales( ): This method Consists o
is used to return an array
locales which have the calendars. of Locale objects whie

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 =

System.outprint("Current date and time:");


System.out.println(cal.getTime( );
Jan.25, 2007 to 3: 35
cal.se(2007, 0, 25, 3, 35); /Sct time to
System.out.println("Updated time:" + cal.getTime( );
cal.set(Calendar.HOUR, 10);
cal.set(Calendar.MINUTE, 40);
cal.sct(Calendar.SECOND, 05);
System.out.print("Updated time:");
System.out.print(cal.get(Calendar.HOUR) + ":");
System.out.print(cal.get(Calendar.MINUTE)+ ":")
System.out.println(cal.get(Calendar.SECOND):
cal.set(cal.DATE, 20);
System.out.printin("Set date to 20:" + cal.getTime( ):

Output

Current date and time : Fri Nov 08 12:41:18 IST 2019


Updated time: Thu Jan 25 03:35:18 IST 2007
Updated time : 10:40:5

. Set date to 20:Sat Jan 20 10:40:05 IST 2007


Explaln tho Bitsot and
Answer
Calondar classes In dotal.
Nov./Dec.-17(R16), Q9(a)

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

public static void main(String arys[ )

random ro= new random( );


double value;
double total=0;
int arr [ ] = new int( 10);
Sor(int i-20;i<50;i+1)

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

Er nexiBigintegert ): This method is uscd to retuma Biglnteger


valuc Le, 10.
SPEX
aRaM ALLAN-ONE JOURNAL FOR ENGINEERING STUDENTS
SIA GRoUP
IJNTU-HYDERAD
JAVA PROGRAMMING EA
4.42
Programm
import java.util.";
import java.util.Scanner;
class ScannerEx

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

Locale locale() It returns the locale of the invoking object.


lt returns the reference of destination for output1.
Appendable out()
It returns a string to hold the lormatted output.
String tostring()

string. It can be represented as:


Once the formatter is created, it can be used to create formatted

Fomatter format(String fmistring, object...arg)

The format specifiers can be represented with a percent sign


followed by the conversion specifier.

The various format specifiers are as follows,

Format Specifier Conversion


oa Floating point hexadecimal
%A Floating point hexadecimal
%b Boolean
%B Boolean
oc Character
%d Decimal integer
%h Hash code of argument
%H Hash code of argument
%e Scientific notation
%E Scientific notation
%f Decimal floating point
% Makes use of %e or %f
%G Makes use of %e or %f
Octal integer
New line character
String
%S String
Time and date
%T Time and dáte
Integer hexadecimal
%X Integer hexadecimal
%% will insert a % sign
sPECTR
d ALL-IN-ONE J0URNAL FOR ENGINEERING STuDENTS StA GROUP
JAVA PROGRAMMING (JNTU-HYDERE
44 follows,
A sample example to illustrate the
creation of a formatted string and to display it is as

import java.util.";

class format

})
public static void main(String args[

Formatier F = new Formatter( : llobject creation

F.format(Java%s basics %d %f", "Formatting", 5, 2.5);


System.out.println(F);

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

Formatting Strings and Characters


A character is formatted by using %c and a string is formatted by using %s.
Example

f.format(%c %s", "a", "specifier");


Formatting Numbers
An integer value/number in decimal format is formatted ntific
by using %d. A floating point value in decimal format and set
notation is formatted by using %f and %e respectively.

The representation of number in scientific


notation is given by,
x.ddde+/-y
The %g format specifier specifies the
formatter when it use %f and %e.
Example
f.format(%f%d%c", 1.23, 12,
23.45 e+67);
The speciliers %0 and %x ure used
to display the integer value in octal
used to display the floating point value in and hexadecimal format respectiveiy.
hexadecimal format,
Example
f.format("%x %0 %a", 123, 456, 712.00);

Formatting Time and Date


The specifiers %t is used 1or 1omatting time and date. desiredform
The suffixes are used with %t
of time and date. that determines the de

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);

Specifyinga Minimum Ficld Width

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

f.format("%f%n %012f %n %0123r", 10.123, 10.456, 10.789)


The output of above example is shown below,

.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

f.format ("%5.2f", 9876.4321 5012);

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.

Format flag Description


This lag is used for left justification.
This flag is used for the alternate conversion format.
This flag is used to display the output with zeros instead of spaces.
Space This flag allows a positive numeric output to be preceded with a space
This flag allows positive numeric output to be preceded by a + sigt
a

This flag ullows a numeric values to include grouping separators


This flag is used for enclosing the negative numeric valucs

ECTRUM ALINONE JOURMAL FOR ENGINEERINd STUDENTS SIA GROUP


-HYDERABAD
JAVA PROGRAMMING JNTU-HYDERA
6
4.
Justifying Output
printed is smaller than the ficld width
any program is right-justified by default. When the data n
The output of by using a minus sign placing it afler the
The output can be set len-justified
is moved to the right cdge of field.

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.

Space, +,0, and ( Flngs


(a) + Flng

The + Flag is used to place + sign before any positive numeric valuc.

Example
f.format("%+d", 250)

(b) Space Flag


numbers. While creating a column with mumben,
Space flag is used to display the output that has spaces in betwcen the
ahe space flag is placed before positive values such that the negative
and positive are lincd up differently.

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);:

The output for the above statement will be (280)

(d) O Flag
0 flag is used to display the output with zeros instead of spaces.

(e) Comma Flag


are added to the number
Comma flag (.) is used to display the larger number. The grouping separators

Example
f.format(%, .2f", 9876543210.12);
The output will be

9, 876, 543, 210.12

# 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

converted to OX, if it is present.


Example
F.fomat%X", 120):
F.format(%E", 234.456):
Argument Index
A formatter allows an argument to be specified with the format specifier. In this, the first format specifier is matched with
the first argument and the second format specifier is matched with the second argument and so on. Therefore the format specifier:
are matched with the arguments in a lefn to right order. An argument index is used explicitly to specify which fornat specifier i:
matched with an argument. An argument index is given by S symbol that is followed by the % symbol in a given format specifier
Example
F.format%4Sd %2Sd %6$d" 60, 40, 20):
An argument that is matched with the preceding format specitfier can be used again and is referred to relative index. Instead
of S
symbol, < is used before the format specifier.
Example
F.format("%d in hex is % <x", 123);
Closing a Formatter
A formatter is closed by cxplicitly calling the closc( ). A formatter can be closed automatically by using an auto closeable
interiace. The try-with-resources statement are supported by this interface.
Syntax for Closing a
Formatter
f.close( ):
example for closing a formatter automatically is as follows,
import java.util."
class format

public static void main(String args[ ])

try(Formatter f= new Formatter( ))

1.format("Hello %s is printed in the output program %d", "world", 5);


System.out.println();

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.

ROM ALLIN-ONE JOURNAL


FOR ENaINEERINa STUDENTS SIA GROP

You might also like