BCS306A – OOP with JAVA
Module 5
Chapter 11 & 12
11. Multithreaded Programming,
12. Enumerators, Type Wrappers and Autoboxing
Dr. [Link], [Link].D.,
Professor, Department of ISE, HKBKCE
Java :
The Complete Reference
Chapter – 11 Multithreaded Programming
Topics Covered
• Multithreaded Programming The java thread
model, main thread Creating thread, creating
multiple threads using isAlive() and join() thread
priorities, synchronization Interthread
communication suspending, resuming and
stopping threads obtaining a thread state, multi
threading
Dr. [Link], Professor,
Dept. of ISE, HKBKCE.
3
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).
• 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.
Dr. [Link], Professor,
Dept. of ISE, HKBKCE. 4
Synchronization
• synchronize the code in two ways
1. Using Synchronized Methods
2. The synchronized Statement
Dr. [Link], Professor,
Dept. of ISE, HKBKCE.
5
Using Synchronized Methods
• Synchronization is easy in Java, because all objects
have their own implicit monitor associated with them.
• To enter an object’s monitor, just call a method that
has been modified with the synchronized keyword.
While a thread is inside a synchronized method, all
other threads that try to call it (or any other
synchronized method) on the same instance have to
wait.
• To exit the monitor and relinquish control of the
object to the next waiting thread, the owner of the
monitor simply returns from the synchronized
Dr. [Link], Professor,
method. Dept. of ISE, HKBKCE. 6
// This program is not synchronized.
class Callme {
void call(String msg) {
[Link]("[" + msg);
try {
[Link](1000);
} catch(InterruptedException e) {
[Link]("Interrupted");
}
[Link]("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
[Link]();
}
public void run() {
[Link](msg);
} Dr. [Link], Professor,
} Dept. of ISE, HKBKCE.
7
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 {
[Link]();
[Link]();
[Link]();
} catch(InterruptedException e) {
[Link]("Interrupted");
}
}
}
Dr. [Link],
Professor, Dept. of ISE,
HKBKCE. 8
by calling sleep( ), the call( ) method allows execution to switch to
another thread. This results in the mixed-up output of the three
message strings.
In this program, nothing exists to stop all three threads from calling
the same method, on the same object, at the same time. This is
known as a race condition, because the three threads are racing each
other to complete the method.
To fix the program, you must serialize access to call( ). That is, you
must restrict its access to only one thread at a time. To do this, you
simply need to precede call( )’s definition
with the keyword synchronized,
class Callme {
synchronized void call(String msg) {
...
Dr. [Link], Professor,
Dept. of ISE, HKBKCE. 9
// This program is synchronized.
class Callme {
synchronized void call(String msg) {
[Link]("[" + msg);
try {
[Link](1000);
} catch(InterruptedException e) {
[Link]("Interrupted");
}
[Link]("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
[Link]();
}
public void run() {
[Link](msg);
} Dr. [Link], Professor,
} Dept. of ISE, HKBKCE.
10
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 {
[Link]();
[Link]();
[Link]();
} catch(InterruptedException e) {
[Link]("Interrupted");
}
}
}
Dr. [Link], Professor,
Dept. of ISE, HKBKCE.
11
//program - 2
class Table{
void printTable(int n){ //method not synchronized
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
}
}
}
class MyThread1 extends Thread{ class MyThread2 extends Thread{
Table t; Table t;
MyThread1(Table t){ MyThread2(Table t){
this.t=t; this.t=t;
} }
public void run(){ public void run(){
[Link](5); [Link](100);
} }
} }
12
class TestSynchronization1{ Output:
public static void main(String args[]){ 5
Table obj = new Table(); //only one object 100
10
MyThread1 t1=new MyThread1(obj); 200
MyThread2 t2=new MyThread2(obj); 15
[Link](); 300
20
[Link](); 400
} 25
} 500
Dr. [Link],
Professor, Dept. of ISE,
HKBKCE. 13
//program - 3
class Table{
synchronized void printTable(int n){ //method synchronized
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
}
}
}
class MyThread1 extends Thread{ class MyThread2 extends Thread{
Table t; Table t;
MyThread1(Table t){ MyThread2(Table t){
this.t=t; this.t=t;
} }
public void run(){ public void run(){
[Link](5); [Link](100);
} }
} }
14
class TestSynchronization1{
Output:
public static void main(String args[]){
5
Table obj = new Table(); //only one object
10
MyThread1 t1=new MyThread1(obj);
15
MyThread2 t2=new MyThread2(obj);
20
[Link]();
25
[Link]();
100
}
200
}
300
400
500
Dr. [Link], Professor,
Dept. of ISE, HKBKCE.
15
The synchronized Statement
• While creating synchronized methods within classes
that you create is an easy and effective means of
achieving synchronization, it will not work in all cases.
• Imagine that you want to synchronize access to
objects of a class that was not designed for
multithreaded access. That is, the class does not use
synchronized methods.
• Further, this class was not created by you, but by a
third party, and you do not have access to the source
code. Thus, you can’t add synchronized to the
appropriate methods within the class.
• How can access to an object of this class be
synchronized? Fortunately, the solution to this
problem is simply put calls to the methods defined by
this class inside a synchronized block. 16
The synchronized Statement
• This is the general form of the synchronized
statement:
synchronized(object) {
// statements to be synchronized
}
• Here, object is a reference to the object being
synchronized.
• A synchronized block ensures that a call to a
method that is a member of object occurs only
after the current thread has successfully entered
object’s monitor. 17
// This program uses a synchronized block. class Caller implements Runnable {
class Callme { String msg;
void call(String msg) { Callme target;
[Link]("[" + msg); Thread t;
try { public Caller(Callme targ, String s) {
[Link](1000); target = targ;
} catch (InterruptedException e) { msg = s;
[Link]("Interrupted"); t = new Thread(this);
} [Link]();
[Link]("]"); }
} // synchronize calls to call()
} public void run() {
synchronized(target) {
[Link](msg);
}
}
}
Dr. [Link], Professor,
Dept. of ISE, HKBKCE.
18
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 {
[Link]();
[Link]();
[Link]();
} catch(InterruptedException e) {
[Link]("Interrupted");
}
}
}
Dr. [Link], Professor,
Dept. of ISE, HKBKCE.
19
Interthread Communication
• Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
• Inter-thread communication is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or
lock) in the same critical section to be executed.
• To avoid polling, Java includes an elegant interprocess communication
mechanism via the wait( ), notify( ), and notifyAll( ) methods.
• These methods are implemented as final methods in Object, so all classes
have them.
• All three methods can be called only from within a synchronized context.
– wait()
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()
notify( ) wakes up a thread that called wait( ) on the same object.
– notifyAll()
notifyAll( ) wakes up all the threads that called wait( ) on the same object.
One of the threads will be granted access.
20
Interthread Communication
• These methods are declared within Object,
final void wait( ) throws InterruptedException
final void wait(long timeout)throws InterruptedException
final void notify( )
final void notifyAll( )
• Example: Producer and consumer problem
Dr. [Link], Professor,
Dept. of ISE, HKBKCE.
21
Understanding the process of inter-thread communication:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state
(runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state
of the object.
Dr. [Link], Professor,
Dept. of ISE, HKBKCE. 22
Difference between wait and sleep
wait() sleep()
• wait() method releases the • sleep() method doesn't
lock release the lock.
• is the method of Object • is the method of Thread
class class
• is the non-static method • is the static method
• is the non-static method • is the static method
• should be notified by • after the specified amount
notify() or notifyAll() of time, sleep is completed.
methods
Dr. [Link], Professor,
Dept. of ISE, HKBKCE.
23
//Example - 1
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
[Link]("going to withdraw...");
if([Link]<amount){
[Link]("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
[Link] -= amount;
[Link]("withdraw completed...");
}
synchronized void deposit(int amount){
[Link]("going to deposit...");
[Link] += amount;
[Link]("deposit completed... ");
notify();
}
Dr. [Link], Professor,
}
Dept. of ISE, HKBKCE. 24
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){[Link](15000);}
}.start();
new Thread(){
public void run(){[Link](10000);}
}.start();
}}
Output: going to withdraw...
Less balance; waiting for deposit...
Dr. [Link], Professor, going to deposit...
Dept. of ISE, HKBKCE. deposit completed...
withdraw completed 25
Deadlock
• A special type of error that need to avoid that relates
specifically to multitasking is deadlock, which occurs when
two threads have a circular dependency on a pair of
synchronized objects.
• For example, suppose one thread enters the monitor on
object X and another thread enters the monitor on object Y.
If the thread in X tries to call any synchronized method on Y,
it will block as expected. However, if the thread in Y, in turn,
tries to call any synchronized method on X, the thread waits
forever, because to access X, it would have to release its own
lock on Y so that the first thread could complete.
• Deadlock is a difficult error to debug for two reasons:
– In general, it occurs only rarely, when the two threads time-slice
in just the right way.
– It may involve more than two threads and two synchronized
objects. (That is, deadlock can occur through a more convoluted
sequence of events than just described.) 26
Dr. [Link], Professor,
Dept. of ISE, HKBKCE.
27
// An example of deadlock.
class A {
synchronized void foo(B b) {
String name = [Link]().getName();
[Link](name + " entered [Link]");
try {
[Link](1000);
} catch(Exception e) {
[Link]("A Interrupted");
}
[Link](name + " trying to call [Link]()");
[Link]();
}
synchronized void last() {
[Link]("Inside [Link]");
}
} Dr. [Link],
Professor, Dept. of ISE,
28
HKBKCE.
class B {
synchronized void bar(A a) {
String name = [Link]().getName();
[Link](name + " entered [Link]");
try {
[Link](1000);
} catch(Exception e) {
[Link]("B Interrupted");
}
[Link](name + " trying to call [Link]()");
[Link]();
}
synchronized void last() {
[Link]("Inside [Link]");
}
}
Dr. [Link], Professor,
Dept. of ISE, HKBKCE.
29
class Deadlock implements Runnable {
A a = new A();
B b = new B();
Deadlock() {
[Link]().setName("MainThread");
Thread t = new Thread(this, "RacingThread");
[Link]();
[Link](b); // get lock on a in this thread.
[Link]("Back in main thread");
}
public void run() {
[Link](a); // get lock on b in other thread.
[Link]("Back in other thread");
}
public static void main(String args[]) { OUTPUT
new Deadlock(); MainThread entered [Link]
RacingThread entered [Link]
} MainThread trying to call [Link]()
} 30
RacingThread trying to call [Link]()
Suspending, Resuming, and Stopping Threads
• Sometimes, suspending execution of a thread is useful.
• For example, a separate thread can be used to display the time of
day. If the user doesn’t want a clock, then its thread can be
suspended.
• Suspending, restarting and stopping the thread is simple.
• Prior to Java 2, a program used suspend( ) and resume( ), which
are methods defined by Thread, to pause and restart the
execution of a thread.
final void suspend( )
final void resume( )
• The Thread class also defines a method called stop( ) that stops a
thread. Once a thread has been stopped, it cannot be restarted
using resume( ).
final void stop( )
31
// Using suspend() and resume(), Prior to Java 2.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
[Link]("New thread: " + t);
[Link](); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 15; i > 0; i--) {
[Link](name + ": " + i);
[Link](200);
}
} catch (InterruptedException e) {
[Link](name + " interrupted.");
}
[Link](name + " exiting.");
}
Dr. [Link], Professor,
}
Dept. of ISE, HKBKCE. 32
class SuspendResume { [Link]();
public static void main(String args[]) { } catch (InterruptedException e) {
NewThread ob1 = new NewThread("One"); [Link]("Main thread Interrupted");
NewThread ob2 = new NewThread("Two"); }
try { [Link]("Main thread exiting.");
[Link](1000); }
[Link](); }
[Link]("Suspending thread One");
[Link](1000);
[Link]();
[Link]("Resuming thread One");
[Link]();
[Link]("Suspending thread Two");
[Link](1000);
[Link]();
[Link]("Resuming thread Two");
} catch (InterruptedException e) {
[Link]("Main thread Interrupted");
}
// wait for threads to finish
try {
[Link]("Waiting for threads to finish.");
[Link]();
33
New thread: Thread[One,5,main] One: 7
One: 15 One: 6
New thread: Thread[Two,5,main] Resuming thread Two
Two: 15 Waiting for threads to finish.
One: 14 Two: 5
Two: 14 One: 5
One: 13 Two: 4
Two: 13 One: 4
One: 12 Two: 3
Two: 12 One: 3
One: 11 Two: 2
Two: 11 One: 2
Suspending thread One Two: 1
Two: 10 One: 1
Two: 9 Two exiting.
Two: 8 One exiting.
Two: 7 Main thread exiting.
Two: 6
Resuming thread One
Suspending thread Two
One: 10
Dr. [Link], Professor,
One: 9
Dept. of ISE, HKBKCE.
One: 8
34
Java 2: The Modern Way of Suspending,
Resuming, and Stopping Threads
• While the suspend( ), resume( ), and stop( ) methods defined by Thread
seem to be a perfectly reasonable and convenient approach to managing
the execution of threads, they must not be used for new Java programs.
• Here’s why.
• The suspend( ) method of the Thread class was deprecated by Java 2
several years ago. This was done because suspend() can sometimes cause
serious system failures. Assume that a thread has obtained locks on critical
data structures. If that thread is suspended at that point, those locks are
not relinquished. Other threads that may be waiting for those resources
can be deadlocked.
• The resume( ) method is also deprecated. It does not cause problems, but
cannot be used without the suspend( ) method as its counterpart.
• The stop( ) method of the Thread class, too, was deprecated by Java 2.
This was done because this method can sometimes cause serious system
failures. Assume that a thread is writing to a critically important data
structure and has completed only part of its changes. If that thread is
stopped at that point, that data structure might be left in a corrupted
state.
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 35
Control a thread with a flag variable
• Can’t now use the suspend( ), resume( ), or stop( ) methods
• A thread must be designed so that the run( ) method
periodically checks to determine whether that thread should
suspend, resume, or stop its own execution.
• Typically, this is accomplished by establishing a flag variable
that indicates the execution state of the thread.
• As long as this flag is set to “running,” the run( ) method
must continue to let the thread execute.
• If this variable is set to “suspend,” the thread must pause.
• If it is set to “stop,” the thread must terminate.
• Of course, a variety of ways exist in which to write such
code, but the central theme will be the same for all
programs. to control a thread.
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 36
// Suspending and resuming a thread the modern way.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
boolean suspendFlag;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
[Link]("New thread: " + t);
suspendFlag = false;
[Link](); // Start the thread
}
public void run() { // This is the entry point for thread.
try {
for(int i = 15; i > 0; i--) {
[Link](name + ": " + i);
[Link](200);
synchronized(this) {
while(suspendFlag) { void mysuspend() {
wait();
suspendFlag = true;
}
} }
} synchronized void myresume() {
} catch (InterruptedException e) { suspendFlag = false;
[Link](name + " interrupted."); notify();
} [Link](name + " exiting."); }
} } 37
class SuspendResume { }
public static void main(String args[]) { [Link]("Main thread exiting.");
NewThread ob1 = new NewThread("One"); }
NewThread ob2 = new NewThread("Two");
}
try {
[Link](1000);
[Link]();
[Link]("Suspending thread One");
[Link](1000);
[Link]();
[Link]("Resuming thread One");
[Link]();
[Link]("Suspending thread Two");
[Link](1000);
[Link]();
[Link]("Resuming thread Two");
} catch (InterruptedException e) {
[Link]("Main thread Interrupted");
}
// wait for threads to finish
try {
[Link]("Waiting for threads to
finish.");
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread Interrupted"); 38
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main] One: 9
One: 15 Suspending thread Two
Two: 15 One: 8
Two: 14 One: 7
One: 14 One: 6
One: 13 One: 5
Two: 13 One: 4
One: 12 Resuming thread Two
Two: 12 Two: 4
One: 11 Waiting for threads to finish.
Two: 11 Two: 3
One: 10 One: 3
Suspending thread One One: 2
Two: 10 Two: 2
Two: 9 One: 1
Two: 8 Two: 1
Two: 7 Two exiting.
Two: 6 One exiting.
Two: 5 Main thread exiting.
Resuming thread One
39
Using Multithreading
• The key to utilizing Java’s multithreading features
effectively is to think concurrently rather than serially.
• For example, when you have two subsystems within a
program that can execute concurrently, make them
individual threads. With the careful use of
multithreading, you can create very efficient
programs.
• A word of caution is in order, however: If you create
too many threads, you can actually degrade the
performance of your program rather than enhance it.
• Remember, some overhead is associated with context
switching. If you create too many threads, more CPU
time will be spent changing contexts than executing
your program!
40
Daemon thread in Java
• Daemon thread is a low priority thread that runs in
background to perform tasks such as garbage
collection, finalizer.
• It provides services to user threads for background
supporting tasks.
• Its life depends on user threads.
• It is a low priority thread.
• The [Link] class provides two methods
for java daemon thread.
public void setDaemon(boolean status)
public Boolean isDaemon()
41
public class TestDaemonThread1 extends Thread{
public void run(){
if([Link]().isDaemon()){
[Link]("daemon thread work");
}
else{
[Link]("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
[Link](true); //now t1 is daemon thread
[Link](); //starting threads
[Link]();
[Link](); OUTPUT
} daemon thread work
} user thread work
user thread work 42
Thread Group
• ThreadGroup creates a group of threads. It offers a convenient way to
manage groups of threads as a unit. This is particularly valuable in
situation in which you want to suspend and resume a number of related
threads.
• The thread group form a tree in which every thread group except the
initial thread group has a parent.
• A thread is allowed to access information about its own thread group but
not to access information about its thread group’s parent thread group or
any other thread group.
• [Link] class in Java
• public ThreadGroup(String name) - Constructs a new thread group. The
parent of this new group is the thread group of the currently running
thread.
• public ThreadGroup(ThreadGroup parent, String name) - Creates a new
thread group. The parent of this new group is the specified thread group.
• int activeCount(): This method returns the number of threads in the group
plus any group for which this thread is parent.
Dr. [Link], Professor, Dept. of
ISE, HKBKCE. 43
public class ThreadGroupDemo implements Runnable{
public void run(){
[Link]([Link]().getName());
}
public static void main(String args[]){
ThreadGroupDemo obj = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
Thread t1 = new Thread(tg1,obj,"one");
[Link]();
Thread t2 = new Thread(tg1,obj,"two");
[Link]();
Thread t3 = new Thread(tg1,obj,"three");
[Link]();
[Link]("Thread Group Name: "+[Link]());
[Link]();
}
}
44
Java :
The Complete Reference
Chapter – 12
Enumerations
• An enumeration is a list of named constants.
• In Java, an enumeration defines a class type, an
enumeration can have constructors, methods, and
instance variables.
• An enumeration is created using the enum keyword.
// An enumeration of apple varieties.
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
• The identifiers Jonathan, GoldenDel, and so on, are
called enumeration constants. Each is implicitly
declared as a public, static final member of Apple.
• These constants are called self-typed, in which “self”
Dr. [Link], Professor,
Dept. of ISE, HKBKCE. 46
Enumerations
• do not instantiate an enum using new.
• Example, declares ap as a variable of enumeration
type Apple:
Apple ap;
the only values that it can be assigned,
ap = [Link];
• Two enumeration constants can be compared for
equality by using the = = relational operator.
if(ap == [Link]) // ...
Dr. [Link], Professor,
Dept. of ISE, HKBKCE.
47
Enumerations
• An enumeration value can also be used to control a
switch statement.
// Use an enum to control a switch statement.
switch(ap) {
case Jonathan:
// ...
case Winesap:
// ...
the names of the enumeration constants are used
without being qualified by their enumeration type name.
that is Winesap, not [Link], is used.
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 48
Enumerations
• Enum improves type safety
• Enum can be easily used in switch
• Enum can be traversed
• Enum can have fields, constructors and methods
• Enum may implement many interfaces but cannot
extend any class because it internally extends
Enum class
Dr. [Link], Professor,
Dept. of ISE, HKBKCE.
49
//Example - 1
class EnumExample1{
//defining the enum inside the class
public enum Season {
WINTER, SPRING, SUMMER, FALL
}
public static void main(String[] args) {
//traversing the enum
for (Season s : [Link]())
[Link](s);
}
} OUTPUT
WINTER
Dr. [Link], Professor, SPRING
Dept. of ISE, HKBKCE. SUMMER
FALL 50
// Ex-2 An enumeration of apple varieties.
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
class EnumDemo {
public static void main(String args[])
{
Apple ap;
ap = [Link];
// Output an enum value.
[Link]("Value of ap: " + ap);
[Link]();
ap = [Link];
// Compare two enum values.
if(ap == [Link])
[Link]("ap contains GoldenDel.\n");
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 51
// Use an enum to control a switch statement.
switch(ap) {
case Jonathan:
[Link]("Jonathan is red.");
break;
case GoldenDel:
[Link]("Golden Delicious is yellow.");
break;
case RedDel:
[Link]("Red Delicious is red.");
break;
case Winesap:
[Link]("Winesap is red.");
break;
case Cortland:
[Link]("Cortland is red.");
break;
}
}
}
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 52
The values( ) and valueOf( ) Methods
• All enumerations automatically contain two
predefined methods: values( ) and valueOf( ).
public static enum-type[ ] values( )
public static enum-type valueOf(String str)
• The values( ) method returns an array that contains a
list of the enumeration constants.
• The valueOf( ) method returns the enumeration
constant whose value corresponds to the string
passed in str.
• In both cases, enum-type is the type of the
enumeration.
• The ordinal() method returns the index of the enum
value.
final int ordinal( ) 53
Class Types
// Use an enum constructor, instance variable, and method.
enum Apple {
Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);
private int price;
// Constructor
Apple(int p) {
price = p;
}
int getPrice() {
return price;
}
Dr. [Link], Professor,
} Dept. of ISE, HKBKCE.
54
class EnumDemo3 {
public static void main(String args[])
{
Apple ap;
// Display price of Winesap.
[Link]("Winesap costs " +[Link]() +" cents.\n");
// Display all apples and prices.
[Link]("All apple prices:");
for(Apple a : [Link]())
[Link](a + " costs " + [Link]() +" cents.");
}
}
Winesap costs 15 cents.
All apple prices:
Jonathan costs 10 cents.
GoldenDel costs 9 cents.
RedDel costs 12 cents.
Dr. [Link], Professor, Winesap costs 15 cents.
Dept. of ISE, HKBKCE. Cortland costs 8 cents. 55
Enumerations Inherit Enum
• The ordinal() method returns the index of the
enum value.
final int ordinal( )
• You can compare the ordinal value of two
constants of the same enumeration by using
• the compareTo( ) method.
final int compareTo(enum-type e)
• You can compare for equality an enumeration
constant with any other object by using equals( )
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 56
class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }
public static void main(String[] args) {
//printing all enum
for (Season s : [Link]()){
[Link](s);
}
[Link]("Value of WINTER is: "+[Link]("WINTER"));
[Link]("Index of WINTER is: "+[Link]("WINTER").ordinal());
[Link]("Index of SUMMER is: "+[Link]("SUMMER").ordinal());
}
}
Output:
WINTER
SPRING
SUMMER
Dr. [Link], Professor, FALL
Dept. of ISE, HKBKCE. Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2 57
// Demonstrate ordinal(), compareTo(), and equals().
// An enumeration of apple varieties.
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
class EnumDemo4 {
public static void main(String args[])
{
Apple ap, ap2, ap3;
// Obtain all ordinal values using ordinal().
[Link]("Here are all apple constants" + " and their ordinal values: ");
for(Apple a : [Link]())
[Link](a + " " + [Link]());
ap = [Link];
ap2 = [Link];
ap3 = [Link];
[Link]();
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 58
// Demonstrate compareTo() and equals()
if([Link](ap2) < 0)
[Link](ap + " comes before " + ap2);
if([Link](ap2) > 0)
[Link](ap2 + " comes before " + ap);
if([Link](ap3) == 0)
[Link](ap + " equals " + ap3);
[Link]();
if([Link](ap2))
[Link]("Error!");
if([Link](ap3))
[Link](ap + " equals " + ap3);
if(ap == ap3)
[Link](ap + " == " + ap3);
}
}
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 59
Here are all apple constants and their ordinal values:
Jonathan 0
GoldenDel 1
RedDel 2
Winesap 3
Cortland 4
GoldenDel comes before RedDel
RedDel equals RedDel
RedDel equals RedDel
RedDel == RedDel
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 60
Topics Covered
• Wrapper
• Autoboxing
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 61
Type Wrappers
• Java provides type wrappers, which are
classes that encapsulate a primitive type
within an object.
• Wrapper classes provide a way to use
primitive data types (int, boolean, etc..) as
objects.
• The eight classes of the [Link] package
are known as wrapper classes in Java.
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 62
Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 63
Character
• Character is a wrapper around a char. The
constructor for Character is
Character(char ch)
• Here, ch specifies the character that will be
wrapped by the Character object being created.
• To obtain the char value contained in a Character
object, call charValue( ), shown here:
char charValue( )
• It returns the encapsulated character.
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 64
Boolean
• Boolean is a wrapper around boolean values. It defines
these constructors:
Boolean(boolean boolValue)
Boolean(String boolString)
• In the first version, boolValue must be either true or false. In
the second version, if boolString contains the string “true”
(in uppercase or lowercase), then the new Boolean object
will be true. Otherwise, it will be false.
• To obtain a boolean value from a Boolean object, use
booleanValue( ), shown here:
boolean booleanValue( )
• It returns the boolean equivalent of the invoking object.
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 65
The Numeric Type Wrappers
• The most commonly used type wrappers are those that
represent numeric values.
• These are Byte, Short, Integer, Long, Float, and Double.
• All of the numeric type wrappers inherit the abstract class
Number.
• Number declares methods that return the value of an object
in each of the different number formats.
• These methods are shown here:
byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )
66
The Numeric Type Wrappers
• All of the numeric type wrappers define
constructors that allow an object to be
constructed from a given value, or a string
representation of that value.
• For example, here are the constructors defined for
Integer:
Integer(int num)
Integer(String str)
• If str does not contain a valid numeric value, then
a NumberFormatException is thrown.
• All of the type wrappers override toString( ).
67
// Demonstrate a type wrapper.
class Wrap {
public static void main(String args[]) {
Integer iOb = new Integer(100);
int i = [Link]();
[Link](i + " " + iOb); // displays 100 100
}
}
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 68
Boxing & unboxing
• The process of encapsulating a value within an
object is called boxing.
• Thus, in the program, this line boxes the value 100
into an Integer:
Integer iOb = new Integer(100);
• The process of extracting a value from a type
wrapper is called unboxing.
• For example, the program unboxes the value in
iOb with this statement:
int i = [Link]();
69
Why we need Wrapper Class
• To use data types in the form of objects we use wrapper
classes.
• Wrapper Class will convert primitive data types into objects.
The objects are necessary if we wish to modify the
arguments passed into the method (because primitive types
are passed by value).
• The classes in [Link] package handles only objects and
hence wrapper classes help in this case also.
• Data structures in the Collection framework such
as ArrayList and Vector store only the objects (reference
types) and not the primitive types.
• The object is needed to support synchronization in
multithreading.
• Wrapper class in Java is mainly an object which makes the
code fully object oriented.
70
Autoboxing
• The automatic conversion of primitive data type
into its corresponding wrapper class is known as
autoboxing.
• For example,
byte to Byte, char to Character, int to Integer, long
to Long, float to Float, boolean to Boolean,
double to Double, and short to Short.
• Since Java 5, we do not need to use the valueOf()
method of wrapper classes to convert the
primitive into objects.
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 71
Autoboxing and Methods
• Autoboxing automatically occurs whenever a
primitive type must be converted into an object;
auto-unboxing takes place whenever an object
must be converted into a primitive type.
• Thus, autoboxing/unboxing might occur when an
argument is passed to a method, or when a value
is returned by a method.
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 72
// Autoboxing/unboxing takes place with
// method parameters and return values.
class AutoBox2 {
static int m(Integer v) {
return v ; // auto-unbox to int
}
public static void main(String args[]) {
Integer iOb = m(100);
[Link](iOb);
}
}
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 73
Autoboxing/Unboxing Occurs in Expressions
• In general, autoboxing and unboxing take place
whenever a conversion into an object or from an
object is required. This applies to expressions.
• Within an expression, a numeric object is
automatically unboxed. The outcome of the
expression is reboxed, if necessary.
Dr. [Link], Professor, Dept. of ISE, HKBKCE. 74
// Autoboxing/unboxing occurs inside expressions.
class AutoBox3 {
public static void main(String args[]) {
Integer iOb, iOb2;
int i;
iOb = 100;
[Link]("Original value of iOb: " + iOb);
++iOb;
[Link]("After ++iOb: " + iOb);
iOb2 = iOb + (iOb / 3);
[Link]("iOb2 after expression: " + iOb2);
i = iOb + (iOb / 3);
[Link]("i after expression: " + i);
}
}
Original value of iOb: 100
After ++iOb: 101
iOb2 after expression: 134
i after expression: 134 75
Thank You
76