Unit 4
Unit 4
UNIT IV
MULTITHREADING
MULTITHREADING
• Java provides builtin support for multithreaded programming.
• A multithreaded program contains two or more parts that can run concurrently.
• Each part of such a program is called a thread, and each thread defines a separate path
of execution.
• Thus, multithreading is a specialized form of multitasking.
TYPES OF MULTITASKING
Processbased Multitasking
• A process is, in essence, a program that is executing.
• Thus, processbased multitasking is the feature that allows your computer to run two or
more programs concurrently.
• Ex: Processbased multitasking enables you to run the Java compiler at the same time that you
are using a text editor.
Threadbased Multitasking
• In a threadbased multitasking environment, the thread is the smallest unit of dispatchable code.
• This means that a single program can perform two or more tasks simultaneously.
• Ex: A text editor can format text at the same time that it is printing, as long as these two
actions are being performed by two separate threads.
1
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
• In this model, a single thread of control runs in an infinite loop, polling a single event
queue to decide what to do next.
• Once this polling mechanism returns with, say, a signal that a network file is ready to be read,
then the event loop dispatches control to the appropriate event handler.
• Until this event handler returns, nothing else can happen in the system.
• This wastes CPU time. It can also result in one part of a program dominating the system
and preventing any other events from being processed.
• In general, in a singledthreaded environment, when a thread blocks (that is, suspends
execution) because it is waiting for some resource, the entire program stops running.
Java’s Multithreading System
• The benefit of Java’s multithreading is that the main loop/polling mechanism is eliminated.
• One thread can pause without stopping other parts of your program.
• For example, the idle time created when a thread reads data from a network or waits for
user input can be utilized elsewhere.
• Multithreading allows animation loops to sleep for a second between each frame without
causing the whole system to pause.
• When a thread blocks in a Java program, only the single thread that is blocked pauses.
• All other threads continue to run.
THREADS
Threads exist in several states.
Running
Ready to
Run
Suspended
Resumed
Blocked
Terminated
Method Meaning
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
t.setName("My Thread");
System.out.println("After name change: "
+ t); try
{
for(int n = 5; n > 0; n)
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted");
}
}
}
Sleep()
• The sleep( ) method causes the thread from which it is called to suspend execution for
the specified period of milliseconds.
Its general form is shown here:
static void sleep(long milliseconds) throws InterruptedException
Creating a Thread
• You create a thread by instantiating an object of type Thread.
• Java defines two ways in which this can be accomplished:
■ You can implement the Runnable interface.
■ You can extend the Thread class, itself.
Implementing Runnable
• The easiest way to create a thread is to create a class that implements the Runnable interface.
• You can construct a thread on any object that implements Runnable.
• To implement Runnable, a class need only implement a single method called run( ), which is
declared like this:
public void run( )
• run( ) establishes the entry point for another, concurrent thread of execution within
your program.
4
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
5
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread {
public static void main(String args[]) { new NewThread(); // create a new
thread try {
for(int i = 5; i > 0; i) { System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) { System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Creating Multiple Threads
• Till now we have seen a Main Thread & one Child Thread.
• It is also possible to create multiple Threads.
• The following program demonstrates creation of multiThreads. Program 4
class NewThread implements Runnable
{
String name; // name of thread Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name); System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread. public void run() {
try {
for(int i = 5; i > 0; i) { System.out.println(name )
}
System.out.println(name + " exiting.");
}
}
6
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start
threads new NewThread("Two");
new
NewThread("Three"); try
{
// wait for other threads to
end Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread
Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Using isAlive( ) and join( )
• How can one thread know when another thread has ended?
• Fortunately, Thread provides a means by which you can answer this question.
• Two ways exist to determine whether a thread has finished.
Alive()
• First, you can call isAlive( ) on the thread.
• This method is defined by Thread, and its general form is shown here:
final boolean isAlive( )
• The isAlive( ) method returns true if the thread upon which it is called is still running. It
returns false otherwise.
• Alive is occasionally used.
Join()
• The method that you will more commonly use to wait for a thread to finish is called join( ),
shown here:
final void join( ) throws InterruptedException
• This method waits until the thread on which it is called terminates.
• Its name comes from the concept of the calling thread waiting until the specified thread joins
it. Program 5
class NewThread implements Runnable
{ String name; // name of thread
Thread t;
7
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
NewThread(String threadname)
{ name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " +
t); t.start(); // Start the thread
}
// This is the entry point for
thread. public void run() {
try {
for(int i = 5; i > 0; i) {
System.out.println(name + ": " +
i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + "
interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new
NewThread("Three");
System.out.println("Thread One is alive: "
+ ob1.t.isAlive());
System.out.println("Thread Two is alive:
" + ob2.t.isAlive());
System.out.println("Thread Three is alive:
" + ob3.t.isAlive());
// wait for threads to
finish try {
System.out.println("Waiting for threads to
finish."); ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
8
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
System.out.println("Main thread
Interrupted");
}
System.out.println("Thread One is alive: "
+ ob1.t.isAlive());
System.out.println("Thread Two is alive:
" + ob2.t.isAlive());
System.out.println("Thread Three is alive:
" + ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}
Thread Priorities
• Thread priorities are used by the thread scheduler to decide when each thread should be
allowed to run.
• A higherpriority thread can also preempt a lowerpriority one.
• For Example, when a lowerpriority thread is running and a higherpriority thread resumes
(from sleeping or waiting on I/O, for example), it will preempt the lowerpriority thread.
• To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is
its general form:
final void setPriority(int level)
• The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY.
• Currently, these values are 1 and 10, respectively.
}
}
public void stop()
{ running = false;
}
public void start()
{ t.start();
}
}
class HiLoPri {
public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY 2);
lo.start();
hi.start()
; try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread
interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to
terminate. try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException
caught");
}
System.out.println("Lowpriority thread: " +
lo.click); System.out.println("Highpriority thread: "
+ hi.click);
10
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
}
}
Synchronization
• When two or more threads need access to a shared resource, they need some way to ensure
that the resource will be used by only one thread at a time.
• The process by which this is achieved is called synchronization.
• Key to synchronization is the concept of the monitor (also called a semaphore).
Monitor
• A monitor is an object that is used as a mutually exclusive lock, or mutex.
• Only one thread can own a monitor at a given time.
• When a thread acquires a lock, it is said to have entered the monitor.
• All other threads attempting to enter the locked monitor will be suspended until the first
thread exits the monitor.
• These other threads are said to be waiting for the monitor.
• A thread that owns a monitor can reenter the same monitor if it so desires.
Java implements synchronization through language elements in either one of the two ways.
1. Using Synchronized Methods
2. The synchronized Statement
Using Synchronized Methods
Program 7(unsynchronized
Thread) class Callme {
void call(String msg) {
System.out.print("[" +
msg); try {
Thread.sleep(1000);
} catch(InterruptedException e)
{
System.out.println("Interrupted"
);
}
System.out.println("]");
}
}
class Caller implements Runnable
{ String msg;
Callme
target;
Thread t;
public Caller(Callme targ, String
s) { target = targ;
11
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
msg = s;
t = new
Thread(this);
t.start();
}
public void run() {
target.call(msg);
}
}
class Synch {
public static void main(String
args[]) { Callme target = new
Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target,
"Synchronized"); Caller ob3 = new
Caller(target, "World");
// wait for threads to
end try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e)
{
System.out.println("Interrupted"
);
}
}
}
The synchronized Statement
• Second solution is to call the methods defined by the class inside a synchronized block.
• This is the general form of the synchronized statement:
synchronized(object)
{
// statements to be synchronized
}
Program 8
class Callme
{
void call(String msg) {
12
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
System.out.print("[" +
msg); try {
Thread.sleep(1000);
} catch (InterruptedException e)
{
System.out.println("Interrupted"
);
}
System.out.println("]");
}
}
class Caller implements Runnable
{ String msg;
Callme
target;
Thread t;
public Caller(Callme targ, String
s) { target = targ;
msg = s;
t = new
Thread(this);
t.start();
}
// synchronize calls to
call() public void run() {
synchronized(target) { // synchronized
block target.call(msg);
}
}
}
class Synch1 {
public static void main(String
args[]) { Callme target = new
Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target,
"Synchronized"); Caller ob3 = new
Caller(target, "World");
// wait for threads to end
try {
13
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
ob1.t.join()
;
ob2.t.join()
;
ob3.t.join()
;
} catch(InterruptedException e)
{
System.out.println("Interrupted"
);
}
}
}
Interthread Communication
• To avoid polling, Java includes an elegant interprocess communication mechanism via the wait( ),
notify( ), and notifyAll( ) methods.
wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread
enters the same monitor and calls notify( ).
notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest
priority thread will run first.
These methods are declared within Object, as shown
here: final void wait( ) throws
InterruptedException final void notify( )
final void notifyAll( )
Program 9 (Correct Implementation of Producer & Consumer Problem)
class Q {
int n;
boolean valueSet =
false; synchronized int
get() { if(!valueSet)
try {
wait(
);
} catch(InterruptedException e) {
System.out.println("InterruptedException
caught");
}
System.out.println("Got: " + n);
14
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
valueSet =
false; notify();
return n;
}
synchronized void put(int n)
{ if(valueSet)
try {
wait(
);
} catch(InterruptedException e) {
System.out.println("InterruptedException
caught");
}
this.n = n;
valueSet =
true;
System.out.println("Put: " +
n); notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q)
{ this.q = q;
new Thread(this, "Producer").start();
}
public void run()
{ int i = 0;
while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q)
{ this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{ while(true) {
q.get();
}
15
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
}
}
class PCFixed {
public static void main(String
args[]) { Q q = new Q();
new Producer(q);
new
Consumer(q);
System.out.println("Press ControlC to stop.");
}
}
16
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
Deadlock
• A special type of error that you need to avoid that relates specifically to multitasking is
“deadlock”.
• It occurs when two threads have a circular dependency on a pair of synchronized objects.
Deadlock is a difficult error to debug for two reasons:
■ In general, it occurs only rarely, when the two threads timeslice in just the right way.
■ It may involve more than two threads and two synchronized objects.
Suspending, Resuming, and Stopping Threads
• suspend( ) and resume( ), which are methods defined by Thread, to pause and
restart the execution of a thread. They have the form shown below:
final void
suspend( )
final void
resume( )
• The Thread class also defines a method called stop( ) that stops a thread. Its
signature is shown here:
final void stop( )
o java.lang.Object
o java.util.AbstractCollection<E> (implements java.util.Collection<E>)
o java.util.AbstractList<E> (implements java.util.List<E>)
o java.util.AbstractSequentialList<E>
o java.util.LinkedList<E> (implements java.lang.Cloneable,
java.util.List<E>, java.util.Queue<E>, java.io.Serializable)
o java.util.ArrayList<E> (implements java.lang.Cloneable,
java.util.List<E>, java.util.RandomAccess, java.io.Serializable)
o java.util.Vector<E> (implements java.lang.Cloneable,
java.util.List<E>, java.util.RandomAccess, java.io.Serializable)
o java.util.Stack<E>
o java.util.AbstractQueue<E> (implements java.util.Queue<E>)
o java.util.PriorityQueue<E> (implements java.io.Serializable)
o java.util.AbstractSet<E> (implements java.util.Set<E>)
o java.util.EnumSet<E> (implements java.lang.Cloneable,
java.io.Serializable)
17
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
o java.util.ListResourceBundle
o java.util.PropertyResourceBundle
java.util.Scanner (implements java.util.Iterator<E>)
java.util.StringTokenizer (implements java.util.Enumeration<E>)
java.lang.Throwable (implements java.io.Serializable)
o java.lang.Exception
o java.io.IOException
o java.util.InvalidPropertiesFormatException
o java.lang.RuntimeException
o java.util.ConcurrentModificationException
o java.util.EmptyStackException
o java.lang.IllegalArgumentException
o java.util.IllegalFormatException
o java.util.DuplicateFormatFlagsException
o java.util.FormatFlagsConversionMismatchEx
ception
o java.util.IllegalFormatCodePointException
o java.util.IllegalFormatConversionException
o java.util.IllegalFormatFlagsException
o java.util.IllegalFormatPrecisionException
o java.util.IllegalFormatWidthException
o java.util.MissingFormatArgumentException
o java.util.MissingFormatWidthException
o java.util.UnknownFormatConversionExcepti
on
o java.util.UnknownFormatFlagsException
o java.lang.IllegalStateException
o java.util.FormatterClosedException
o java.util.MissingResourceException
o java.util.NoSuchElementException
o java.util.InputMismatchException
o java.util.TooManyListenersException
java.util.Timer
java.util.TimerTask (implements java.lang.Runnable)
java.util.TimeZone (implements java.lang.Cloneable, java.io.Serializable)
o java.util.SimpleTimeZone
java.util.UUID (implements java.lang.Comparable<T>, java.io.Serializable)
Interface Hierarchy
o java.util.Comparator<T>
19
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
o java.util.Enumeration<E>
o java.util.EventListener
o java.util.Formattable
o java.lang.Iterable<T>
o java.util.Collection<E>
o java.util.List<E>
o java.util.Queue<E>
o java.util.Set<E>
o java.util.SortedSet<E>
o java.util.Iterator<E>
java.util.ListIterator<E>
o java.util.Map<K,V>
java.util.SortedMap<K,V>
o java.util.Map.Entry<K,V>
o java.util.Observer
o java.util.RandomAccess
Enum Hierarchy
o java.lang.Object
o java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)
o java.util.Formatter.BigDecimalLayoutForm
Introduction
The Java 2 platform includes a collections framework. A collection is an object that represents a
group of objects (such as the familiar Vector class). A collections framework is a unified
architecture for representing and manipulating collections, allowing them to be manipulated
independently of the details of their representation.
In order to handle group of objects we can use array of objects. If we have a class called Employ
with members name and id, if we want to store details of 10 Employees, create an array of object
to hold 10 Employ details.
Employ ob [] = new Employ [10];
We cannot store different class objects into same array.
Inserting element at the end of array is easy but at the middle is difficult.
After retriving the elements from the array, in order to process the elements we dont
have any methods
20
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
Collection Object:
A collection object is an object which can store group of other objects.
A collection object has a class called Collection class or Container class.
All the collection classes are available in the package called 'java.util’ (util stands for
utility).
Group of collection classes is called a Collection Framework.
A collection object does not store the physical copies of other objects; it stores references
of other objects.
Reduces programming effort by providing useful data structures and algorithms so you
don't have to write them yourself.
Increases performance by providing high-performance implementations of useful data
structures and algorithms. Because the various implementations of each interface are
interchangeable, programs can be easily tuned by switching implementations.
Provides interoperability between unrelated APIs by establishing a common language
to pass collections back and forth.
Reduces the effort required to learn APIs by eliminating the need to learn multiple ad
hoc collection APIs.
Reduces the effort required to design and implement APIs by eliminating the need to
produce ad hoc collections APIs.
Fosters software reuse by providing a standard interface for collections and algorithms
to manipulate them.
Collection Interfaces - Represent different types of collections, such as sets, lists and
maps. These interfaces form the basis of the framework.
General-purpose Implementations - Primary implementations of the collection
interfaces.
Legacy Implementations - The collection classes from earlier releases, Vector and
Hashtable, have been retrofitted to implement the collection interfaces.
Special-purpose Implementations - Implementations designed for use in special
situations. These implementations display nonstandard performance characteristics, usage
restrictions, or behavior.
Concurrent Implementations - Implementations designed for highly concurrent use.
Wrapper Implementations - Add functionality, such as synchronization, to other
implementations.
21
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
Collection Interfaces
There are nine collection interfaces. The most basic interface is Collection. Five interfaces
extend Collection: Set, List, SortedSet, Queue, and BlockingQueue. The other three collection
interfaces, Map, SortedMap, and ConcurrentMap do not extend Collection, as they represent
mappings rather than true collections. However, these interfaces contain collection-view
operations, which allow them to be manipulated as collections.
All of the modification methods in the collection interfaces are labeled optional. Some
implementations may not perform one or more of these operations, throwing a runtime exception
(UnsupportedOperationException) if they are attempted. Implementations must specify in
their documentation which optional operations they support. Several terms are introduced to aid
in this specification:
Collections that do not support any modification operations (such as add, remove and
clear) are referred to as unmodifiable. Collections that are not unmodifiable are referred
to modifiable.
Collections that additionally guarantee that no change in the Collection object will ever
be visible are referred to as immutable. Collections that are not immutable are referred to
as mutable.
Lists that guarantee that their size remains constant even though the elements may change
are referred to as fixed-size. Lists that are not fixed-size are referred to as variable-size.
Lists that support fast (generally constant time) indexed element access are known as
random access lists. Lists that do not support fast indexed element access are known as
sequential access lists. The RandomAccess marker interface is provided to allow lists to
advertise the fact that they support random access. This allows generic algorithms to alter
their behavior to provide good performance when applied to either random or sequential
access lists.
22
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
Some implementations may restrict what elements (or in the case of Maps, keys and values) may
be stored. Possible restrictions include requiring elements to:
Be of a particular type.
Be non-null.
Obey some arbitrary predicate.
Collection Implementations
Classes that implement the collection interfaces typically have names of the form
<Implementation-style><Interface>. The general purpose implementations are summarized in the
table below:
Implementations
The general-purpose implementations support all of the optional operations in the collection
interfaces, and have no restrictions on the elements they may contain. They are unsynchronized,
but the Collections class contains static factories called synchronization wrappers that may be
used to add synchronization to any unsynchronized collection. All of the new implementations
have fail-fast iterators, which detect illegal concurrent modification, and fail quickly and cleanly
(rather than behaving erratically).
23
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
Retrieving Elements from Collections: Following are the ways to retrieve any element from a
collection object:
ListIterator Interface: ListIterator is an interface that contains methods to retrieve the elements
from a collection object, both in forward and reverse directions. It can retrieve the elements in
forward and backward direction. It has the following important methods:
24
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
Enumeration Interface: This interface is useful to retrieve elements one by one like Iterator. It
has 2 methods.
HashSet Class: HashSet represents a set of elements (objects). It does not guarantee the order of
elements. Also it does not allow the duplicate elements to be stored.
We can write the HashSet class as: class HashSet<T>
We can create the object as: HashSet<String> hs = new HashSet<String> ();
The following constructors are available in HashSet:
HashSet();
HashSet (int capacity); Here capacity represents how many elements can be stored into
the HashSet initially. This capacity may increase automatically when more number of
elements is being stored.
25
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
Program : Write a program which shows the use of HashSet and Iterator.
//HashSet Demo
import java.util.*;
class HS
{ public static void main(String args[])
{ //create a HashSet to store Strings
HashSet <String> hs = new HashSet<String> ();
//Store some String elements
hs.add ("India");
hs.add ("America");
hs.add ("Japan");
hs.add ("China");
hs.add ("America");
//view the HashSet
System.out.println ("HashSet = " + hs);
//add an Iterator to hs
Iterator it = hs.iterator ();
//display element by element using Iterator
System.out.println ("Elements Using Iterator: ");
while (it.hasNext() )
{ String s = (String) it.next ();
System.out.println(s);
}
26
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
}
}
Output:
LinkedHashSet Class: This is a subclass of HashSet class and does not contain any
additional members on its own. LinkedHashSet internally uses a linked list to store the
elements. It is a generic class that has the declaration:
class LinkedHashSet<T>
Stack Class: A stack represents a group of elements stored in LIFO (Last In First Out)
order.
This means that the element which is stored as a last element into the stack will be
the first element to be removed from the stack. Inserting the elements (Objects) into
the stack is called push operation and removing the elements from stack is called pop
operation. Searching for an element in stack is called peep operation. Insertion and deletion
of elements take place only from one side of the stack, called top of the stack. We can write a
Stack class as:
class Stack<E>
e.g.: Stack<Integer> obj = new Stack<Integer> ();
Stack Class Methods:
27
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
28
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
for(int i=top;i>=0;i--)
System.out.println(st[i]);
}
boolean isFull()
{
return(top==5-1);
}
boolean isEmpty()
{
return(top==-1);
}
}
class Stack
{
public static void main(String a[])
{
Scanner sc=new Scanner(System.in);
Stack1 s=new Stack1();
int el=0,ch=1;
while(ch!=4)
{
System.out.println("\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT");
System.out.println("ENTER YOUR CHOICE");
ch=sc.nextInt();
switch(ch)
29
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
{
case 1:if(s.isFull())
System.out.println("\nstack is full");
else
{
System.out.println("Enter element");
el=sc.nextInt();
s.push(el);
}break;
case 2:if(s.isEmpty())
System.out.println("\nstack is empty");
else
{
el=s.pop();
System.out.println("\nDeleted element = "+el);
}break;
case 3:if(s.isEmpty())
System.out.println("\nstack is empty");
else
s.display();
break;
case 4:break;
default:System.out.println("\nEnter correct choice");
}
}
30
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
}
}
LinkedList Class: A linked list contains a group of elements in the form of nodes. Each
node will have three fields- the data field contatins data and the link fields contain
references to previous and next nodes.A linked list is written in the form of:
class LinkedList<E>
we can create an empty linked list for storing String type elements (objects) as:
LinkedList <String> ll = new LinkedList<String> ();
31
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
Note: In case of LinkedList counting starts from 0 and we start counting from 1.
32
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
33
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
al.add ("Africa");
al.add ("Europe");
al.add (1,"Australia");
al.add (2,"Antarctica");
System.out.print ("Size of the Array List is: " + al.size ());
System.out.print ("\nRetrieving elements in ArrayList using Iterator :");
Iterator it = al.iterator ();
while (it.hasNext () )
System.out.print (it.next () + "\t");
}
}
Output:
Vector Class: Similar to ArrayList, but Vector is synchronized. It means even if several
threads act on Vector object simultaneously, the results will be reliable.
Vector class can be written as: class Vector <E>
We can create an object to Vector as: Vector <String> v = new Vector<String> ();
35
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
36
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
Output:
HashMap Class: HashMap is a collection that stores elements in the form of key-value
pairs. If key is provided later its corresponding value can be easily retrieved from the
HAshMap. Key should be unique. HashMap is not synchronized and hence while using
multiple threads on HashMap object, we get unreliable results.
We can write HashMap class as: class HashMap<K, V>
For example to store a String as key and an integer object as its value, we can
create the
HashMap as: HashMap<String, Integer> hm = new HashMap<String, Integer> ();
37
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
The default initial capacity of this HashMap will be taken as 16 and the load factor as 0.75.
Load factor represents at what level the HashMap capacity should be doubled. For
example, the product of capacity and load factor = 16 * 0.75 = 12. This represents that after
storing 12th key-value pair into the HashMap, its capacity will become 32.
38
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
System.out.println (set);
}
}
Output:
Hashtable Class: Hashtable is a collection that stores elements in the form of key-value
pairs. If key is provided later its corresponding value can be easily retrieved from the
HAshtable. Keys should be unique. Hashtable is synchronized and hence while using
multiple threads on Hashtable object, we get reliable results.
We can write Hashtable class as: class Hashtable<K,V>
For example to store a String as key and an integer object as its value, we can
create the
Hashtable as: Hashtable<String, Integer> ht = new Hashtable<String, Integer> ();
The default initial capacity of this Hashtable will be taken as 11 and the load factor as 0.75.
Load factor represents at what level the Hashtable capacity should be doubled. For
example, the product of capacity and load factor = 11 * 0.75 = 8.25. This represents that
after storing 8th key-value pair into the Hashtable, its capacity will become 22.
39
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
Output:
40
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
Arrays Class: Arrays class provides methods to perform certain operations on any
single dimensional array. All the methods of the Arrays class are static, so they can be
called in the form of Arrays.methodname ().
Program : Write a program to sort given numbers using sort () method of Arrays Class.
import java.util.*;
//Arrays Demo
class ArraysDemo
41
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
StringTokenizer: The StringTokenizer class is useful to break a String into small pieces
called tokens. We can create an object to StringTokenizer as:
StringTokenizer st = new StringTokenizer (str, "delimeter");
class STDemo
{
public static void main(String args[])
{ //take a String
String str = "Java is an OOP Language";
//brake wherever a space is found
StringTokenizer st = new StringTokenizer (str," ");
//retrieve tokens and display
System.out.println ("The tokens are: ");
while ( st.hasMoreTokens () )
{
String s = st.nextToken ();
System.out.println (s );
}
}
}
Output:
Calendar: This class is useful to handle date and time. We can create an object to Calendar
class as: Calendar cl = Calendar.getInstance ();
44
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
Output:
Date Class: Date Class is also useful to handle date and time. Once Date class object is
created, it should be formatted using the following methods of DateFormat class of java.text
package.We can create an object to Date class as: Date dd = new Date ();
Once Date class object is created, it should be formatted using the methods of DateFormat
class of java.text package.
45
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
class MyDate
{
public static void main(String args[])
{ Date d = new Date ();
DateFormat fmt = DateFormat.getDateTimeInstance (DateFormat.MEDIUM,
DateFormat.SHORT, Locale.UK);
String str = fmt.format (d);
System.out.println (str);
}
}
Output:
Design Goals
The main design goal was to produce an API that was reasonably small, both in size, and, more
importantly, in "conceptual weight." It was critical that the new functionality not seem alien to
current Java programmers; it had to augment current facilities, rather than replacing them. At the
same time, the new API had to be powerful enough to provide all the advantages described
above.
To keep the number of core interfaces small, the interfaces do not attempt to capture such subtle
distinctions as mutability, modifiability, and resizability. Instead, certain calls in the core
interfaces are optional, allowing implementations to throw an
UnsupportedOperationException to indicate that they do not support a specified optional
operation. Of course, collection implementers must clearly document which optional operations
are supported by an implementation.
46
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
To keep the number of methods in each core interface small, an interface contains a method only
if either:
It was critical that all reasonable representations of collections interoperate well. This included
arrays, which cannot be made to implement the Collection interface directly without changing
the language. Thus, the framework includes methods to allow collections to be dumped into
arrays, arrays to be viewed as collections, and maps to be viewed as collections.
47
SREE RAMA ENGINEERING COLLEGE OOP’S PROGRAMMING THROUGH JAVA CSE
48