Sie sind auf Seite 1von 158

www.csetube.

in
CS2305 / CS55 / 10144CS506
PROGRAMMING PARADIGMS
NOTES
Unit No Title
6) A cce s s Sp ec ifie rs
7) Static Me m bers
8) C on s tr u c tor s
a) Parameterized Const r uctors
b) this Key w ord
c) Ga r bag e C oll ec tion
9) F inali z e Me thod
10) Arr a s
a) One Dimensional Arrays
b) Multi Dimensional Arrays
11) St r in! s
1") #a c $a! es
1%) &a'a()C Com m ents
14) Re f een!e"
1# Re$ie% OOP !on!e&t"
The object oriented paradigm is built on the foundation laid by the structured
programming concepts.
The fundamental change in OOP is that a program is designed around the data
being operated upon rather upon the operations themselves.
Data and its functions are encapsulated into a single entity.
OOP facilitates creating reusable code that can eventually save a lot of work.
Polymorphism permits to create multiple definitions for functions.
Inheritance permits to derive new classes from old ones.
'enefit" of o()e!t oiente* &o+,--in+
Data security is enforced.
Inheritance saves time.
ser defined data types can be easily constructed.
Page 2 of !"
!
www.csetube.in
"ll #ava programs are object oriented. $omputer programs consist of two elements% code
and data.
In process oriented model code acting on data. Procedural languages such as $ employ
this model.
To manage increasing comple&ity object'oriented Programming approach was conceived.
Object'oriented programming organi(es a program around its data )that is* objects+ and a
set of well'defined interfaces to that data. "n object'oriented program can be
characteri(ed as data controlling access to code.
A("t,!tion
"n essential element of object'oriented programming is abstraction. "bstraction refers to
the act of representing essential features without including the background details or
e&planations.
,or e&ample* people do not think of a car as a set of tens of thousands of individual parts.
They think of it as a well'defined object with its own uni-ue behavior. This abstraction allows
people to use a car to drive to the grocery store without being overwhelmed by the comple&ity of
the parts that form the car. They can ignore the details of how the engine* transmission* and
braking systems work. Instead they are free to utili(e the object as a whole.
T.e T.ee OOP Pin!i&le"
"ll object'oriented programming languages provide mechanisms to implement the
object'oriented model. They are
.ncapsulation
Inheritance
Polymorphism
Page # of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
,) En!,&"/l,tion
.ncapsulation is the mechanism that binds together code and the data it manipulates* and
keeps both safe from outside interference and misuse.
,or e&ample* shifting gears does not turn on the headlights in car* because it encapsulates
the information about all process.
In #ava the basis of encapsulation is the class. " class defines the structure and behavior
)data and code+ that will be shared by a set of objects. ,or this reason* objects are sometimes
referred to as instances of a class. Thus* a class is a logical construct and an object has physical
reality.
() In.eit,n!e
Inheritance is the process by which one object ac-uires the properties of another object.
This is important because it supports the concept of hierarchical classification. ,or e&ample
/ird
"ttributes%
,eathers
0ay eggs
,lying 1on flying
bird bird
"ttributes% "ttributes%
''''''''''' '''''''''''
'''''''''' '''''''''''
The bird 2robin 2 is a part of the class 2flying bird2 which is again a part of the class 2bird2.
The concept of inheritance provides the idea of reusability.
!) Pol0-o&.i"-
Polymorphism means the ability to take more than one form. 3ubclasses of a class can
define their own uni-ue behaviors and yet share some of the same functionality of the parent
class.
3hape
Draw)+
$ircle Object /o& Object Triangle Object
Draw)+ Draw)+ Draw)+
2# Cl,"" ,n* O()e!t
$lass defines a new data type. Once defined* this new type can be used to create objects
of that type. Thus* a class is a template for an object* and an object is an instance of a class.
Cl,""
" class is a blueprint or prototype from which objects are created. The entire set of data
and code of an object can be made of a user defined data type with the help of a class. 4e can
create any number of objects for the same class.
Page $ of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
,or e&ample the construction of building re-uires a plan. 4ithout plan we can2t construct
building. 5ere plan acts as class. /uilding acts as object. sing the same plan we can build any
number of buildings. In the same way we can create any number of objects for the same class.
$lass tells the object6s state and behavior. /asically class tells what the object should have.
O()e!t
Object is an instance of class. Object is real world entity which has state* identity and
behavior. It may represent a person* a place* a bank account* a table of data or any item that the
program has to handle.
1A2A Po+,- "t/!t/e
" file containing #ava source code is considered a compilation unit. 3uch a compilation
unit contains a set of classes and* optionally* a package definition to group related classes
together. $lasses contain data and method members that specify the state and behavior of the
objects in your program. #ava programs come in two flavors%
7. 3tandalone applications that have no initial conte&t such as a pre'e&isting main window
8. "pplets for 444 programming
.&ecution begins when you launch the java virtual machine and tell it to find a particular class.
"fter finding the class* java e&ecutes the enclosed main)+ method with signature%
public static void main)3tring9: args+
;
<<<...
=
Po+,- E3e!/tion
$reate a source code file using a te&t editor. The source code is then compiled using the
java compiler javac. .ach java program is converted into one or more class files. The content of
the class file is a set of instructions called bytecode to be e&ecuted by #ava >irtual ?achine
)#>?+.#ava introduces bytecode to create platform independent program. #>? is an interpreter
for bytecode which accepts java bytecode and produces result.
#ava 3ource $ode
#ava $ompiler )#avac+
#ava /yte $ode ).class+
#ava >irtual ?achine
#ava program Output
Page ! of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
3# 4,n+/,+e ',"i!"
,) Co--ent"
#ava comments make your code easy to understand* modify and use. #ava supports three
different types of comment styles.
7..verything between initial slash @asterisk and ending asterisk'slash is ignored by the java
compiler.)AB<<BA+
8.Double slash )AA+mark is ignored by java compiler.
C..verything between initial slash @ asterisk ' asterisk and ending asterisk'slash is ignored
by the java compiler and another program called #">"DO$..D. that ships with the
#DE uses these comments to construct 5T?0 documentation files that describe your
packages* classes and methods as well as all the variables used. )ABB<<BA+
() D,t, T0&e"
#ava defines eight simple )or elemental+ types of data% (0te* ".ot* int* lon+* !.,* flo,t*
*o/(le* and (oole,n. These can be put in four groups%
Integers ' This group includes (0te* ".ot* int* and lon+* which are for whole valued
signed numbers.
,loating 'point numbers' This group includes flo,t and *o/(le* which represent numbers
with fractional precision.
$haracters ' This group includes !.,* which represents symbols in a character set* like
letters and numbers.
/oolean ' This group includes (oole,n* which is a special type for representing trueAfalse
values.
!) 2,i,(le"
>ariables are locations in memory in which values can be stored. They have a name* a
type* and a value. /efore you can use a variable* you have to declare it. "fter it is declared* you
can then assign values to it.
#ava actually has three kinds of variables% instance variables* class variables* and local
variables.
Instance variables are used to define attributes or the state for a particular object.
$lass variables are similar to instance variables* e&cept their values apply to all
that class6s instances )and to the class itself+ rather than having different values
for each object.
0ocal variables are declared and used inside method definitions* for e&ample* for
inde& counters in loops* as temporary variables* or to hold values that you need
only inside the method definition itself.
"lthough all three kinds of variables are declared in much the same ways* class and
instance variables are accessed and assigned in slightly different ways from local variables.
S!o&e
Page % of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
#ava has no global variables.
"ll variables must be declared within either a class scope or a function scope.
De!l,in+ 2,i,(le"
,or variable declarations* #ava synta& is similar to $ and $FF synta&. ,or native types*
the synta& may be summari(ed as follows%
One word type name.
" list of variable names* separated by commas.
"n optional initiali(er following each variable name.
Terminated by semicolon.
The following are e&amples of variable declarations%
This line of #ava code declares a C8'bit integer variable named i%
int iG
This line declares two C8'bit integer variables named i and j%
int i * jG
This line declares i and j as above and initiali(es them%
int iHC* jHIG
*) St,te-ent"
#ava* like $* is an e&pression'based language. .&pressions must always appear in the
conte&t of statements. " statement consists of an e&pression followed by a terminating semicolon
)G+.
3tatements can be made up of (ero or more e&pressions* provided that their combination
makes syntactic sense. .&pressions )e&cept for the return value of void methods+ have a value
and a type. " terminating semicolon )e.g.* 8JG+ turns it into a legal statement even though it does
not do anything useful. " simple statement consists of an e&pression and a semicolon. The
semicolon is a re-uired terminator.
4# Definin+ Cl,""
The class is at the core of #ava. It is the logical construct upon which the entire #ava
language is built because it defines the shape and nature of an object. "s such* the class forms
the basis for object'oriented programming in #ava. The entire set of data and code of an object
can be made of a user defined data type with the help of a class. Thus* a class is a template for an
object* and an object is an instance of a class.
T.e Gene,l 5o- of , Cl,""
The class contains data and the code that operates on that data. " class is declared by use
of the class keyword. The data* or variables* defined within a class are called instance variables.
The code is contained within methods. $ollectively* the methods and variables defined within a
class are called members of the class. The general form of a class definition is shown here%
class classname
;
type instance'variable7G
type instance'variable8G
Page & of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
AA ...
type instance'variable1G
type methodname7)parameter'list+;
AA body of method
=
type methodname8)parameter'list+ ;
AA body of method
=
AA ...
type methodname1)parameter'list+ ;
AA body of method
=
=
5ere is a class called 'o3 that defines three instance variables% %i*t.* .ei+.t* and *e&t..
$urrently* 'o3 does not contain any methods )but some will be added soon+.
class /o&
;
double widthG
double heightG
double depthG
=
In"t,nti,tin+ , !l,""
$lass declaration only creates a templateG it does not create an actual object. To create a
/o& object* you will use a statement like the following%
/o& mybo& H new /o&)+G AA create a /o& object called mybo&
The new operator allocates space for the new object* calls a class constructor and returns
a reference to the object.
It should be noted that the class and its constructor have the same name.
"fter this statement e&ecutes* mybo& will be an instance of /o&. .ach time you create an
instance of a class* you are creating an object that contains its own copy of each instance variable
defined by the class. Thus* every /o& object will contain its own copies of the instance variables
width* height* and depth. To access these variables* you will use the dot ).+ operator. The dot
operator links the name of the object with the name of an instance variable. ,or e&ample* to
assign the width variable of mybo& the value 7KK* you would use the following statement%
mybo&.width H 7KKG
This statement tells the compiler to assign the copy of width that is contained within the
mybo& object the value of 7KK.
5# Met.o*"
$lasses usually consist of two things% instance variables and methods.
This is the general form of a method%
Type name )parameter'list+
Page " of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
;
AA body of method
=
Type specifies the type of data returned by the method. This can be any valid type*
including class types that you create. If the method does not return a value* its return type must
be void.
The name of the method is specified by name. This can be any legal identifier other than
those already used by other items within the current scope.
The parameter'list is a se-uence of type and identifier pairs separated by commas.
Parameters are essentially variables that receive the value of the arguments passed to the method
when it is called. If the method has no parameters* then the parameter list will be empty.
?ethods that have a return type other than void return a value to the calling routine using
the following form of the return statement%
return valueG
5ere* value is the value returned.
Program includes a method inside the bo& class.
class /o&
;
double widthG
double heightG
double depthG
AA display volume of a bo&
void volume)+ ;
3ystem.out.print)L>olume is L+G
3ystem.out.println)width B height B depth+G
=
=
class /o&DemoC
;
public static void main)3tring args9:+ ;
/o& mybo&7 H new /o&)+G
/o& mybo&8 H new /o&)+G
AA assign values to mybo&72s instance variables
mybo&7.width H 7KG
mybo&7.height H 8KG
mybo&7.depth H 7MG
AB assign different values to mybo&82s instance variables BA
mybo&8.width H CG
mybo&8.height H NG
mybo&8.depth H OG
AA display volume of first bo&
mybo&7.volume)+G
AA display volume of second bo&
Page ' of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
mybo&8.volume)+G
=
=
This program generates the following output.
T5. #">" 0"1P"P.
>olume is CKKK.K
>olume is 7N8.K
The mybo&7.volume)+ invokes the $ol/-e6 ) method on -0(o31. That is* it calls
$ol/-e6 ) relative to the -0(o31 object* using the object6s name followed by the dot operator.
Thus* the call to -0(o31#$ol/-e6 ) displays the volume of the bo& defined by -0(o31* and the
call to -0(o32#$ol/-e6 ) displays the volume of the bo& defined by -0(o32. .ach time
$ol/-e6 ) is invoked* it displays the volume for the specified bo&.
6# A!!e"" "&e!ifie"
.ncapsulation provides another important attribute% access control. Through
encapsulation* you can control what parts of a program can access the members of a class. /y
controlling access* you can prevent misuse.
5ow a member can be accessed is determined by the access specifier that modifies its
declaration. #ava supplies a rich set of access specifiers. 3ome aspects of access control are
related mostly to inheritance or packages. )" package is* essentially* a grouping of classes.+
#ava6s access specifiers are
Public
Private
Protected
default access level.
P/(li!
4hen a member of a class is modified by the public specifier* then that member can be
accessed by any other code. 3o main) + has always been preceded by the public specifier.
$lasses can be declared public. " public class is accessible by any other #ava class. "
class that is not declared public has package access* which means that only classes within the
same package may access it. $lass members labeled public are accessible to all other classes.
Pi$,te
4hen a member of a class is specified as private* then that member can only be accessed
by other members of its class.
$lass members can be declared public or private to enforce proper encapsulation. $ertain
data elements or methods that are necessary for the class6s internal behavior should be protected
from access by outside classes. These should be declared private. " class member that has been
declared as private will remain private to its class. It is not accessible by any code outside its
class* including subclasses.
Pote!te*
"ny member that is declared protected is accessible only by a class that is derived from
the current class or is in the same package as the containing class.
Page ( of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
*ef,/lt ,!!e"" le$el
4hen no access specifier is used* then by default the member of a class is public within
its own package* but cannot be accessed outside of its package.
7# St,ti! Me-(e"
St,ti! 2,i,(le"
If you define a field as static* then there is only one such field per class. In contrast* each
object has its own copy of all instance fields. ,or e&ample* let2s suppose we want to assign a
uni-ue identification number to each employee. 4e add an instance field id and a static field
ne&tId to the .mployee class%
class .mployee
;
. . .
private int idG
private static int ne&tId H 7G
=
1ow* every employee object has its own id field* but there is only one ne&tId field that is shared
among all instances of the class. 0et2s put it another way. If there are one thousand objects of the
.mployee class* then there are one thousand instance fields id* one for each object. /ut there is a
single static field ne&tId. .ven if there are no employee objects* the static field ne&tId is present.
It belongs to the class* not to any individual object.
Con"t,nt"
3tatic variables are -uite rare. 5owever* static constants are more common. ,or e&ample*
the ?ath class defines a static constant%
public class ?ath
;
. . .
public static final double PI H C.7I7MO8NMCMQOJOC8CQING
Page of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
. . .
=
Rou can access this constant in your programs as ?ath.PI. If the keyword static had been
omitted* then PI would have been an instance field of the ?ath class. That is* you would need an
object of the ?ath class to access PI* and every object would have its own copy of PI. "nother
static constant that you have used many times is 3ystem.out. It is declared in the 3ystem class as%
public class 3ystem
;
. . .
public static final Print3tream out H . . .G
. . .
=
"s we mentioned several times* it is never a good idea to have public fields because everyone
can modify them. 5owever* public constants )that is* final fields+ are ok. 3ince out has been
declared as final* you cannot reassign another print stream to it%
out H new Print3tream). . .+G AA .SSOS''out is final
St,ti! Met.o*"
3tatic methods are methods that do not operate on objects. ,or e&ample* the pow method
of the ?ath class is a static method. The e&pression%
?ath.pow)&* y+
$omputes the power &y. It does not use any ?ath object to carry out its task. In other words* it
has no implicit parameter. In other words* you can think of static methods as methods that don2t
have a this parameter. /ecause static methods don2t operate on objects* you cannot access
instance fields from a static method. /ut static methods can access the static fields in their class.
5ere is an e&ample of such a static method%
public static int get1e&tId)+
;
return ne&tIdG AA returns static field
=
To call this method* you supply the name of the class%
int n H .mployee.get1e&tId)+G
$ould you have omitted the keyword static for this methodT Res* but then you would need to
have an object reference of type .mployee to invoke the method. Rou use static methods in two
situations%
7. 4hen a method doesn2t need to access the object state because all needed
parameters are supplied as e&plicit parameters )e&ample% ?ath.pow+
8. 4hen a method only needs to access static fields of the class )e&ample%
.mployee.get1e&tId+
8# Con"t/!to"
" constructor is a special method whose purpose is to construct and initiali(e objects.
$onstructors always have the same name as the class name.
The constructor is automatically called immediately after the object is created* before the
new operator completes.
/o& mybo&7 H new /o&)+G
Page 2 of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
new /o&) + is calling the /o&) + constructor. 4hen you do not e&plicitly define a
constructor for a class* then #ava creates a default constructor for the class. The default
constructor automatically initiali(es all instance variables to (ero.
There is an important difference between constructors and other methods% " constructor
can only be called in conjunction with the new operator. Rou can2t apply a constructor to an
e&isting object to reset the instance fields.
5e,t/e" of !on"t/!to
" constructor has the same name as the class.
" class can have more than one constructor.
" constructor may take (ero* one* or more parameters.
" constructor has no return value.
" constructor is always called with the new operator.
,) P,,-etei9e* Con"t/!to"
"dd parameters to the constructor.
class /o&
;
double widthG
double heightG
double depthG
AA This is the constructor for /o&.
/o&)double w* double h* double d+ ;
width H wG
height H hG
depth H dG
=
AA compute and return volume
double volume)+ ;
return width B height B depthG
=
=
class /o&DemoJ
;
public static void main)3tring args9:+ ;
AA declare* allocate* and initiali(e /o& objects
/o& mybo&7 H new /o&)7K* 8K* 7M+G
double volG
AA get volume of first bo&
vol H mybo&7.volume)+G
3ystem.out.println)L>olume is L F vol+G
=
=
The output from this program is shown here%
>olume is CKKK.K
Page # of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Object is initiali(ed as specified in the parameters to its constructor.
/o& mybo&7 H new /o&)7K* 8K* 7M+G
The values 7K* 8K* and 7M are passed to the 'o36 ) constructor when ne% creates the object.
Thus* -0(o316s copy of %i*t.* .ei+.t* and *e&t. will contain the values 7K* 8K* and 7M*
respectively.
() :t.i"; <e0%o*
this can be used inside any method to refer to the current object. this keyword has two
meanings%
to denote a reference to the implicit parameter
to call another constructor of the same class.
AA " redundant use of this.
/o&)double w* double h* double d+
;
this.width H wG
this.height H hG
this.depth H dG
=
!) G,(,+e Colle!tion
The purpose of garbage collection is to identify and discard objects that are no longer
needed by a program so that their resources can be reclaimed and reused. " #ava object is subject
to garbage collection when it becomes unreachable to the program in which it is used.
=# 5in,li9e -et.o*
,inali(er methods are like the opposite of constructor methodsG whereas a constructor
method is used to initiali(e an object* finali(er methods are called just before the object is
garbage collected and its memory reclaimed. To create a finali(er method* include a method with
the following signature in your class definition%
void finali(e)+ ;
...
=
Inside the body of that finali(e)+ method* include any cleaning up you want to do for that
object. /efore you start using finali(er methods e&tensively in your #ava programs* however* be
aware that finali(er methods have several very important restrictions. ,irst of all* the finali(er
method is not guaranteed to be called until the object6s memory is actually reclaimed* which may
be some time after you6ve removed all references to that object.
5owever* calling finali(e)+ does not trigger an object to be garbage'collected. Only
removing all references to an object will cause it to be marked for deleting* and even then* #ava
may or may not call the finali(e)+ method itselfUregardless of whether or not you6ve already
called it. ,inali(er methods are best used for optimi(ing the removal of an objectUfor e&ample*
by removing references to other objects* by cleaning up things that object may have touched* or
for other optional behaviors that may make it easier for that object to be removed. In most cases*
you may not need to use finali(e)+ at all.
Page $ of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
3ome object'oriented programming languages* notably $FF* have e&plicit destructor
methods for any cleanup code that may be needed when an object is no longer used. The most
common activity in a destructor is reclaiming the memory set aside for objects. 3ince #ava does
automatic garbage collection* manual memory reclamation is not needed* and #ava does not
support destructors. Of course* some objects utili(e a resource other than memory* such as a file
or a handle to another object that uses system resources. In this case* it is important that the
resource be reclaimed and recycled when it is no longer needed. Rou can add a finali(e method
to any class. The finali(e method will be called before the garbage collector sweeps away the
object. In practice* do not rely on the finali(e method for recycling any resources that are in short
supplyUyou simply cannot know when this method will be called. If a resource needs to be
closed as soon as you have finished using it* you need to manage it manually. "dd a dispose
method that you call to clean up what needs cleaning. #ust as importantly* if a class you use has a
dispose method* you will want to call it when you are done with the object. In particular* if your
class has an instance field that has a dispose method* provide a dispose method that disposes of
the instance fields.
10# A,0"
"n array is a group of like'typed variables that are referred to by a common name. "rrays
of any type can be created and may have one or more dimensions. " specific element in an array
is accessed by its inde&. "rrays offer a convenient means of grouping related information.
"rrays are ordered collections of identical objects that can be accessed via an inde&. #ava
arrays have their own behavior that is encapsulated into their definition when the compiler
creates them. 3ince arrays are objects* array variables behave like class'type variables. It is
important to distinguish between the array variable and the array instance to which it refers.
Declaring an array only declares the array variable.
To instantiate the array* the new operator must be used with the 9: operator to
enclose the array si(e. The array si(e can be any integer e&pression.
The following code declares an array variable and initiali(es it to null%
char data9: H nullG
A,0 Con"t,nt"
The declaration of an array must include its type* but not its si(e. "n array initiali(er is
either a new e&pression that evaluates to the correct array type* or a list of initial element values
enclosed in ; =. The following array constant provides initial values for its elements%
int9: intVarray H ;7* C* I* 7M* K=G
U"in+ A,0"
"rray elements can be accessed using an inde& in s-uare brackets 9n:* where the inde&
must be an integer. "rrays start with inde& number K* not 7. The inde& can be thought of as an
offset from the beginning of the array. The inde& may not be less than (ero or greater than the
declared si(e. If the array is declared si(e n* the inde& must be in the range K to n'7. "ny attempt
to inde& an array with an illegal value will cause an e&ception to be thrown. "ll arrays have a
data field called length that indicates its si(e.
int ia9: H new int97KK:G
for )int i H KG i W ia.lengthG iFF+
;
Page ! of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
ia9i: H i B iG
=
Co&0in+ A,0 Ele-ent"
The library method 3ystem.arraycopy)+ is useful for copying a number of elements from
one array to another. The method can be used on any type of array and is declared as follows%
public static void arraycopy )Object src* int srcVposition* Object dst* int dstVposition* int
length+
The method copies elements from the given source array* beginning at the specified
position to the destination array at the specified position. It copies the number of elements
specified by the length argument. The destination array must already be allocated. "ny type of
array may be copied. If range e&ceeds bounds of either array* a run'time error results.
"rrays in #ava are in between a class and a data type although they are implemented as a
class internally by #ava.
char data9: H nullG
char9: data H nullG
int length H NKG
char9: data H new char 9length:G
,) One>Di-en"ion,l A,0"
" one'dimensional array is a list of like'typed variables. "rray is created by following steps.
7. $reate an array variable of the desired type. The general form of a one dimensional array
declaration is
type var'name9 :G
8. "llocate memory for array.
Met.o*1? The general form of ne% as it applies to one'dimensional arrays appears as
follows%
array'var H new type9si(e:G
The elements in the array allocated by ne% will automatically be initiali(ed to (ero.
Met.o*2? "rrays can be initiali(ed when they are declared. The process is much the
same as that used to initiali(e the simple types. "n array initiali(er is a list of comma'
separated e&pressions surrounded by curly braces. The commas separate the values of the
array elements. The array will automatically be created large enough to hold the number
of elements you specify in the array initiali(er. There is no need to use ne%. ,or e&ample*
to store the number of days in each month* the following code creates an initiali(ed array
of integers%
AA "n improved version of the previous program.
class "uto"rray ;
public static void main)3tring args9:+ ;
int monthVdays9: H ; C7* 8Q* C7* CK* C7* CK* C7* C7* CK* C7*CK* C7 =G
3ystem.out.println)L"pril has L F monthVdays9C: F L days.L+G
=
=
Page % of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
() M/lti*i-en"ion,l A,0"
In #ava* multidimensional arrays are actually arrays of arrays. These* as you might
e&pect* look and act like regular multidimensional arrays. 5owever* as you will see* there are a
couple of subtle differences. To declare a multidimensional array variable* specify each
additional inde& using another set of s-uare brackets. ,or e&ample* the following declares a two'
dimensional array variable called t%oD.
int twoD9:9: H new int9I:9M:G
This allocates a I by M array and assigns it to t%oD. Internally this matri& is implemented as an
array of arrays of int.
There is a second form that may be used to declare an array%
type9 : var'nameG
5ere* the s-uare brackets follow the type specifier* and not the name of the array variable. ,or
e&ample* the following two declarations are e-uivalent%
int al9: H new int9C:G
int9: a8 H new int9C:G
The following declarations are also e-uivalent
11# Stin+ o()e!t"
The #ava 3tring class )java.lang.3tring+ is a class of object that represents a character
array of arbitrary length. 4hile this e&ternal class can be used to handle string objects* #ava
integrates internal* built'in strings into the language.
Page & of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
"n important attribute of the 3tring class is that once a string object is constructed* its
value cannot change )note that it is the value of an object that cannot change* not that of a string
variable* which is just a reference to a string object+. "ll 3tring data members are private* and no
string method modifies the string6s value.
Stin+ Met.o*"
"lthough a string represents an array* standard array synta& cannot be used to in-uire into
it. These are detailed in the below Table.
Stin+ Co-&,i"on
3tring comparison methods listed in below Table.
Page " of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Stin+ Se,!.in+
The 3tring class also provides methods that search a string for the occurrence of a single
character or substring. These return the inde& of the matching substring or character if found* or '
7 if not found.
int inde&Of )char ch+
int inde&Of )char ch* int begin+
int lastInde&Of )char ch+
int lastInde&Of )char ch* int fromInde&+
int inde&Of )3tring str+
int inde&Of )3tring str* int begin+
int lastInde&Of )3tring str+
int lastInde&Of )3tring str* int fromInde&+
The following e&ample shows the usage of these functions%
if )s7.inde&Of )6%6+ XH K+
;
<
=
3tring suffi& H
s7.substring )s7.lastInde&Of )6.6++G
int space$ount H KG
int inde& H s7.inde&Of )6 6+G
while )inde& XH K+
;
FFspace$ountG
inde& H s7.inde&Of )6 6* inde& F 7+G
Page ' of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
=
int inde& H s7.inde&Of )Ythat +G
Stin+ Con!,ten,tion
The 3tring class provides a method for concatenating two strings%
3tring concat )3tring other3tring+
The F and FH 3tring operators are more commonly used% The #ava compiler recogni(es the F and
FH operators as 3tring operators. ,or each F e&pression* the compiler generates calls to methods
that carry out the concatentation. ,or each FH e&pression* the compiler generates calls to
methods that carry out the concatenation and assignment.
Con$etin+ O()e!t" To Stin+"
The 3tring F operator accepts a non'string operand* provided the other operand is a
string. The action of the F operator on non'string operands is to convert the non'string to a string*
then to do the concatenation. Operands of native types are converted to string by formatting their
values. Operands of class types are converted to a string by the method to3tring)+ that is defined
for all classes. "ny object or value can be converted to a string by e&plicitly using one of the
static valueOf)+ methods defined in class 3tring%
3tring str H 3tring.valueOf )obj+G
If the argument to valueOf)+ is of class type* then valueOf)+ calls that object6s to3tring)+ method.
"ny class can define its own to3tring)+ method* or just rely on the default. The output produced
by to3tring)+ is suitable for debugging and diagnostics. It is not meant to be an elaborate te&t
representation of the object* nor is it meant to be parsed. These conversion rules also apply to the
right'hand side of the 3tring FH operator.
Con$etin+ Stin+" To N/-(e"
?ethods from the various wrapper classes* such as Integer and Double* can be used to
convert numerical strings to numbers.
The wrapper classes contain static methods such as parseInt)+ which convert a string to its
own internal data type.
12# P,!@,+e"
#ava allows you to group classes in a collection called a package. " class can use all
classes from its own package and all public classes from other packages.
Rou can import a specific class or the whole package. Rou place import statements at the
top of your source files )but below any package statements+. ,or e&ample* you can import all
classes in the java.util package with the statement%
import java.util.BG
A**in+ , !l,"" into , &,!@,+e
To place classes inside a package* you must put the name of the package at the top of
your source file* before the code that defines the classes in the package. ,or e&ample*
package com.horstmann.corejavaG
public class .mployee
Page 2( of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
;
. . .
=
P,!@,+e "!o&e
Public features can be used by any class.
Private features can only be used by the class that defines them.
If you don2t specify either public or private* then the feature )that is* the class* method* or
variable+ can be accessed by all methods in the same package.
13# Do!/-ent,tion Co--ent"
The #ava 3DE contains a very useful tool* called javadoc* that generates 5T?0
documentation from your source files. If you add comments that start with the special delimiter
ABB to your source code* you too can produce professional'looking documentation easily. This is
a very nice scheme because it lets you keep your code and documentation in one place. If you
put your documentation into a separate file* then you probably know that the code and comments
tend to diverge over time. /ut since the documentation comments are in the same file as the
source code* it is an easy matter to update both and run javadoc again.
Ao% to In"et Co--ent"
The javadoc utility e&tracts information for the following items%
Z Packages
Z Public classes and interfaces
Z Public and protected methods
Z Public and protected fields
Rou can )and should+ supply a comment for each of these features. .ach comment is
placed immediately above the feature it describes. " comment starts with a ABB and ends with a
BA. .ach ABB . . . BA documentation comment contains free'form te&t followed by tags. " tag starts
with an [* such as [author or [param. The first sentence of the free'form te&t should be a
summary statement. The javadoc utility automatically generates summary pages that e&tract
these sentences. In the free'form te&t* you can use 5T?0 modifiers such as WemX...WAemX for
emphasis* WcodeX...WAcodeX for a monospaced Ytypewriter font* WstrongX...WAstrongX for strong
emphasis* and even Wimg ...X to include an image. Rou should* however* stay away from
heading Wh7X or rules WhrX since they can interfere with the formatting of the document.
Cl,"" Co--ent"
The class comment must be placed after any import statements* directly before the class
definition. 5ere is an e&ample of a class comment%
ABB
" WcodeX$ardWAcodeX object represents a playing card* such as L\ueen of 5eartsL. "
card has a suit )Diamond* 5eart* 3pade or $lub+ and a value )7 H "ce* 8 . . . 7K* 77 H
#ack* 78 H \ueen* 7C H Eing+.
BA
public class $ard
Page 2 of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
;
. . .
=
Met.o* Co--ent"
.ach method comment must immediately precede the method that it describes. In
addition to the general'purpose tags* you can use the following tags%
[param variable description
This tag adds an entry to the Yparameters section of the current method. The description can
span multiple lines and can use 5T?0 tags. "ll [param tags for one method must be kept
together.
[return description
This tag adds a Yreturns section to the current method. The description can span multiple lines
and can use 5T?0 tags.
[throws class description
5iel* Co--ent"
Rou only need to document public fieldsUgenerally that means static constants. ,or
e&ample*
ABB
The L5eartsL card suit
BA
public static final int 5."ST3 H 7G
Gene,l Co--ent"
The following tags can be used in class documentation comments.
[author name
This tag makes an Yauthor entry. Rou can have multiple [author tags* one for each author.
[version te&t
Ao% to E3t,!t Co--ent"
5ere* docDirectory is the name of the directory where you want the 5T?0 files to go. ,ollow
these steps%
7. $hange to the directory that contains the source files you want to document. If you have
nested packages to document* such as com.horstmann.corejava* you must be in the
directory that contains the subdirectory com. )This is the directory that contains the
overview.html file* if you supplied one.+
2# Sun the command javadoc 'd docDirectory nameOfPackage for a single package. Or run
javadoc 'd docDirectory nameOfPackage7 nameOfPackage8... to document multiple
packages. If your files are in the default package* then run javadoc 'd docDirectory B.java
instead. If you omit the 'd docDirectory option* then the 5T?0 files are e&tracted to the
current directory. That can get messy* and we don2t recommend it. The javadoc program
can be fine'tuned by numerous command'line options. ,or e&ample* you can use the '
author and 'version options to include the [author and [version tags in the
documentation. )/y default* they are omitted.+
Page 22 of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
14# Refeen!e"
7. $ay 3. 5orstmann and Pary $ornell* Y$ore #ava% >olume I @ ,undamentals * .ighth
.dition* 3un ?icrosystems Press* 8KKQ.
8. 5erbert 3childt Y#">"8%The complete reference ,ifth .dition* ?cPraw'5illAOsborne.
C. h ttp%AAja v a.su n .com
Page 2# of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
UNIT II O'1ECT>ORIENTED PROGRAMMING B INAERITANCE
7. I n. e it,n ! e
1#1# Me - (e A!!e"" An* In.e it,n!e
1#2# S/&e <e0%o *
8. Cl,"" Aie,!. 0
C. Pol0-o&.i"-
3#1# O$ei**en M et.o*"
3#2# O$elo,*e* M et.o*"
I. D0n,-i! ' in*in+
4#1# D0n,-i! ' in*in+
4#2# St,ti! 'in * in +
5# 5 in, l <e0%o *
6# A("t,!t C l,""e"
6#1# A("t,!t M et.o*"
J. T.e O()e!t C l,""
Q. Refle!tio n
O. Intef,!e"
7K. O()e!t C lonin+
77. Inne C l,""e"
78. P o 3 ie"
In.eit,n!e
Inheritance is a process of making a new class that derives from an e&isting class. The
e&isting class is called the superclass* base class* or parent class. The new class is called the
subclass* derived class* or child class.
Therefore* a subclass is a speciali(ed version of a superclass. It inherits all of the
instance variables and methods defined by the superclass and add its own* uni-ue elements.
3ubclasses of a class can define their own uni-ue behaviors and yet share some of the
same functionality of the parent class.
To inherit a class* you simply incorporate the definition of one class into another by using
the e3ten*" keyword. The general form of a !l,"" declaration that inherits a superclass is shown
here%
class subclass'name e&tends superclass'name
;
AA body of class
=
Rou can only specify one superclass for any subclass that you create. #ava does not
support the inheritance of multiple superclasses into a single subclass.
Protected features in #ava are visible to all subclasses as well as all other classes in the
same package.
Page 2$ of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Me-(e A!!e"" ,n* In.eit,n!e
" class member that has been declared as private will remain private to its class. It is not
accessible by any code outside its class* including subclasses.
S/&e @e0%o*
3uper is a special keyword that directs the compiler to invoke the superclass method.
"/&e has two general forms.
to invoke a superclass constructor.
to invoke a superclass members)variables ]methods+. invoke a superclass
constructor
In$o@e "/&e!l,"" !on"t/!to?
" subclass can call a constructor method defined by its superclass by use of the following
form of "/&e%
super)parameter'list+G
5ere* parameter'list specifies any parameters needed by the constructor in the superclass.
"/&e6 ) must always be the first statement e&ecuted inside a subclass constructor.
The compiler implicitly calls the base class6s no'parameter constructor or default
constructor.
If the superclass has parameteri(ed constructor and the subclass constructor does not call
superclass constructor e&plicitly* then the #ava compiler reports an error.
In$o@e "/&e!l,"" -e-(e"?
S/&e always refers to the superclass of the subclass in which it is used. This usage has
the following general form%
super.memberG
5ere* member can be either a method or an instance variable. This second form of "/&e
is most applicable to situations in which member names of a subclass hide members by
the same name in the superclass.
If a parent class contains a finali(e)+ method* it must be called e&plicitly by the derived
class6s finali(e)+ method.
super.finali(e)+G
C.en Con"t/!to" ,e C,lle*
$onstructors are called in order of derivation* from superclass to subclass. /ecause a
superclass has no knowledge of any subclass* any initiali(ation it needs to perform is separate
from and possibly prere-uisite to any initiali(ation performed by the subclass. Therefore* it must
be e&ecuted first.
C4ASS AIERARCAD
The collection of all classes e&tending from a common superclass is called an inheritance
hierarchyG the path from a particular class to its ancestors in the inheritance hierarchy is its
inheritance chain.
3imple class hierarchies consist of only a superclass and a subclass. /ut you can build
hierarchies that contain as many layers of inheritance as you like.
Page 2! of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
,or e&ample* create three classes called A* '* and C* C can be a subclass of '* which is a
subclass of A. 4hen this type of situation occurs* each subclass inherits all of the traits found in
all of its superclasses. In this case* C inherits all aspects of ' and A.
PO4DMORPAISM
Polymorphism means the ability of methods to behave differently based on the kinds of
input.
T0&e" of &ol0-o&.i"-
?ethod Overloading
?ethod overriding
O$elo,*e* -et.o*"
Overloaded methods are methods with the same name but different method signature
)either a different number of parameters or different types in the parameter list+.
public class Test;
public static void main)3tring arg9:+;
" aHnew ")+G
a.display)+G
/ bHnew /)+G
b.display)L5elloL+G
=
=
class ";
void display)+;
3ystem.out.println)L5aiL+G
=
=
class / e&tends ";
void display)3tring s+;
3ystem.out.println)s+G
=
=
O/t&/t
5ai
5ello
O$ei**en -et.o*"
The process of a subclass redefining a method contained in the superclass )with the same
parameter types+ is called overriding the method.
Overridden methods allow #ava to support run time polymorphism. 4henever a method
is called for a subclass object* the compiler calls the overriding version instead of the superclass
version. The version of the method defined by the superclass will be hidden.
Page 2% of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
$all to an overridden method is resolved at run time* rather than compile time. 3uperclass
reference variable can refer to a subclass object. #ava uses this fact to resolve calls to overridden
methods at run time. 4hen an overridden method is called through a superclass reference* #ava
determines which version of that method to e&ecute based upon the type of the object being
referred to at the time the call occurs. This determination is made at run time.
class Dispatch ;
public static void main)3tring args9:+ ;
" a H new ")+G )) ob*ect of ty+e A
/ b H new /)+G )) ob*ect of ty+e ,
$ c H new $)+G )) ob*ect of ty+e C
" rG )) obtain a reference of ty+e A
r H aG )) r refers to an A ob*ect
r.callme)+G )) calls A-s .ersion of callme
r H bG )) r refers to a , ob*ect
r.callme)+G )) calls ,-s .ersion of callme
r H cG )) r refers to a C ob*ect
r.callme)+G )) calls C-s .ersion of callme
=
=
4hen you override a method* the subclass method must be at least as visible as the
superclass method.
In particular* if the superclass method is public* then the subclass method must also be
declared as public. It is a common error to accidentally omit the public specifier for the subclass
method. Then the compiler complains that you try to supply a weaker access privilege.
public class Test7;
public static void main)3tring arg9:+;
" aHnew ")+G
a.display)+G
/ bHnew /)+G
b.display)+G
=
=
class ";
protected void display)+;
3ystem.out.println)L5aiL+G
=
=
class / e&tends ";
public void display)+;
3ystem.out.println)L5elloL+G
=
=
Page 2& of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
O/t&/ t
5ai
5ello
?ethods labeled fin,lE &i$,teE o "t,ti! are not subject to dynamic lookup because they
may not be overridden. private methods are simply not inherited because they would never be
callable anyway. static methods apply to a particular class6s static data and thus make no sense in
a derivation. final methods are those designated as not'overridable for reasons of comple&ity or
safety.
public class Test7;
public static void main)3tring arg9:+;
" a7Hnew ")+G
a7.display)+G
" a8Hnew /)+G
a8.display)+G
=
=
class ";
void display)+;
3ystem.out.println)L5aiL+G
=
=
class / e&tends ";
void display)+;
3ystem.out.println)L5elloL+G
=
=
O/t&/ t
5ai
5ello
DDNAMIC 'INDING
3electing the appropriate method at runtime is called dynamic binding. Dynamic /inding
refers to the case where compiler is not able to resolve the call and the binding is done at runtime
only.
"ll the instance methods in #ava follow dynamic binding.
Dynamic binding has a very important property%
It makes programs e&tensible without recompiling the e&isting code.
3uppose a new class is added* and there is the possibility that the variable refers to an
object of that class. The code contains the method invoking statement of that class need not be
recompiled. The method is called automatically if the object happens to refer to the class.
Page 2" of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
D0n,-i! 'in*in+ o 4,te 'in*in+
It is important to understand what happens when a method call is applied to an object. 5ere
are the details%
7. The compiler looks at the declared type of the object and the method name. The compiler
knows all possible candidates for the method to be called.
8. 1e&t* the compiler determines the types of the parameters that are supplied in the method
call. If among all the methods called fun there is a uni-ue method whose parameter types
are a best match for the supplied parameters* then that method is chosen to be called. This
process is called o$elo,*in+ e"ol/tion.
C. If the method is private* static* final* or a constructor* then the compiler knows e&actly
which method to call.
I. 4hen the program runs and uses dynamic binding to call a method* then the virtual
machine must call the version of the method that is appropriate for the actual type of the
object. The virtual machine precomputes a method table for each class that lists all
method signatures and the actual methods to be called. 4hen a method is actually called*
the virtual machine simply makes a table lookup. This is used to reduce the time
consumed by searching process.
STATIC 'INDING OR EAR4D 'INDING
If the compiler can resolve the binding at the compile time only then such a binding is
called 3tatic /inding or .arly /inding. Sesolve the call and binding at compile time.
If the method is private* static* final* or a constructor* then the compiler knows e&actly
which method to call. This is called static binding/
"ll the member variables in #ava follow static binding.
"ll the static method calls are resolved at compile time itself.
"ll private methods are resolved at compile time itself.
5INA4 <EDCORD
The keyword fin,l has three uses.
sed to create the e-uivalent of a named constant.
sed to Prevent Overriding
sed to Prevent Inheritance
N,-e* !on"t,nt
" variable can be declared as fin,l. Doing so prevents its contents from being modified.
This means that you must initiali(e a fin,l variable when it is declared. ,or e&ample%
final int constant H 7G
>ariables declared as fin,l do not occupy memory on a per'instance basis. Thus* a fin,l variable
is essentially a constant. The keyword fin,l can also be applied to methods* but its meaning is
substantially different than when it is applied to variables. "ttempts to change it will generate
either a compile'time error or an e&ception.
Page 2' of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
U"in+ fin,l to Pe$ent O$ei*in+
?ethods declared as fin,l cannot be overridden.The synta& is simple* just put the
keyword final after the access specifier and before the return type like this%
class "
;
final void meth)+ ;
3ystem.out.println)LThis is a final method.L+G
=
=
class / e&tends "
;
void meth)+ ; AA .SSOS^ $an2t override.
3ystem.out.println)LIllegal^L+G
=
=
1ormally* #ava resolves calls to methods dynamically* at run time. This is called late
binding. 5owever* since fin,l methods cannot be overridden* a call to one can be resolved at
compile time. This is called early binding.
U"in+ fin,l to Pe$ent In.eit,n!e
Declaring a class as fin,l implicitly declares all of its methods as fin,l. 3o it prevents a
class from being inherited. To do this* precede the class declaration with fin,l.
It is illegal to declare a class as both ,("t,!t and fin,l since an abstract class is
incomplete by itself and relies upon its subclasses to provide complete implementations.
5ere is an e&ample of a fin,l class%
final class "
;
AA ...
=
AA The following class is illegal.
class / e&tends "
; AA .SSOS^ $an2t subclass "
AA ...
=
A'STRACT C4ASSES
"n abstract class is a type of class that is not allowed to be instantiated. The only reason
it e&ists is to be e&tended. "bstract classes contain methods and variables common to all the
subclasses* but the abstract class itself is of a type that will not be used directly. .ven a single
abstract method re-uires that a class be marked abstract.
Page #( of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
To declare a class abstract* you simply use the ,("t,!t keyword in front of the !l,""
keyword at the beginning of the class declaration.
,("t,!t class classname
;
public ,("t,!t type methodname)+G
AA no implementation re-uired
<<..
=
There can be no objects of an abstract class. That is* an abstract class cannot be directly
instantiated with the ne% operator. 3uch objects would be useless* because an abstract class is
not fully defined.
"lso* you cannot declare abstract constructors* or abstract static methods. "ny subclass
of an abstract class must either implement all of the abstract methods in the superclass* or be
itself declared ,("t,!t.
5ere is a simple e&ample of a class with an abstract method* followed by a class which
implements that method%
AA " 3imple demonstration of abstract.
abstract class "
;
abstract void callme)+GAA concrete methods are still allowed in abstract classes
void callmetoo)+ ;
3ystem.out.println)LThis is a concrete method.L+G
=
=
class / e&tends "
;
void callme)+ ;
3ystem.out.println)L/2s implementation of callme.L+G
=
=
class "bstractDemo
;
public static void main)3tring args9:+ ;
/ b H new /)+G
b.callme)+G
b.callmetoo)+G
=
=
That is* sometimes you will want to create a superclass that only defines a generali(ed
form that will be shared by all of its subclasses* leaving it to each subclass to fill in the details.
3uch a class determines the nature of the methods that the subclasses must implement. Rou can
re-uire that certain methods be overridden by subclasses by specifying the ,("t,!t type
Page # of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
modifier. These methods are sometimes referred to as subclasser responsibility because they
have no implementation specified in the superclass.
Thus* a subclass must override themUit cannot simply use the version defined in the
superclass.
A("t,!t -et.o*"
"n abstract method is a method declaration that contains no functional code. The reason for
using an abstract method is to ensure that subclasses of this class will include an implementation
of this method. "ny concrete class )that is* a class that is not abstract* and therefore capable of
being instantiated+ must implement all abstract methods it has inherited.
?ethods declared with the keyword abstract define a skeleton for a method but do not
implement it. This re-uires a derived class to provide the code for this class.
" class with one or more abstract methods must itself be declared abstract and cannot be
instantiated. It can only be used for derivation.
To declare an abstract method* use this general form%
abstract type name)parameter'list+G
"P.
/ut while an abstract class can define both abstract and nonabstract methods* an interface can
have only abstract methods. Interface as being similar to an abstract class with no instance fields.
Intef,!e"
"n interface is a collection of method definitions )without implementations+ and constant values.
Definin+ ,n Intef,!e
This is the general form of an interface%
"n interface must be declared with the keyword interface.
access interface name ;
return'type method'name)parameter'list+G
type final'varname H valueG
=
It is also possible to declare that an interface is protected so that it can only be
implemented by classes in a particular package. 5owever this is very unusual.
Sules for interface constants. They must always be
public
static
final
Once the value has been assigned* the value can never be modified. The assignment happens in
the interface itself )where the constant is declared+* so the implementing class can access it and
use it* but as a read'only value.
To make a class implement an interface* have to carry out two steps%
Page #2 of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Declare that your class intends to implement the given interface.
3upply definitions for all methods in the interface.
To declare that a class implements an interface* use the implements keyword%
access class classname implements interfacename
;
AAdefinitions for all methods in the interface
=
Implementation classes must adhere to the same rules for method implementation as a class
e&tending an abstract class. In order to be a legal implementation class* a nonabstract
implementation class must do the following%
4hen you implement an interface method* method must be declared as public. )The
access level can be more accessible than that of the overridden method.+
Type signature of the implementing method must match e&actly the type signature
specified in the interface definition. )The argument list and return type must e&actly
match that of the overridden method.+
" class can implement one or more interfaces.
Partial Implementations% If a class includes an interface but does not fully implement the
methods defined by that interface* then that class must be declared as abstract.
Inne C l," " e"
"n inner class is a class that is defined inside another class.
Inner classes let you make one class a member of another class. #ust as classes have
member variables and methods* a class can also have member classes.
Re+/ l, Inne C l,""
Rou define an inner class within the curly braces of the outer class* as follows%
class ?yOuter ;
class ?yInner ; =
=
"nd if you compile it* F),$,! M0O/te#),$, * you6ll end up with two class files%
?yOuter.class
?yOuter_?yInner.class
The inner class is still* in the end* a separate class* so a class file is generated. /ut the
inner class file isn6t accessible to you in the usual way. The only way you can access the inner
class is through a live instance of the outer class.
Page ## of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
In"t,nti,tin+ ,n Inne Cl,""
To instantiate an instance of an inner class* you must have an instance of the outer class.
"n inner class instance can never stand alone without a direct relationship with a specific
instance of the outer class.
In"t,nti,tin+ ,n Inne Cl,"" fo- Cit.in Co*e in t.e O/te Cl,""
,rom inside the outer class instance code* use the inner class name in the normal way%
class ?yOuter ;
private int & H JG
?yInner mi H new ?yInner)+G
class ?yInner ;
public void seeOuter)+ ;
3ystem.out.println)LOuter & is L F &+G
=
=
public static void main)3tring arg9:+;
?yOuter moHnew ?yOuter)+G
mo.mi.seeOuter)+G
=
=
Output%
Outer & is J
Met.o*>4o!,l Inne C l,""e"
" method'local inner class is defined within a method of the enclosing class.
class ?yOuter ;
void inner)+
;
final int cHOG
class ?yInner ;
int &HMG
public void display)+ ;
3ystem.out.println)LInner & is L F &+G
3ystem.out.println)LInner c is L F c+G
=
=
?yInner mi H new ?yInner)+G
mi.display)+G
=
public static void main)3tring arg9:+;
?yOuter mo H new ?yOuter)+G
mo.inner)+G
=
=
Page #$ of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Output% & is M
c is O
Anon0-o/" Inne C l,""e"
"nonymous inner classes have no name* and their type must be either a subclass of the
named type or an implementer of the named interface.
"n anonymous inner class is always created as part of a statement* so the synta& will end
the class definition with a curly brace* followed by a closing parenthesis to end the
method call* followed by a semicolon to end the statement% =+G
"n anonymous inner class can e&tend one subclass* or implement one interface. It cannot
both e&tend a class and implement an interface* nor can it implement more than one
interface.
public class Test;
public static void main)3tring arg9:+;
/ bHnew /)+G
b.ob.display)+G
=
=
class ";
void display)+;
3ystem.out.println)L5aiL+G
=
=
class / ;
" obHnew ")+;
void display)+;
3ystem.out.println)L5elloL+G
=
=G
=
O/t&/t? 5ello
"nd if you compile it* F),$,! Te"t#),$, * you6ll end up with two class files%
".class
/.class
/_7.class
Test.class
St,ti! Ne"te* C l,""e"
3tatic nested classes are inner classes marked with the static modifier.
Technically* a static nested class is not an inner class* but instead is considered a top'
level nested class.
Page #! of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
/ecause the nested class is static* it does not share any special relationship with an
instance of the outer class. In fact* you don6t need an instance of the outer class to
instantiate a static nested class.
Instantiating a static nested class re-uires using both the outer and nested class names as
follows%
/igOuter.1ested n H new /igOuter.1ested)+G
" static nested class cannot access nonstatic members of the outer class* since it does not
have an implicit reference to any outer instance )in other words* the nested class instance
does not get an outer this reference+.
public class Test;
public static void main)3tring arg9:+;
"./ bHnew "./)+G
b.display)+G
==
class " ;
static class / ;
int mHMG
void display)+;
3ystem.out.println)LmHLFm+G
=
=
=
Output% mHM
T . e O () e! t Cl, "" > T.e Co"-i! S/&e!l,""
The Object class sits at the top of the class hierarchy tree in the #ava development
environment. The Object class is the ultimate ancestor
.very class in #ava e&tends Object class.
The Object class defines the basic state and behavior that all objects must have* such as
the ability to compare with another object* to convert to a string* to wait on a condition variable*
to notify other objects that a condition variable has changed* and to return the object2s class.
O()e!t defines the following methods* which means that they are available in every
object.
R e f le ! tion
Seflection is the ability of the software to analy(e itself at runtime.
Seflection is provided by the java.lang.reflect package and elements in class.
This mechanism is helpful to tool builders* not application programmers.
The reflection mechanism is e&tremely used to
Page #% of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
"naly(e the capabilities of classes at run time
Inspect objects at run time
Implement generic array manipulation code
An,l09e t.e !,&,(ilitie" of !l,""e" ,t /n ti- e > .&amine the structure of class.
#ava.lang.$lass
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
class Test;
public int var7G
private int var8G
protected int varCG
int varIG
=
public class ,ieldDemo;
public static void main)3tring args9:+throws .&ception;
$lass cH$lass.for1ame)LTestL+G
,ield f9:Hc.get,ields)+G
,ield fdec9:Hc.getDeclared,ields)+G
3ystem.out.println)Lpublic ,ields%L+G
for)int iHKGiWf.lengthGiFF+
3ystem.out.println)f9i:+G
3ystem.out.println)L"ll ,ields%L+G
for)int iHKGiWfdec.lengthGiFF+
3ystem.out.println)fdec9i:+G
=
=
O/t&/t?
&/(li! 5iel*"?
public int Test.var7
All 5iel*"?
public int Test.var7
private int Test.var8
protected int Test.varC
int Test.varI
M et.o*
Provides information about method
The get?ethods)+ method return an array containing ?ethod objects that give you all the
public methods.
The getDeclared?ethods )+ return all methods of the class or interface. This includes
those inherited from classes or interfaces above it in the inheritance chain.
import java.lang.reflect.BG
class Test;
public void method7)+
;=
protected void method8)+
;=
private void methodC)+
;=
void methodI)+
;=
=
Page #" of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
public class ?ethodDemo;
public static void main)3tring args9:+throws .&ception;
$lass cH$lass.for1ame)LTestL+G
?ethod m9:Hc.get?ethods)+G
?ethod mdec9:Hc.getDeclared?ethods)+G
3ystem.out.println)Lpublic ?ethods of class Test ] its 3uper class%L+G
for)int iHKGiWm.lengthGiFF+
3ystem.out.println)m9i:.get1ame)++G
3ystem.out.println)L"ll ?ethods%L+G
for)int iHKGiWmdec.lengthGiFF+
3ystem.out.println)mdec9i:.get1ame)++G
=
=
O/t&/t?
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Con"t /!to
Provide information about constructors
get$onstructors )+ method return an array containing $onstructor objects that give you all
the public constructors
getDeclared$onstructors )+ method return all constructors of the class represented by the
$lass object.
U"in+ Ref le!tion to An, l0 9 e O()e!t" ,t R/ n T i- e
0ook at the contents of the data fields. It is easy to look at the contents of a specific field
of an object whose name and type are known when you write a program. /ut reflection lets you
look at fields of objects that were not known at compile time.
f/set0ob*1 .alue) sets the field represented by f of the object obj to the new value.
f/!et0ob*) returns an object whose value is the current value of the field of obj.
import java.lang.reflect.BG
class ";
public int var7*var8G
")int i* int j+;
var7HiG
var8HjG
=
=
public class $onstructorDemo ;
public static void main)3tring args9:+ throws .&ception;
" objHnew ")7K*8K+G
3ystem.out.println)L/efore `n var7H LFobj.var7+G
,ield f7 H obj.get$lass)+.get,ield)Lvar7L+G
int v7 H f7.getInt)obj+ F 7G
f7.setInt)obj* v7+G
3ystem.out.println)L"fter `n var7H LFv7+G
3ystem.out.println)L/efore `n var8H LFobj.var8+G
,ield f8 H obj.get$lass)+.get,ield)Lvar8L+G
f8.set)obj*87+G
3ystem.out.println)L"fter `n var8H LFf8.get)obj++G
=
=
O/t&/t?
/efore var7H 7K
"fter
var7H 77
/efore var8H 8K
"fter
Page $( of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
var8H 87
U"in+ Refle!tion to i-&le-ent +enei! ,,0 -,ni&/l,tion !o*e
The "rray class in the java.lang.reflect package allows you to create arrays dynamically.
,irst the given array can be converted to an Object9: array. newInstance)+ method of "rray class*
constructs a new array.
Ob*ect newarray2 Array/new3nstance0Com+onent4y+e1 newlength)
ne%In"t,n!e6) method needs two parameters
Co-&onent T0&e of new array
To get component type
7. Pet the class object using get$lass)+ method.
8. $onfirm that it is really an array using is"rray)+.
C. se get$omponentType method of class $lass* to find the right type for the array.
4en+t. of new array
0ength is obtained by get0ength)+ method. It returns the length of any array)method is
static method* "rray.get0engh)array name++.
import java.lang.reflect.BG
public class Test"rraySef ;
static Object arrayProw)Object a+;
$lass cl H a.get$lass)+G
if )^cl.is"rray)++ return nullG
$lass componentType H cl.get$omponentType)+G
int length H "rray.get0ength)a+G
int new0ength H length F 7KG
Object new"rray H "rray.newInstance)componentType*new0ength+G
3ystem.arraycopy)a* K* new"rray* K* length+G
return new"rrayG
=
public static void main)3tring args9:+ throws .&ception;
int arr9:Hnew int97K:G
3ystem.out.println)arr.length+G
arr H )int9:+arrayProw)arr+G
3ystem.out.println)arr.length+G
=
=
Output%
7K
8K
O()e!t ! lonin +
Page $ of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
" clone of an object is a new object that has the same state as the original but a different
identity. Rou can modify the clone without affecting the original.
4hen you make a copy of a variable* the original and the copy are references to the same object.
This means a change to either variable also affects the other.
If you want to make a clone of any class then the class must
implement the $loneable interface* and
Sedefine the clone method with the public access modifier.
import java.util.BG
class Test implements $loneable;
int aH7KG
public void display)+;
3ystem.out.println)LaHLFa+G
=
public Object clone)+;
try;
Test cloned H )Test+super.clone)+G
return clonedG
=
catch)$lone1ot3upported.&ception e+;
return nullG
=
=
=
public class $loneDemo;
public static void main)3tring arg9:+;
Test originalHnew Test)+G
original.aH8KG
Test copyH)Test+original.clone)+G
copy.aHQKG
original.display)+G
copy.display)+G
=
=
Output%
aH8K
aHQK
P o 3 0
Pro&y used to create new classes at runtime that implement a given set of interfaces. The
pro&y class can create brand'new classes at runtime.
Page $2 of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
The pro&y class can create brand'new classes at runtime. 3uch a pro&y class implements
the interfaces that you specify. In particular* the pro&y class has the following methods%
Z "ll methods re-uired by the specified interfacesG
Z "ll methods defined in the Object class )to3tring* e-uals* and so on+.
To create a pro&y object* you use the newPro&yInstance method of the Pro&y class. The method has
three parameters%
7. " class loader/ "s part of the #ava security model* it is possible to use different
class loaders for system classes* classes that are downloaded from the Internet*
and so on.
8. "n array of $lass objects* one for each interface to be implemented.
C. "n invocation handler.
Pro&ies can be used for many purposes* such as%
Z Souting method calls to remote serversG
Z "ssociating user interface events with actions in a running programG
Z Tracing method calls for debugging purposes.
Page $# of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Unit III E$ent>D i$en P o+ ,--in+
G ,&.i!" & o+ ,- - in+
5 ,-e
,rame is a top'level window that has a title bar* menu bar* borders* and resi(ing corners. /y
default* a frame has a si(e of K a K pi&els and it is not visible.
,rames are e&amples of containers. It can contain other user interface components such as
buttons and te&t fields.
Class hierarch for Frame
#ava.awt
$omponent
$ontainer
4indow
,rame
Co-&onent G Cin*o% !l,"" Met.o*"
*a.a/awt/Com+onent
.oid set.isible0boolean b) 5 shows or hides the component depending on whether b is
true or false.
.oid setSize0int width1 int height) 5 resi(es the component to the specified width and
height.
.oid set/ounds0int 61 int y1 int width1 int height) 5 moves and resi(es this component. The
location of the top'left corner is given by & and y* and the new si(e is given by the width
and height parameters.
.oid set/ac$!round0*a.a/awt/Color) 7 set /ackground color to the window.
.oid setFore!round0*a.a/awt/Color)5 set ,oreground color to the window.
.oid repaint0) 5 causes a repaint of the component Yas soon as possible.
Page $$ of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
*a.a/a w t/8indow
.oid set0itle09tring s) ' sets the te&t in the title bar for the frame to the string s.
5,-e6s constructors%
Frame0 ) ' creates a standard window that does not contain a title.
Frame09tring title) ' creates a window with the title specified by title
Met.o*" of 5,-e !l,""?
.oid setSize0int new8idth1 int new:eight) ' method is used to set the dimensions of the
window. The dimensions are specified in terms of pi&els.
.oid set.isible0boolean .isible;lag)5 The component is visible if the argument to this
method is t/e. Otherwise* it is hidden.
.oid set0itle09tring new4itle)5 change the title in a frame window.
Ce,tin+ , 5,-e Cin*o%
Method 1< 3n main0) method
$reate an instance of a ,rame class.
,rame fHnew ,rame)Yframe name+G
3et the frame si(e
f.set3i(e)MKK*MKK+G
?ake the frame visible
f.set>isible)true+G
.&ample%
The following java program creates a frame with the dimension as NKK & IKK and makes it
visible in the screen. Import java.awt package because ,rame class is available in that package.
import java.awt.BG
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Method 1"
$reate a subclass of 5,-e.
In the 3ubclass constructor
$hange the frame title by calling superclass 9,rame: constructor using super2Strin!)
method call.
3et the si(e of the window e&plicitly by calling the setSize2 ) method.
?ake the frame visible by calling set.isible2) method.
In main)+ method
$reate an instance of subclass.
.&ample%
The following java program creates a frame with the dimension as NKK & IKK and makes it
visible in the screen. Import java.awt package because ,rame class is available in that package.
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
right* and positive y values are down. $oordinate units are measured in pi&els )picture element+.
"ll pi&el values are integersG there are no partial or fractional pi&els.
D coordinate% 5ori(ontal distance moving right from the left of the screen.
R coordinate% >ertical distance moving from top to bottom of the screen.
The Praphics class provides a set of simple built'in graphics primitives for drawing* including
lines* rectangles* polygons* ovals* and arcs.
4 in e "
To draw straight lines* use the draw0ine method. draw0ine takes four arguments% the & and y
coordinates of the starting point and the & and y coordinates of the ending point.
.oid dra34ine0int start=1 int start>1 int end=1 int end>) 5 displays a line in the current
drawing color that begins at startD*startR and ends at endD*endR.
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Re!t,n+ le"
The #ava graphics primitives provide two kinds of rectangles% Plain rectangles and Sounded
rectangles)which are rectangles with rounded corners+.
.oid dra3*ect0int 61 int y1 int width1 int height)
.oid fill*ect0int 61 int y1 int width1 int height)
.oid dra3*ound*ect0int 61 int y1 int width1 int height1 int 6Diam1 int yDiam)
.oid fill*ound*ect0int 61 int y1 int width1 int height1 int 6Diam1 int yDiam)
" rounded rectangle has rounded corners. The upper'left corner of the rectangle is at 61 y/ The
dimensions of the rectangle are specified by width and height/ The diameter of the rounding arc
along the D a&is is specified by 6Diam/ The diameter of the rounding arc along the R a&is is
specified by yDiam/
E3,-&le? De-o#),$,
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
P o l0+on"
Polygons are shapes with an unlimited number of sides. 3et of & and y coordinates are needed to
draw a polygon* and the drawing method starts at one* draws a line to the second* then a line to
the third* and so on.
.oid dra3#ol!on0int 6? @1 int y? @1 int numPoints)
.oid fill#ol!on0int 6? @1 int y? @1 int numPoints)
&9:' "n array of integers representing & coordinates
y9:' "n array of integers representing y coordinates
numPoints' "n integer for the total number of points
E3,-&le? De-o#),$,
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
O$, l"
se ovals to draw ellipses or circles.
.oid dra3)'al0int to+1 int left1 int width1 int height)
.oid fill)'al0int to+1 int left1 int width1 int height)
Page !( of !"
!
www.csetube.in
Demo obHnew Demo)LOval DemoL+G
A !
The arc is drawn from startAngle through the angular distance specified by arAAngle/ "ngles are
specified in degrees. The arc is drawn counterclockwise if swee+Angle is positive* and clockwise
if arAAngle is negative.
void *,%A!)int 6* int y* int width* int height* int startAngle* int arcAngle+
void fillA!)int 6* int y* int width* int height* int startAngle* int arcAngle+
&HK
yHK
widthH7KK
heightH7KK
3tartangleHOK
arc"ngleH7QK
Page ! of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Page !2 of !"
!
www.csetube.in
E3,-&le?De-o#),$,
import java.awt.BG
public class Demo e&tends ,rame;
Demo)3tring s+;
super)s+G
set3i(e)CKK*CKK+G
set>isible)true+G
=
public void paint)Praphics g+ ;
g.draw"rc)8K*78K*OK*OK*OK*7QK+G
g.fill"rc)78K*78K*OK*OK*OK*7QK+G
g.draw"rc)7JK*78K*OK*OK*OK*'7QK+G
=
public static void main)3tring arg9:+;
Demo obHnew Demo)L"rc DemoL+G
D ,%in+ Te 3 t
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Page !$ of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
U " in+ ! o l o E f ont "E , n* i- ,+ e "
Colo? java.awt.$olor
$olor class creates a solid SP/ color with the specified red* green* blue value in the range )K'
8MM+. #ava6s abstract color model uses 8I'bit color. The values of each color must be in the range
)K' 8MM+.
$onstructor%
Color0int red1 int green1 int blue) ' create new color object for any combination of red* green*
and blue.
#ava.awt.$olor class used to create new color object for any combination of red* green* and blue*
and it predefines a few color constants. They are stored in class variables*
public static void main)3tring arg9:+;
5on t ? java.awt.,ont
,ont class is used to create ,ont Objects to set the font for drawing te&t* labels* te&t,ield* buttons
etc..*
One 5ont constructor has this general form%
Font29tring fontBame1 int font9tyle1 int +oint9ize)
5ere* fontBame specifies the name of the desired font. The style of the font is specified by
font9tyle/ It may consist of one or more of thesethree constants% 5ont#P4AIN* 5ont#'O4D* and
5ont#ITA4IC. The si(e* in points* of the font is specified by +oint9ize/ point si(e may or may
not be the height of the characters.
To draw characters in a font* first create an object of the class ,ont. then specify the font name*
the font style* and the point si(e.
Page !% of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Met.o*"
Ca.a/a w t/Gra+hics
.oid setFont0;ont fontOb*)5 selects a font for the graphics conte&t. That font will be used
for subse-uent te&t drawing operations.
;ont !etFont0 )' get the current font by calling get,ont) +.
Ca.a/a w t/Com+onent
.oid setFont0;ont fontOb*)
E3,-&le? The following program that draws several lines of te&t in different fonts.
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
#ava provides the functions for reading images that are stored in local files and display them on
graphics object.
Step11 4oadin! an ima!e
*a.a/a w t/4oolAit
4oolAit !et(efault0ool$it0)5 returns the default toolkit.
3mage !et,ma!e09tring filename) 5 returns an image that will read its pi&el data from a
file.
Toolkit object can only read PI, and #P.P files.
Step"1 displain! an ima!e
*a.a/a w t/Gra+hics
boolean dra3,ma!e03mage img1 int 61 int y1 3mageObser.er obser.er)' draws a scaled image.
boolean dra3,ma!e03mage img1 int 61 int y1 int width1 int height1 3mageObser.er obser.er) '
draws a scaled image. The system scales the image to fit into a region with the given width
and height. 1ote% This call may return before the image is drawn.
.&ample% the following program draws a tiled graphics image from the top'left corner to bottom
right corner of the window.
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
AC T Co- & on e nt"
"ll components are subclass of $omponent class
$omponents allow the user to interact with application. " layout manager
arranges components within a container ),rameA"ppletAPanel+.
Addin! and *emo'in! Controls
add0Com+onent com+Ob*)5 add components to the conatainer. Once it is added* it will
automatically be visible whenever its parent window is displayed. 5ere* compObj is an
instance of the control that you want to add.
.oid remo'e0Com+onent ob*)5 remove a control from a window
remo'eAll2 )5 remo.e all controls from a window
0abels are components that hold te&t.
0abels don6t react to user input. It is used to identify components.
Con"t/!to"
4abel09tring str+ ' constructs a label with left'aligned te&t.
4abel09tring str1 int how+ ' constructs a label with the alignment specified by how.
Met.o*"
.oid set0e5t09tring str)5 set the te&t in the label
9tring !et0e5t0 )5 return the te&t of label
65ample1 The following e&ample creates three labels and adds them to a frame..The labels are
organi(ed in the frame by the flow layout manager.
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Page % of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
'/ tto n
" push button is a component that contains a label and that generates an event when it is pressed.
Push buttons are objects of type /utton.
Con"t/!to"
/utton0 )5 creates an empty button
/utton09tring str)5 creates a button that contains str as a label.
Met.o*"
.oid set4abel09tring str) 'set the label in the button
9tring !et4abel0 ) 'return the label of button
E3,-&le? The following e&ample creates three buttons and adds them to a frame. The buttons
are organi(ed in the frame by the flow layout manager.
public static void main)3tring arg9:+;
E3,-&le? The following e&ample creates a list and adds it to a frame.
import java.awt.BG
public class Demo e&tends ,rame;
,low0ayout flowH new ,low0ayout)+G
0ist l7Hnew 0ist)8+G
0ist l8Hnew 0ist)C+G
0ist lCHnew 0ist)I*true+G
0abel lb7 H new 0abel)LDeptL+G
0abel lb8 H new 0abel)LDeptL+G
0abel lbC H new 0abel)LDeptL+G
Demo)3tring s+;
super)s+G
set3i(e)8KK*CKK+G
set0ayout)flow+G
l7.add)L$3.L+Gl7.add)L.$.L+Gl7.add)L...L+Gl7.add)L?.$5L+G
l8.add)L$3.L+Gl8.add)L.$.L+Gl8.add)L...L+Gl8.add)L?.$5L+G
lC.add)L$3.L+GlC.add)L.$.L+GlC.add)L...L+GlC.add)L?.$5L+G
add)lb7+Gadd)l7+Gadd)lb8+Gadd)l8+Gadd)lbC+Gadd)lC+G
set>isible)true+G
=
public static void main)3tring arg9:+;
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
C.e ! @ 'o3
" check bo& is a control that is used to turn an option on or off. It consists of a small bo& that can
either contain a check mark or not. There is a label associated with each check bo& that describes
what option the bo& represents.
Con"t/!to"
Chec$bo50 )5 check bo& whose label is initially blank
Chec$bo509tring str)5 check bo& whose label is specified by str.
Chec$bo509tring str1 boolean on) 5 allows you to set the initial state of the check bo&. If
on is t/e* the check bo& is initially checked
Chec$bo509tring str1 boolean on1 ChecAbo6Grou+ cbGrou+)5 group is specified by
cbProup
Chec$bo509tring str1 ChecAbo6Grou+ cbGrou+1 boolean on)
Met.o*"
boolean !etState0 )
.oid setState0boolean on)
9tring !et4abel0 )
.oid set4abel09tring str)
C.e!@(o3Go/ &
$reate a set of mutually e&clusive check bo&es in which one and only one check bo& in the group
can be checked at any one time. These check bo&es are often called radio buttons. The default
constructor is defined* which creates an empty group.
E3,-&le? The following e&ample creates a checkbo& group )Pender+ and checkbo&es
)0anguages Enown+.
import java.awt.BG 0abel l8Hnew 0abel)L0anguages EnownL+G
public class Demo e&tends ,rame; $heckbo&Proup cgHnew $heckbo&Proup)+G
,low0ayout flowH new ,low0ayout)+G $heckbo& c7Hnew $heckbo&)L?aleL*cg*true+G
0abel l7Hnew 0abel)LPenderL+G $heckbo& c8Hnew $heckbo&)L,emaleL*cg*false+G
Page %$ of !"
!
www.csetube.in
C.oi ! e
The $hoice class is used to create a pop'up list of items from which the user may choose. It
allows the user to select single item at any time. C.oi!e only defines the default constructor*
which creates an empty list.
To add a item to the list* call ,**6 ). It has this general form%
.oid add09tring name)
To determine which item is currently selected* you may call either !etSelected,tem6 ) or
!etSelected,nde56 ).
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Te3t5ie l*
Te&t fields allow the user to enter strings and to edit the te&t using the arrow keys* cut and paste
keys* and mouse selections.
0e5tField0 )5 creates a default te&t field
0e5tField0int numChars)5 creates a te&t field that is num$hars characters wide
0e5tField09tring str)5 initiali(es the te&t field with the string contained in str
0e5tField09tring str1 int numChars)
Met.o*"
9tring !et0e5t2 )
.oid set0e5t09tring str)
Te 3 tAe,
3imple multiline editor allow the user to enter strings.
Te3tAe, ,n* Te3t5iel* are subclass of Te3tCo-&onent. Therefore* it supports the +etTe3t6 )*
"etTe3t6 )* +etSele!te*Te3t6 )* "ele!t6 )* i"E*it,(le6 )* and "etE*it,(le6 ) methods described in
Te&t,ield class.
import java.awt.BG Te&t"rea taHnew Te&t"rea)8*7K+G
public class Demo e&tends ,rame; Demo)3tring s+;
,low0ayout flowH new ,low0ayout)+G super)s+G
0abel lb7Hnew 0abel)L1ameL+G set3i(e)8MK*8KK+G
0abel lb8Hnew 0abel)L1oL+G set0ayout)flow+G
0abel lbCHnew 0abel)L?essageL+G add)lb7+Gadd)t7+G
Te&t,ield t7Hnew Te&t,ield)8K+G add)lb8+Gadd)t8+G
Te&t,ield t8Hnew Te&t,ield)7M+G add)lbC+Gadd)ta+G
Page %% of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
set>isible)true+G
=
public static void main)3tring arg9:+;
Demo obHnew Demo)LTe&t$omponents DemoL+G
=
=
output%
Page %& of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
',"i!" of E$ent A,n*lin+
.vent handling concept is -uite simple% a source generates an event and sends it to one or more
listeners. 0istener simply waits until it receives an event. Once received* the listener processes
the event and then returns.
E$ent"
"n event is an object that describes a state change in a source. 3ome of the activities that cause
events to be generated are pressing a button* entering a character via the keyboard* selecting an
item in a list* and clicking the mouse.
E$ent So/!e"
" source is an object that generates an event. 3ources may generate more than one type of event.
" source must register listeners in order for the listeners to receive notifications about a specific
type of event.
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
7o3 e'ent handlin! in the A80 3or$s
" listener object is an instance of a class that implements a special interface called
)naturally enough+ a listener interface/
"n event source is an object that can register listener objects and send them event objects.
The event source sends out event objects to all registered listeners when that event
occurs.
The listener objects will then use the information in the event object to determine their
reaction to the event.
Rou register the listener object with the source object by using lines of code that follow the
model%
e.ent9ourceOb*ect/,**D.ent4i"tene)e.entEistenerOb*ect+G
ACT E$ent Aie , !.0
java.awt.event
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
A,n* lin+ <e0(o, * E$ent"
To handle keyboard events* class must implement the Eey0istener interface.
Segister key listener to receive notifications about Eey.vents.
addEey0istener)this+G
So/!e% Key,oard
E$ent Cl,""% *a.a/awt/e.ent/KeyD.ent
4i"tene Intef,!e% *a.a/awt/e.ent/KeyEistener
.&ample% The following program demonstrates keyboard input. 4hen program receives
keystrokes* identifies the key and perform the corresponding actions specified by the program.
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
A,n*lin+ M o/"e E$ent"
To handle ?ouse events* class must implement the ?ouse0istener ] ?ouse?otion0iatener
interface. Segister mouse listener ] mouse motion listener to receive notifications about
?ouse.vents.
add?ouse0istener)this+G
add?ouse?otion0istener)this+G
So/!e? Mouse
E$ent Cl,""% *a.a/awt/e.ent/MouseD.ent
4i"tene Intef,!e? *a.a/awt/e.ent/MouseEistener
*a.a/awt/e.ent/MouseMotionEistener
D6am+le< The following program demonstrates ?ouse event handling. 4hen user drag the
mouse it draws a line along the motion path.
import java.awt.BG y8Hme.getR)+G
import java.awt.event.BG Praphics gHthis.getPraphics)+G
public class Demo e&tends ,rame implements g.draw0ine)&7*y7*&8*y8+G
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
public void paint)Praphics g+;=
public static void main)3tring arg9:+;
Demo obHnew Demo)L?ouse event DemoL+G
=
=
Page &2 of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
A ! tion E$ent
To handle "ction events* class must implement the "ction0istener interface. 3ource objects
needs to register action listener to receive events.
3ourceObject.add"ction0istener)this+G
So/!e? ,utton
E$ent Cl,""% *a.a/awt/e.ent/ActionD.ent
4i"tene Intef,!e? *a.a/awt/e.ent/ActionEistener
D6am+le< The following program demonstrates "ction event handling. "pplication window has
C Te&t ,ields and two buttons. Te&t fields are used to get user input and show the result to the
user. 4hen the user presses /utton* it will generate an action event. 0istener receives the event
and performs the operation specified in the actionPerformed ?ethod.
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
I te - E $ e nt
To handle Item events* class must implement the Item0istener interface. 3ource objects needs to
register action listener to receive events.
3ourceObject.add"ction0istener)this+G
So/!e? Eist1 Choice1 ChecAbo6
E$ent Cl,""% *a.a/awt/e.ent/3temD.ent
4i"tene Intef,!e? *a.a/awt/e.ent/3temEistener
D6am+le< The following program demonstrates Item event handling. "pplication window has
Te&t ,ield* $heckbo&* and $hoice. Te&t fields are used to show the result to the user. 4hen the
user select item from any component* then the selected item will be displayed in te&t field. "
listener receives the event and performs the operation specified in the item3tate$hanged)+
?ethod.
import java.awt.BG Te&t,ield tHnew Te&t,ield)8K+G
import java.awt.event.BG Demo)3tring s+;
public class Demo e&tends ,rame implements super)s+G
Item0istener; set0ayout)flow+G
3tring msgHLLG c.add)L$hennaiL+Gc.add)L$oimbatoreL+G
,low0ayout flowHnew ,low0ayout)+G c.add)LEanyaEumariL+Gc.add)L?aduraiL+G
0abel lb7 H new 0abel)L$ityL+G c.add)LTirunelveliL+G
0abel lb8 H new 0abel)L\ualificationL+G add)lb7+Gadd)c+G
0abel lbC H new 0abel)L0anguages EnownL+G add)lb8+Gadd)c7+Gadd)c8+G
$hoice cHnew $hoice)+G add)lbC+Gadd)cC+Gadd)cI+Gadd)cM+Gadd)cN+G
$heckbo&Proup cgHnew $heckbo&Proup)+G add)t+G
$heckbo& c7Hnew $heckbo&)LPL*cg*true+G set3i(e)8KK*CKK+G
$heckbo& c8Hnew $heckbo&)LPPL*cg*false+G set>isible)true+G
$heckbo& cCHnew $heckbo&)L>isual /asicL+G c.addItem0istener)this+G
$heckbo& cIHnew $heckbo&)L$FFL+G c7.addItem0istener)this+G
$heckbo& cMHnew $heckbo&)L#avaL+G c8.addItem0istener)this+G
$heckbo& cNHnew $heckbo&)LdotnetL+G cC.addItem0istener)this+G
Page &$ of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
cI.addItem0istener)this+G
cM.addItem0istener)this+G
cN.addItem0istener)this+G
=
public void item3tate$hanged)Item.vent ie+;
3tring msgH)3tring+ie.getItem)+G
t.setTe&t)msg+G
=
public static void main)3tring arg9:+;
Demo obHnew Demo)L0ist event DemoL+G
=
=
Output%
4 ,0o/t M ,n,+ e - e nt
0ayout manager automatically arranges several components within a window. .ach container
object has a layout manager associated with it.
Panel*"pplet ' ,low 0ayout
,rame ' /order 0ayout
4henever a container is resi(ed* the layout manager is used to position each of the components
within it. Peneral synta& for setting layout to container
Foid setEayout0EayouManager ob*)
0ayout ?anagers are
,low0ayout
/order0ayout
Prid 0ayout
Pridbag0ayout
/o&0ayout
A,n+e !o-&onent %it.o/t /"in+ l,0o/t M,n,+e?
Rou can position components manually using set/ounds)+ method defined by
$omponent class.
7. Disable the default manager of your container.
set0ayout)null+G
8. Pivethe location and si(e of the component which is to be added in the container.
Page &! of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
set/ounds)int &* int y* int width* int height+G
eg%
/utton bHnew /utton)Yclick me+G
b.set/ounds)7K*7K*MK*8K+G
5 lo% 4 ,0o/t
,low0ayout arranges the components in rows from left'to'right and top'to'bottom order based
on the order in which they were added to the container.
,low0ayout arranges components in rows* and the alignment specifies the alignment of the rows.
,or e&ample* if you create a ,low0ayout that6s left aligned* the components in each row will
appear ne&t to the left edge of the container.
The ,low0ayout constructors allow you to specify the hori(ontal and vertical gaps that should
appear between components* and if you use a constructor that doesn6t accept these values* they
both default to M.
Con"t/!to?
Flo34aout2) ' create default layout* which centers component and leaves M pi&els
spaces between each component.
Flo34aout2int ho3)9specify how ech line is aligned.
The flow layout manager lines the components hori(ontally until there is no more room and then
starts a new row of components. 4hen the user resi(es the container* the layout manager
automatically reflows the components to fill the available space. If you reduce the width of the
frame further* then portions of the wider components begin to disappear. 3imilarly* if you reduce
the frame6s vertical si(e so that there6s not enough vertical space to display all rows* some of the
components will become partially or completely inaccessible
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
G i* 4 ,0o/t
The Prid0ayout layout manager divides the available space into a grid of cells* evenly allocating
the space among all the cells in the grid and placing one component in each cell.
$ells are always same si(e. 4hen you resi(e the window* the cells grow and shrink* but all the
cells have identical si(es.
$onstructor
Prid0ayout)int rows* int cols+' construct a grid with specified rows and cols.
Prid0ayout)int rows* int cols* int hspace* int vspace+ ' to specify the amount of hori(ontal
and vertical space that should appear between adjacent components.
4hen you create a Prid0ayout* you can specify a value of K for either the row count or the
column count* but not both. If you set the number of rows to K* Prid0ayout creates as many rows
as it needs to display all the components using the specified number of columns.
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
The five regions correspond to the top* left* bottom* and right sides of the container* along with
one in the center. .ach of the five areas is associated with a constant value defined in
/order0ayout% 1OST5* 3OT5* ."3T* 4.3T* and $.1T.S for the top* bottom* right* left*
and center regions* respectively.
Con"t/!to
/order0ayout)+
/order0ayout)int hspace* int vspace+ @ leave space between components.
/order layout grows all components to fill the available space.Rou can add components by
specifying a constraint ' /order0ayout.$.1T.Sb1OST5b3OT5b."3Tb4.3T
.oid add0Com+onent ob*1 constraint)
import java.awt.BG
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
In Prid bag layout* the rows and columns have variable si(es. It is possible to merge two
adjacent cells and make a space for placing larger components.
To describe the layout to grid bag manager* you must follow the procedure
7. $reate an object of type Prid/ag0ayout. 1o need to specify rows and column.
8. 3et this Prid/ag0ayout object to the container.
C. $reate an object of type Prid/ag$onstraints. This object will specify how the
components are laid out within the grid bag.
I. ,or each components* fill in the Prid/ag$onstraints object.,inally add the component
with the constraint by using the call
add)$omponent* constraint+G
Gi*',+Con"t,int"?
Prid& @ specify the column position of the component to be added
Pridy ' specify the row position of the component to be added
Pridwidth' specify how many columns occupied by the component
Pridheight ' specify how many rows occupied by the component
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
"rrange components in single row or single column. $omponents are arranged either vertically
from top to bottom or hori(ontally from left to right
/o&0ayout)$ontainer Obj* /o&0ayout.DV"DI3 b RV"DI3+G
A*, & t e ! l, " " e "
"n adapter class provides an empty implementation of all methods in an event listener interface.
It is useful when you want to receive and process only some of the events that are handled by an
event listener interface.
Define a new class that e&tends the adapter class and overrides the desired methods only.
.&tends adapter class to create 0istener and override the desired methods. If you implement the
interface* you have to define all of methods in it. This adapter class defines null methods for all
events* so you can only redefine the methods that you needed.
3ome "dapter classes are
Eey"dapter
?ouse"dapter
?ouse?otion"dapter
D6am+le< If the user only interest in mouse pressed event*then simply e&tends ?ouse"dapter
class and redefine the mousePressed event. The following program listening ?ouse.vent
whenever the user press the mouse it will print Ymouse pressed t e&t on command prompt.
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Page " of !"
!
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
M o* e l>2i e % > C ont o l le * e " i+ n &, t t e n
3wing uses the model5.iew5controller architecture )?>$+ as the fundamental design
behind each of its components. .ssentially* ?>$ breaks PI components into three
elements. .ach of these elements plays a crucial role in how the component behaves.
Model 9 )includes state data for each component+
The model encompasses the state data for each component. There are different models for
different types of components. ?odel has no user interface. ?odel data always e&ists
independent of the component2s visual representation.
,or e&ample* model of a $hoice list might contain the information about list of items and
currently selected item. This information remains the same no matter how the component
is painted on the screen.
.ie3 9 )to display component on screen+
The view refers to how you see the component on the screen. It determines e&actly where
and how to draw the choice list by the information offered by the model.
Controller9 )handles user Input+
The controller decides the behavior of each component with respect to the events. .vents
come in many forms )a mouse click* a keyboard event+.The controller decides how each
component will react to the eventUif it reacts at all.
Page "2 of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
M2C Inte ,!tion
In ?>$* each of the three elementsUthe model* the view* and the controllerUre-uires
the services of another element to keep itself continually updated.
Page "# of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Int o*/ ! tion to S % i n+
S3in! Features
Pluggable look'and feels '' as above
0ightweight components
o Do not depend on native peers to render themselves.
o 3implified graphics to paint on screen
o 3imilar behaviour across all platforms
o Portable look and feel
o Only a few top level containers not lightweight.
1ew components '' tress tables* sliders progress bars* frames* te&t components.
Tooltips '' te&tual popup to give additional help
arbitrary keyboard event binding
Debugging support
S % i n+ C o- & on e nt"
),$,3#"%in+
Co-&onent Con"t/!to
#0abel #0abel)+
#0abel)3tring te&t+
#0abel)3tring te&t* int hori(ontal"lignment+
#/utton #/utton) +
#/utton)3tring str+
#0ist #0ist)+
#0ist)3tring9: +
#Sadio/utton #Sadio/utton)+
#Sadio/utton)3tring te&t+
#Sadio/utton)3tring te&t* boolean selected+
#Sadio/utton)3tring te&t* Icon icon* boolean
selected+
#$ombo/o& #$ombo/o&)+
#$ombo/o&)Object items9:+
#$heckbo& #$heckbo&) +
#$heckbo&)3tring str+
#$heckbo&)3tring str* boolean on+
#$heck/o&)3tring te&t* Icon icon+
#Te&t,ield #Te&t,ield)int num$hars+
#Te&t,ield)3tring str* int num$hars+
#Te&t"rea #Te&t"rea)int num0ines* int num$hars+
#Te&t"rea)3tring str* int num0ines* int num$hars+
#Password,ield #Password,ield)3tring te&t* int columns+
T .e 14,(e l C l, " "
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
3wing allows you to create labels that can contain te&t* images* or both. nlike
java.awt.0abel objects* #0abel objects may consist of both te&t and graphics )icons+.
Te 3 t In&/t
In #ava* two components are used to get te&t input%
#Te&t,ield
#Te&t"rea.
The difference between them is that a te&t field can accept only one line of te&t and a te&t
area can accept multiple lines of te&t. The classes are called #Te&t,ield for single'line
input and #Te&t"rea for multiple lines of te&t.
T.e 1P,""%o *5ie l* C l,""
Password fields are a special kind of te&t field. To avoid nosy bystanders being able to
glance at a password* the characters that the user entered are not actually displayed.
Instead* each typed character is represented by an echo character1 typically an asterisk
)B+. The 3wing set supplies a #Password,ield class that implements such a te&t field.
T.e 1'/tton C l,""
They are typically used much like java.awt./uttons. #/uttons fire "ction.vents when
they are clicked.
T.e 1C.e! @ 'o 3 C l,""
It is used to allow the user to turn a given feature on or off* or to make multiple selections
from a set of choices. " #$heck/o& is usually rendered by showing a small bo& into
which a LcheckL is placed when selected. The user could check either* both* or none of
the two check bo&es.
T.e 1R,*io'/tton C l,""
#Sadio/uttons* allowing users to make a single selection from a set of options.
Page "% of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
T.e 14i"t C l,""
" list is a graphical component from which the user can select choices. 0ists typically
display several items at a time* allowing the user to make either a single selection or
multiple selections."4T limited the contents of its 0ist component to strings. The 3wing
#0ist component lifts this restriction. 0ist elements can now be strings* images.
T.e 1Co - (o'o 3 C l,""
" combo bo& component is actually a combination of a 3wing list and a te&t field. nlike
lists* a combo bo& only allows the user one selection at a time* which is usually copied
into an editable component at the top* such as a te&t field. The user can be permitted*
however* to manually enter in a selection as well.
#$ombo/o& is the 3wing version of a combo bo& component. It is very similar to the
"4T Choice component.
T.e 1P,ne l C l,""
#Panel is an e&tension of #$omponent )which* remember* e&tends java.awt.$ontainer+
used for grouping together other components. It gets most of its implementation from its
superclasses.
Typically* using #Panel amounts to instantiating it* setting a layout manager )this can be
set in the constructor and defaults to a ,low0ayout+* and adding components to it using
the add)+ methods inherited from $ontainer.
Page "& of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
nit I>
Peneric Programming%
Penerics are a facility of generic programming that was added to the #ava programming
language.
Peneric programming is a style of computer programming in which algorithms are
written in terms of to5be5s+ecified5later types that are then instantiated when needed for
specific types provided as parameters.
"s per Ca.a Eanguage 9+ecification%
" t ype va r iable is an un-ualified identifier. Type variables are introduced by
generic class declarations* generic interface declarations* generic method
declarations* and by generic constructor declarations.
" class is generic if it declares one or more type variables. These type variables
are known as the type parameters of the class. It defines one or more type
variables that act as parameters. " generic class declaration defines a set of
parameteri(ed types* one for each possible invocation of the type parameter
section. "ll of these parameteri(ed types share the same class at runtime.
"n inte r face is generic if it declares one or more type variables. These type
variables are known as the type parameters of the interface. It defines one or more
type variables that act as parameters. " generic interface declaration defines a set
of types* one for each possible invocation of the type parameter section. "ll
parameteri(ed types share the same interface at runtime.
" method is generic if it declares one or more type variables. These type variables
are known as the formal type parameters of the method. The form of the formal
type parameter list is identical to a type parameter list of a class or interface.
" c o ns t ructor can be declared as generic* independently of whether the class the
constructor is declared in is itself generic. " constructor is generic if it declares
one or more type variables. These type variables are known as the formal type
parameters of the constructor. The form of the formal type parameter list is
identical to a type parameter list of a generic class or interface.
Motivation for Generics:
Overloaded methods are often used to perform similar operations on different types of
data. To motivate generic methods* let6s begin with an e&ample that contains three
overloaded print"rray methods These methods print the string representations of the
elements of an Integer array* a Double array and a $haracter array* respectively. 1ote
that we could have used arrays of primitive types int* double and char in this e&ample.
4e chose to use arrays of typeInteger* Double and $haracter to set up our generic
method e&ample* because only reference types can be used with generic methods and
classes.
Page "" of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
public class Overloaded?ethods
;
AA method print"rray to print Integer array
public static void print"rray) Integer9: input"rray +
;
AA display array elements
for ) Integer element % input"rray +
3ystem.out.printf) Lcs L* element +G
3ystem.out.println)+G
= AA end method print"rray
AA method print"rray to print Double array
public static void print"rray) Double9: input"rray +
;
AA display array elements
for ) Double element % input"rray +
3ystem.out.printf) Lcs L* element +G
3ystem.out.println)+G
= AA end method print"rray
AA method print"rray to print $haracter array
public static void print"rray) $haracter9: input"rray +
;
AA display array elements
for ) $haracter element % input"rray +
3ystem.out.printf) Lcs L* element +G
3ystem.out.println)+G
= AA end method print"rray
public static void main) 3tring args9: +
;
AA create arrays of Integer* Double and $haracter
Integer9: integer"rray H ; 7* 8* C* I* M* N =G
Double9: double"rray H ; 7.7* 8.8* C.C* I.I* M.M* N.N* J.J =G
$haracter9: character"rray H ; 252* 2.2* 202* 202* 2O2 =G
3ystem.out.println) L"rray integer"rray contains%L +G
print"rray) integer"rray +G AA pass an Integer array
3ystem.out.println) L`n"rray double"rray contains%L +G
print"rray) double"rray +G AA pass a Double array
3ystem.out.println) L`n"rray character"rray contains%L +G
print"rray) character"rray +G AA pass a $haracter array
Page "' of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
= AA end main
= AA end class Overloaded?ethods
"rray integer"rray contains%
7 8 C I M N
"rray double"rray contains%
7.7 8.8 C.C I.I M.M N.N J.J
"rray character"rray contains%
5 . 0 0 O
Generic class definitions
5ere is an e&ample of a generic class%
public class Pair<T, S>
{
public Pair(T f, S s)
{
first = f;
second = s;
}
public T getirst()
{
return first;
}
public S getSecond()
{
return second;
}
public String toString()
{
return !(! " first.toString() " !, ! " second.toString() " !)!;
}
pri#ate T first;
pri#ate S second;
}
This generic class can be used in the following way%
Pair<String, String> grade$$% = new Pair<String, String>(!&i'e!, !(!);
Pair<String, )nteger> &ar's$$% = new Pair<String, )nteger>(!&i'e!,
*%%);
S+ste&.out.println(!grade,! " grade$$%.toString());
S+ste&.out.println(!&ar's,! " &ar's$$%.toString());
Type erasure
Penerics are checked at compile'time for type correctness. The generic type information
is then removed via a process called type erasure. ,or e&ample* -ist<)nteger> will be
Page '( of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
converted to the raw type )non'generic type+ -ist* which can contain arbitrary objects.
5owever* due to the compile'time check* the resulting code is guaranteed to be type
correct* as long as the code generated no unchecked compiler warnings.
"s a result* there is no way to tell at runtime which type parameter is used on an object.
,or e&ample* when you e&amine an (rra+-ist at runtime* there is no general way to tell
whether it was an (rra+-ist<)nteger> or an (rra+-ist<loat>. The e&ception to this
is by using Seflec t ion on e&isting list elements. 5owever* if the list is empty or if its
elements are subtypes of the parameteri(ed type* even Seflection will not divulge the
parameteri(ed type.
The following code demonstrates that the $lass objects appear the same.
(rra+-ist<)nteger> li = new (rra+-ist<)nteger>();
(rra+-ist<loat> lf = new (rra+-ist<loat>();
if (li.get.lass() == lf.get.lass()) // e#aluates to true
S+ste&.out.println(!01ual!);
#ava generics differ from $FF templates. #ava generics generate only one compiled
version of a generic class or function regardless of the number of types used.
,urthermore* the #ava compiler does not need to know which parameteri(ed type is used
because the type information is validated at compile'time and erased from the compiled
code. $onse-uently* one cannot instantiate a #ava class of a parameteri(ed type because
instantiation re-uires a call to a constructor* which is not possible when the type is
unknown at both compile'time and runtime.
T instantiate0le&entT+pe(-ist<T> arg)
{
return new T(); //causes a co&pile error
}
/ecause there is only one copy of a generic class* static variables are shared among all
the instances of the class* regardless of their type parameter. "s a result* the type
parameter cannot be used in the declaration of static variables or in static methods. 3tatic
variables and static methods are LoutsideL of the scope of the class2s parameteri(ed types.
Peneric methods%
Peneric ?ethods
Penericity is not limited to classes and interfaces* you can define generic methods. 3tatic
methods* nonstatic methods* and constructors can all be parameteri(ed in almost the same
way as for classes and interfaces* but the synta& is a bit different. Peneric methods are
also invoked in the same way as non'generic methods.
/efore we see an e&ample of a generics method* consider the following segment of code
that prints out all the elements in a collection%
public #oid print.ollection(.ollection c) {
)terator i = c.iterator();
for(int ' = %;'<c.si2e();'"") {
S+ste&.out.println(i.ne3t());
}
Page ' of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
}
sing generics* this can be re'written as follows. 1ote that the .ollection<4> is the
collection of an unknown type.
#oid print.ollection(.ollection<4> c) {
for(5b6ect o,c) {
S+ste&.out.println(o);
}
}
.&ample%
public class 7eneric8et9odTest
{
// generic &et9od print(rra+
public static < 0 > #oid print(rra+( 0:; input(rra+ )
{
// displa+ arra+ ele&ents
for ( 0 ele&ent , input(rra+ )
S+ste&.out.printf( !<s !, ele&ent );
S+ste&.out.println();
} // end &et9od print(rra+
public static #oid &ain( String args:; )
{
// create arra+s of )nteger, =ouble and .9aracter
)nteger:; int(rra+ = { *, >, ?, $, @ };
=ouble:; double(rra+ = { *.*, >.>, ?.?, $.$, @.@, A.A, B.B };
.9aracter:; c9ar(rra+ = { CDC, C0C, C-C, C-C, C5C };
S+ste&.out.println( !(rra+ integer(rra+ contains,! );
print(rra+( integer(rra+ ); // pass an )nteger arra+
S+ste&.out.println( !En(rra+ double(rra+ contains,! );
print(rra+( double(rra+ ); // pass a =ouble arra+
S+ste&.out.println( !En(rra+ c9aracter(rra+ contains,! );
print(rra+( c9aracter(rra+ ); // pass a .9aracter arra+
} // end &ain
} // end class 7eneric8et9odTest
(rra+ integer(rra+ contains,
* > ? $ @ A
(rra+ double(rra+ contains,
*.* >.> ?.? $.$ @.@ A.A B.B
(rra+ c9aracter(rra+ contains,
D 0 - - 5
/ounded Type Parameters%
There may be times when you2ll want to restrict the kinds of types that are allowed to be
passed to a type parameter. ,or e&ample* a method that operates on numbers might only
Page '2 of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
want to accept instances of Fu&ber or its subclasses. This is what bounded ty+e
+arameters are for.
To declare a bounded type parameter* list the type parameter2s name* followed by the
e3tends keyword* followed by its u++er bound* which in this e&ample is Fu&ber. 1ote
that* in this conte&t* e3tends is used in a general sense to mean either Le&tendsL )as in
classes+ or LimplementsL )as in interfaces+.
public class Go3<T> {
pri#ate T t;
public #oid add(T t) {
t9is.t = t;
}
public T get() {
return t;
}
public <H e3tends Fu&ber> #oid inspect(H u){
S+ste&.out.println(!T, ! " t.get.lass().getFa&e());
S+ste&.out.println(!H, ! " u.get.lass().getFa&e());
}
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Occurrence of any kind of exception in java applications may result in an
abrupt termination of the JVM or simply the JVM crashes which leaves the
user unaware of the causes of such anomalous conditions. However Java
provides mechanisms to handle such situations through its superb exception
handling mechanism. he Java programming language uses !xception
classes to handle such erroneous conditions and exceptional events.
.&ception 5ierarchy%
here are three types of !xceptions"
#. $hecked !xceptions % hese are the exceptions which occur during
the compile time of the program. he compiler checks at the compile
time that whether the program contains handlers for checked exceptions
or not. hese exceptions do not extend &untime!xception class and
must be handled to avoid a compile%time error by the programmer.
hese exceptions extend the java.lang..&ception class hese exceptional
conditions should be anticipated and recovered by an application.
'urthermore $hecked exceptions are re(uired to be caught. &emember
that all the exceptions are checked exceptions unless and until those
indicated by !rror) &untime!xception or their subclasses.
'or example if you call the read*ine+, method on a -uffered&eader
object then the .O!xception may occur or if you want to build a program
that could read a file with a specific name then you would be prompted
to input a file name by the application. hen it passes the name to the
constructor for java.io.'ile&eader and opens the file. However if you do
not provide the name of any existing file then the constructor
throwsjava.io.'ile/ot'ound!xception which abrupt the application to
succeed. Hence this exception will be caught by a well%written
application and will also prompt to correct the file name.
Here is the list of checked exceptions.
Page '$ of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
1o3uch,ield.&ception
.nstantiation!xception
.llegal0ccess!xception
$lass/ot'ound!xception
/o1uchMethod!xception
$lone/ot1upported!xception
.nterrupted!xception
2. 3nchecked !xceptions % 3nchecked exceptions are the exceptions
which occur during the runtime of the program. 3nchecked exceptions
are internal to the application and extend
the java.lang.&untime!xception that is inherited
from java.lang..&ceptionclass. hese exceptions cannot be anticipated and
recovered like programming bugs) such as logic errors or improper use
of an 04.. hese type of exceptions are also called&untime
exceptions that are usually caused by data errors) like arithmetic
overflow) divide by 5ero etc.
*ets take the same file name example as described earlier. .n that
example the file name is passed to the constructor for 'ile&eader.
However) the constructor will throw/ull4ointer!xception if a logic error
causes a null to be passed to the constructor. 6ell in this case the
exception could be caught by the application but it would rather try to
eliminate the bug due to which the exception has occurred. 7ou must
have encountered the most common exception in your program i.e.
the 0rithmetic!xception. . am sure you must be familiar with the reason
of its occurrence that is when something tries to divide by 5ero. 1imilarly
when an instance data member or method of a reference variable is to
be accessed that hasn8t yet referenced an object
throws /ull4ointer!xception.
Here is the list of unchecked exceptions.
Inde&OutOf/ounds.&ception
0rray.ndexOutOf-ounds!xception
$lass$ast!xception
0rithmetic!xception
/ull4ointer!xception
.llegal1tate!xception
1ecurity!xception
Page '! of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
9. !rror % he errors in java are external to the application. hese are the
exceptional conditions that could not be usually anticipated by the
application and also could not be recovered from. !rror exceptions
belong to !rror and its subclasses are not subject to the catch or
1pecify re(uirement. 1uppose a file is successfully opened by an
application for input but due to some system malfunction could not be
able to read that file then the java.io..O!rror would be thrown. his error
will cause the program to terminate but if an application wants then the
error might be caught. 0n !rror indicates serious problems that a
reasonable application should not try to catch. Most such errors are
abnormal conditions.
Hence we conclude that !rrors and runtime exceptions are together
called as unchecked exceptions.
Throwing .&ceptions
.f a method needs to be able to throw an exception) it has to
declare the exception+s, thrown in the method signature) and
then include a throw%statement in the method. Here is an
example"
public void divide)int numberToDivide* int numberToDivide/y+
throws /ad1umber.&ception;
if)numberToDivide/y HH K+;
throw new /ad1umber.&ception)L$annot divide by KL+G
=
return numberToDivide A numberToDivide/yG
=
6hen an exception is thrown the method stops execution right
after the :throw: statement. 0ny statements following the :throw:
statement are not executed. .n the example above the :return
numbero;ivide < numbero;ivide-y=: statement is not
executed if a -ad/umber!xception is thrown. he program
resumes execution when the exception is caught somewhere by
a :catch: block. $atching exceptions is explained later.
7ou can throw any type of exception from your code) as long as
your method signature declares it. 7ou can also make up your
own exceptions. !xceptions are regular Java classes that
Page '% of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
extends java.lang.!xception) or any of the other built%in
exception classes. .f a method declares that it throws an
exception 0) then it is also legal to throw subclasses of 0.
$atching .&ceptions
.f a method calls another method that throws checked
exceptions) the calling method is forced to either pass the
exception on) or catch it. $atching the exception is done using a
try%catch block. Here is an example"
public void callDivide)+;
try ;
int result H divide)8*7+G
3ystem.out.println)result+G
= catch )/ad1umber.&ception e+ ;
AAdo something clever with the e&ception
3ystem.out.println)e.get?essage)++G
=
3ystem.out.println)LDivision attempt doneL+G
=
he -ad/umber!xception parameter e inside the catch%clause
points to the exception thrown from the divide method) if an
exception is thrown.
.f no exeception is thrown by any of the methods called or
statements executed inside the try%block) the catch%block is
simply ignored. .t will not be executed.
.f an exception is thrown inside the try%block) for instance from
the divide method) the program flow of the calling method)
call;ivide) is interrupted just like the program flow inside divide.
he program flow resumes at a catch%block in the call stack that
can catch the thrown exception. .n the example above the
:1ystem.out.println+result,=: statement will not get executed if an
exception is thrown fromt the divide method. .nstead program
execution will resume inside the :catch +-ad/umber!xception
e, > ?: block.
.f an exception is thrown inside the catch%block and that
exception is not caught) the catch%block is interrupted just like
the try%block would have been.
Page '& of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
6hen the catch block is finished the program continues with any
statements following the catch block. .n the example above the
:1ystem.out.println+:;ivision attempt done:,=: statement will
always get executed.
Propagating .&ceptions
7ou don8t have to catch exceptions thrown from other methods.
.f you cannot do anything about the exception where the method
throwing it is called) you can just let the method propagate the
exception up the call stack to the method that called this
method. .f you do so the method calling the method that throws
the exception must also declare to throw the exception. Here is
how the call;ivide+, method would look in that case.
public void callDivide)+ throws /ad1umber.&ception;
int result H divide)8*7+G
3ystem.out.println)result+G
=
/otice how the try%catch block is gone) and the call;ivide
method now declares that it can throw a -ad/umber!xception.
he program execution is still interrupted if an exception is
thrown from the divide method. hus the
:1ystem.out.println+result,=: method will not get executed if an
exception is thrown from the divide method. -ut now the
program execution is not resumed inside the call;ivide method.
he exception is propagated to the method that calls call;ivide.
4rogram execution doesn8t resume until a catch%block
somewhere in the call stack catches the exception. 0ll methods
in the call stack between the method throwing the exception and
the method catching it have their execution stopped at the point
in the code where the exception is thrown or propagated.
.&ample% $atching IO.&ception2s
.f an exception is thrown during a se(uence of statements inside
a try%catch block) the se(uence of statements is interrupted and
the flow of control will skip directly to the catch%block. his code
can be interrupted by exceptions in several places"
public void open,ile)+;
try ;
AA constructor may throw ,ile1ot,ound.&ception
,ileSeader reader H new ,ileSeader)Lsome,ileL+G
Page '" of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
int iHKG
while)i ^H '7+;
AAreader.read)+ may throw IO.&ception
i H reader.read)+G
3ystem.out.println))char+ i +G
=
reader.close)+G
3ystem.out.println)L''' ,ile .nd '''L+G
= catch ),ile1ot,ound.&ception e+ ;
AAdo something clever with the e&ception
= catch )IO.&ception e+ ;
AAdo something clever with the e&ception
=
=
.f the reader.read+, method call throws an .O!xception) the
following 1ystem.out.println++char, i ,= is not executed. /either is
the last reader.close+, or the 1ystem.out.println+:%%% 'ile !nd %%%
:,= statements. .nstead the program skips directly to the
catch+.O!xception e,> ... ? catch clause. .f the new
'ile&eader+:some'ile:,= constructor call throws an exception)
none of the code inside the try%block is executed.
.&ample% Propagating IO.&ception2s
his code is a version of the previous method that throws the
exceptions instead of catching them"
public void open,ile)+ throws IO.&ception ;
,ileSeader reader H new ,ileSeader)Lsome,ileL+G
int iHKG
while)i ^H '7+;
i H reader.read)+G
3ystem.out.println))char+ i +G
=
reader.close)+G
3ystem.out.println)L''' ,ile .nd '''L+G
=
.f an exception is thrown from the reader.read+, method then
program execution is halted) and the exception is passed up the
call stack to the method that called open'ile+,. .f the calling
method has a try%catch block) the exception will be caught there.
.f the calling method also just throws the method on) the calling
method is also interrupted at the open'ile+, method call) and the
Page '' of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
exception passed on up the call stack. he exception is
propagated up the call stack like this until some method catches
the exception) or the Java Virtual Machine does.
,inally
7ou can attach a finally%clause to a try%catch block. he code
inside the finally clause will always be executed) even if an
exception is thrown from within the try or catch block. .f your
code has a return statement inside the try or catch block) the
code inside the finally%block will get executed before returning
from the method. Here is how a finally clause looks"
public void open,ile)+;
,ileSeader reader H nullG
try ;
reader H new ,ileSeader)Lsome,ileL+G
int iHKG
while)i ^H '7+;
i H reader.read)+G
3ystem.out.println))char+ i +G
=
= catch )IO.&ception e+ ;
AAdo something clever with the e&ception
= finally ;
if)reader ^H null+;
try ;
reader.close)+G
= catch )IO.&ception e+ ;
AAdo something clever with the e&ception
=
=
3ystem.out.println)L''' ,ile .nd '''L+G
=
=
/o matter whether an exception is thrown or not inside the try or
catch block the code inside the finally%block is executed. he
example above shows how the file reader is always closed)
regardless of the program flow inside the try or catch block.
/ote" .f an exception is thrown inside a finally block) and it is not
caught) then that finally block is interrupted just like the try%block
and catch%block is. hat is why the previous example had the
Page (( of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
reader.close+, method call in the finally block wrapped in a try%
catch block"
= finally ;
if)reader ^H null+;
try ;
reader.close)+G
= catch )IO.&ception e+ ;
AAdo something clever with the e&ception
=
=
3ystem.out.println)L''' ,ile .nd '''L+G
=
hat way the 1ystem.out.println+:%%% 'ile !nd %%%:,= method call
will always be executed. .f no unchecked exceptions are thrown
that is. More about checked and unchecked in a later chapter.
7ou don8t need both a catch and a finally block. 7ou can have
one of them or both of them with a try%block) but not none of
them. his code doesn8t catch the exception but lets it
propagate up the call stack. ;ue to the finally block the code still
closes the filer reader even if an exception is thrown.
public void open,ile)+ throws IO.&ception ;
,ileSeader reader H nullG
try ;
reader H new ,ileSeader)Lsome,ileL+G
int iHKG
while)i ^H '7+;
i H reader.read)+G
3ystem.out.println))char+ i +G
=
= finally ;
if)reader ^H null+;
try ;
reader.close)+G
= catch )IO.&ception e+ ;
AAdo something clever with the e&ception
=
=
3ystem.out.println)L''' ,ile .nd '''L+G
=
=
Page ( of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
/otice how the catch block is gone.
0ogging%
The #DE contains the L#ava 0ogging "PIL. >ia a logger you can save te&t to a
central place to report on errors* provide additional information about your program* etc.
This logging "PI allows to configure how messages are written by which class with
which priority
Overview of $ontrol ,low
0pplications make logging calls on Logger objects. *oggers are
organi5ed in a hierarchical namespace and child *oggers may
inherit some logging properties from their parents in the
namespace.
0pplications make logging calls on Logger objects. hese
*ogger objects allocate LogRecord objects which are passed
to Handler objects for publication. -oth *oggers and Handlers
may use logging Levels and +optionally, Filters to decide if they
are interested in a particular LogRecord. 6hen it is necessary to
publish a *og&ecord externally) a Handler can +optionally, use
a Formatter to locali5e and format the message before
publishing it to an .<O stream.
!ach *ogger keeps track of a set of output Handlers. -y default
all *oggers also send their output to their parent *ogger. -ut
*oggers may also be configured to ignore Handlers higher up
the tree.
1ome Handlers may direct output to other Handlers. 'or
example) the MemoryHandler maintains an internal ring buffer
of LogRecords and on trigger events it publishes its *og&ecords
through a target Handler. .n such cases) any formatting is done
by the last Handler in the chain.
Page (2 of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
he 04.s are structured so that calls on the *ogger 04.s can be
cheap when logging is disabled. .f logging is disabled for a given
log level) then the *ogger can make a cheap comparison test
and return. .f logging is enabled for a given log level) the *ogger
is still careful to minimi5e costs before passing the *og&ecord
into the Handlers. .n particular) locali5ation and formatting
+which are relatively expensive, are deferred until the Handler
re(uests them. 'or example) a MemoryHandler ca n maintain a
circular buffer of *og&ecords without having to pay formatting
costs.
0og 0evels
!ach log message has an associated log Level. he *evel gives
a rough guide to the importance and urgency of a log message.
*og level objects encapsulate an integer value) with higher
values indicating higher priorities.
he 0evel class defines seven standard log levels) ranging from
'./!1 +the lowest priority) with the lowest value, to 1!V!&!
+the highest priority) with the highest value,.
0oggers
0s stated earlier) client code sends log re(uests to *ogger
objects. !ach logger keeps track of a log level that it is
interested in) and discards log re(uests that are below this level.
*oggers are normally named entities) using dot %separated
names such as :java.awt:. he namespace is hierarchical and is
managed by the *ogManager. he namespace should typically
be aligned with the Java packaging namespace) but is not
re(uired to follow it slavishly. 'or example) a *ogger called
:java.awt: might handle logging re(uests for classes in the
java.awt package) but it might also handle logging for classes in
Page (# of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
sun.awt that support the client%visible abstractions defined in the
java.awt package.
.n addition to named *oggers) it is also possible to create
anonymous *oggers that don8t appear in the shared
namespace. 1ee section #. #@ .
*oggers keep track of their parent loggers in the logging
namespace. 0 logger8s parent is its nearest extant ancestor in
the logging namespace. he root *ogger +named ::, has no
parent. 0nonymous loggers are all given the root logger as their
parent. *oggers may inherit various attributes from their parents
in the logger namespace. .n particular) a logger may inherit"
0ogging level. If a 0ogger2s level is set to be null then the 0ogger will use an
effective 0evel that will be obtained by walking up the parent tree and using the
first non'null 0evel.
5andlers. /y default a 0ogger will log any output messages to its parent2s
handlers* and so on recursively up the tree.
Sesource bundle names. If a logger has a null resource bundle name* then it will
inherit any resource bundle name defined for its parent* and so on recursively up
the tree.
0ogging ?ethods
he *ogger class provides a large set of convenience methods
for generating log messages. 'or convenience) there are
methods for each logging level) named after the logging level
name. hus rather than calling
:logger.log+$onstants.60&/./A)...: a developer can simply call
the convenience method :logger.warning+...:
here are two different styles of logging methods) to meet the
needs of different communities of users.
'irst) there are methods that take an explicit source class name
and source method name. hese methods are intended for
developers who want to be able to (uickly locate the source of
any given logging message. 0n example of this style is"
#oid warning(String source.lass, String source8et9od, String &sg);
1econd) there are a set of methods that do not take explicit
source class or source method names. hese are intended for
Page ($ of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
developers who want easy%to%use logging and do not re(uire
detailed source information.
#oid warning(String &sg);
'or this second set of methods) the *ogging framework will
make a :best effort: to determine which class and method called
into the logging framework and will add this information into the
*og&ecord. However) it is important to reali5e that this
automatically inferred information may only be approximate. he
latest generation of virtual machines perform extensive
optimi5ations when J.ing and may entirely remove stack
frames) making it impossible to reliably locate the calling class
and method.
5andlers
J21! provides the following Handlers"
9tream:andler< " simple handler for writing formatted records to an
Output3tream.
Console:andler< " simple handler for writing formatted records to 3ystem.err
;ile:andler< " handler that writes formatted log records either to a single file* or
to a set of rotating log files.
9ocAet:andler< " handler that writes formatted log records to remote T$P ports.
Memory:andler< " handler that buffers log records in memory.
.t is fairly straightforward to develop new Handlers. ;evelopers
re(uiring specific functionality can either develop a Handler from
scratch or subclass one of the provided Handlers.
,ormatters
#83. also includes two standard ,ormatters%
9im+le;ormatter% 4rites brief Lhuman'readableL summaries of log records.
=ME;ormatter% 4rites detailed D?0'structured information.
0s with Handlers) it is fairly straightforward to develop new
'ormatters.
The 0og?anager
There is a global 0og?anager object that keeps track of global logging information. This
includes%
" hierarchical namespace of named 0oggers.
Page (! of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
" set of logging control properties read from the configuration file.
There is a single 0og?anager object that can be retrieved using the static
0og?anager.get0og?anager method. This is created during 0og?anager
initiali(ation* based on a system property. This property allows container
applications )such as .#/ containers+ to substitute their own subclass of
0og?anager in place of the default class.
$reate a logger
he package java.util.logging provides the logging capabilities
via the class *ogger.
To create a logger in your #ava coding.
import java.util.logging.0oggerG
private final static 0ogger 0OPP.S H 0ogger.get0ogger)?y$lass.class .get1ame)++G
0evel
he log levels define the severity of a message. he class *evel
is used to define which messages should be written to the log.
;ie *og *evels in descending order are"
1!V!&! +highest,
60&/./A
./'O
$O/'.A
'./!
'./!&
'./!1
.n addition to that you have also the levels O'' and 0** to turn
the logging of or to log everything.
'or example the following will set the logger to level info which
means all messages with severe) warning and info will be
logged.
0OPP.S.set0evel)0evel.I1,O+G
Page (% of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
"n .&ample
o help motivate the use of the logging 04.) we will use a
simple program) based on the idea of a :Hello 6orld: program.
public class 5ello4orld ;
public static void main)3tring9: args+ ;
5ello4orld hello H new 5ello4orld)L5ello world^L+G
hello.say5ello)+G
=
private 3tring the?essageG
public 5ello4orld)3tring message+ ;
the?essage H messageG
=
public void say5ello)+ ;
3ystem.err.println)the?essage+G
=
=
6e will expand upon this simple program in order to
demonstrate and motivate the logging 04.. he first thing we will
do is actually generate a logging message. his is
straightforward= we need to create a 0ogger object) which
represents the5ello4orld class) like this"
package logging.e&ample8G
import java.util.logging.0oggerG
ABB
B " simple #ava 5ello 4orld program* in the tradition of
B Eernighan and Sitchie.
BA
public class 5ello4orld ;
private static 0ogger the0ogger H
0ogger.get0ogger)5ello4orld.class.get1ame)++G
public static void main)3tring9: args+ ;
5ello4orld hello H new 5ello4orld)L5ello world^L+G
hello.say5ello)+G
=
private 3tring the?essageG
Page (& of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
public 5ello4orld)3tring message+ ;
the?essage H messageG
=
public void say5ello)+ ;
3ystem.err.println)the?essage+G
=
=
his generates a 0ogger) which we can use to generate logging
messages. 1ince you typically use one logger per class) we can
make it a static field of the 5ello4orld class. 6e use the fully
(ualified name of the 5ello4orld class as the name of the0ogger.
6e8ll look at the reasons for this in more detail later. /ow) let8s
actually use the 0ogger to try to generate a logging message"
import java.util.logging.0oggerG
public class 5ello4orld ;
private static 0ogger the0ogger H
0ogger.get0ogger)5ello4orld.class.get1ame)++G
public static void main)3tring9: args+ ;
5ello4orld hello H new 5ello4orld)L5ello world^L+G
hello.say5ello)+G
=
private 3tring the?essageG
public 5ello4orld)3tring message+ ;
the?essage H messageG
=
public void say5ello)+ ;
the0ogger.finest)L5ello logging^L+G
3ystem.err.println)the?essage+G
=
=
he logging 04. has a configuration file and by default) it
provides a handler that will send logging messages) in the form
of a0ogSecord to the console +3ystem.err,. 1o we would expect to
see the string L5ello logging^LG appear before our message of L5ello
world^L. -ut if you run this program you only see L5ello world^L"
Page (" of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
c java logging.e&ampleC.5ello4orld
5ello world
6hat8s going on hereB he answer lies in the notion of logging
levels.
"ssertions
0n assertion has a -oolean expression that) if evaluated as false)
indicates a bug in the code. his mechanism provides a way to
detect when a program starts falling into an inconsistent state.
0ssertions are excellent for documenting assumptions and
invariants about a class. Here is a simple example of assertion"
/ank"ccount acct H nullG
AA ...
AA Pet a /ank"ccount object
AA ...
AA $heck to ensure we have one
assert acct ^H nullG
his asserts that acct is not null. .f acct is null) an "ssertion.rror is
thrown. 0ny line that executes after the assert statement can
safely assume that acct is not null.
3sing assertions helps developers write code that is more
correct) more readable) and easier to maintain. hus) assertions
improve the odds that the behavior of a class matches the
expectations of its clients.
/ote that assertions can be compiled out. .n languages such as
$<$CC) this means using the preprocessor. .n $<$CC) you can
use assertions through the assert macro) which has the following
definition in 0/1. $"
void assert)int e&pression+
he program will be aborted if the e&pression evaluates to false) and
it has no effect if the e&pression evaluates to true. 6hen testing and
debugging is completed) assertions do not have to be removed
from the program. However) note that the program will be larger
in si5e and therefore slower to load. 6hen assertions are no
longer needed) the line
ddefine 1D./P
Page (' of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
is inserted at the beginning of the program. his causes the
$<$CC preprocessor to ignore all assertions) instead of deleting
them manually.
.n other words) this is a re(uirement for performance reasons.
7ou should write assertions into software in a form that can be
optionally compiled. hus) assertions should be executed with
the code only when you are debugging your program %% that is)
when assertions will really help flush out errors. 7ou can think of
assertions as a uniform mechanism that replaces the use of ad
hoc conditional tests.
Implementing "ssertions in #ava Technology
J21! #.9 and earlier versions have no built%in support for
assertions. hey can) however) be provided as an ad hoc
solution. Here is an example of how you would roll your own
assertion class.
Here we have an assert method that checks whether a -oolean
expression is true or false. .f the expression evaluates to true)
then there is no effect. -ut if it evaluates to false) the assert method
prints the stack trace and the program aborts. .n this sample
implementation) a second argument for a string is used so that
the cause of error can be printed.
/ote that in the assert method) . am checking whether the value
of 1D./P is on +true, or off +false,. .f 1D./P sets to true) then the
assertion is to be executed. Otherwise) it would have no effect.
he user of this class is able to set assertions on or off by
toggling the value of 1D./P. $ode 1ample # shows my
implementation.
public class "ssertion ;
public static boolean 1D./P H trueG
private static void print3tack)3tring why+ ;
Throwable t H new Throwable)why+G
t.print3tackTrace)+G
3ystem.e&it)7+G
=
public static void assert)boolean e&pression* 3tring why+ ;
if )1D./P ]] ^e&pression+ ;
print3tack)why+G
=
Page ( of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
=
=
1ote% In order for $ode 3ample 7 to compile* use Isource *.? because assert is a
keyword as of #83. 7.I. Otherwise* you will get the following error message%
$%`$0"33.3Xjavac "ssertion.java
"ssertion.java%77% as of release 7.I* 2assert2 is a keyword* and may not be used
as an identifier
)try 'source 7.C or lower to use 2assert2 as an identifier+
public static void assert)boolean e&pression* 3tring why+ ;
e
7 error
$ode 1ample 2 demonstrates how to use the "ssertion class. .n
this example) an integer representing the user8s age is read. .f
the age is greater than or e(ual to #D) the assertion evaluates
to true) and it will have no effect on the program execution. -ut if
the age is less than #D) the assertion evaluates to false. he
program then aborts) displays the message Rou are too young to vote)
and shows the stack trace.
It is important to note that in this e&ample assertions are used to validate user input and
that no invariant is being tested or verified. This is merely to demonstrate the use of
assertions.
import java.util.3cannerG
import java.io.IO.&ceptionG
public class "ssertionTest7 ;
public static void main)3tring argv9:+ throws IO.&ception ;
3canner reader H new 3canner)3ystem.in+G
3ystem.out.print)L.nter your age% L+G
int age H reader.ne&tInt)+G
AA"ssertion.1D./PHfalseG
"ssertion.assert)ageXH7Q* LRou are too young to voteL+G
AA use age
3ystem.out.println)LRou are eligible to voteL+G
=
=
import java.io.IO.&ceptionG
public class "ssertionTest8 ;
public static void main)3tring argv9:+ throws IO.&ception ;
3ystem.out.print)L.nter your marital status% L+G
int c H 3ystem.in.read)+G
Page of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
AA"ssertion.1D./PHfalseG
switch ))char+ c+ ;
case 2s2%
case 232% 3ystem.out.println)L3ingleL+G breakG
case 2m2%
case 2?2% 3ystem.out.println)L?arriedL+G breakG
case 2d2%
case 2D2% 3ystem.out.println)LDivorcedL+G breakG
default% "ssertion.assert)^true* LInvalid OptionL+G breakG
=
=
=
.n the three examples) if you do not want assertions to be
executed as part of the code) uncomment the line
"ssert.1D./P H falseG
sing "ssertions
3se the assert statement to insert assertions at particular points in
the code. he assert statement can have one of two forms"
assert boolean.&pressionG
assert boolean.&pression % error?essageG
he error?essage is an optional string message that would be
shown when an assertion fails.
0s an example) . will modify $ode 1ample 9 to use
the assert statement instead of my "ssertion class) as shown in
$ode 1ample @.
import java.io.BG
public class "ssertionTestC ;
public static void main)3tring argv9:+ throws IO.&ception ;
3ystem.out.print)L.nter your marital status% L+G
int c H 3ystem.in.read)+G
switch ))char+ c+ ;
case 2s2%
case 232% 3ystem.out.println)L3ingleL+G breakG
case 2m2%
case 2?2% 3ystem.out.println)L?arriedL+G breakG
case 2d2%
Page 2 of !"
G
www.csetube.in
If you try to compile your assertion'enabled classes without using the Isource
*.$ option* you will get a compiler error saying that assert is a new keyword as of
release 7.I.
.f you now run the program using the command
promptX java "ssertionTestC
and you enter a valid character) it will work fine. However) if you
enter an invalid character) nothing will happen. his is because)
by default) assertions are disabled at runtime. o enable
assertions) use the switch 'enableassertion +or 'ea, as follows"
promptX java 'ea "ssertionTestC
promptX java 'enableassertion "ssertionTestC
'ollowing is a sample run"
$%`$0"33.3Xjava 'ea "ssertionTestC
.nter your marital status% w
.&ception in thread LmainL java.lang."ssertion.rror% Invalid Option
at "ssertionTestC.main)"ssertionTestC.java%7M+
6hen an assertion fails) it means that the application has
entered an incorrect state. 4ossible behaviors may include
suspending the program or allowing it to continue to run. 0 good
behavior) however) might be to terminate the application)
because it may start functioning inappropriately after a failure. .n
this case) when an assertion fails) an "ssertion.rror is thrown.
1ote% /y default* assertions are disabled* so you must not assume that the /oolean
e&pression contained in an assertion will be evaluated. Therefore* your e&pressions must
be free of side effects.
he switch 'disableassertion +or 'da, can be used to disable
assertions. his) however) is most useful when you wish to
disable assertions on classes from specific packages. 'or
example) to run the program ?y$lass with assertions disabled in
class 5ello) you can use the following command"
Page # of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
promptX java 'da%com.javacourses.tests.5ello ?y$lass
0nd to disable assertions in a specific package and any
subpackages it may have) you can use the following command"
promptX java 'da%com.javacourses.tests... ?y$lass
/ote that the three%dot ellipsis +..., is part of the syntax.
1witches can be combined. 'or example) to run a program with
assertions enabled in the com.javacourses.tests package +and any
subpackages, and disabled in the class com.javacourses.ui.phone)
you can use the following command"
promptX java 'ea%com.javacourses.tests... 'da%com.javacourses.ui.phone ?y$lass
/ote that when switches are combined and applied to
packages) they are applied to all classes) including system
classes +which do not have class loaders,. -ut if you use them
with no arguments +'ea or 'da,) they do not apply to system
classes. .n other words) if you use the command
promptX java 'ea ?y$lass
then assertions are enabled in all classes except system
classes. .f you wish to turn assertions on or off in system
classes) use the switches 'enablesystemassertions +or 'esa, and '
disablesystemassertions +or 'dsa,.
sing "ssertions for Design by $ontract
he assertion facility can help you in supporting an informal
design%by%contract style of programming. 6e will now see
examples of using assertions for preconditions) postconditions)
and class invariants. he examples are snippets of code from
an integer stack) which provides operations such as push to add
an item on the stack and pop to retrieve an item from the stack.
4reconditions
.n order to retrieve an item from the stack) the stack must not be
empty. he condition that the stack must not be empty is a
precondition. his precondition can be programmed using
assertions as follows"
public int pop)+ ;
AA precondition
assert ^is.mpty)+ % L3tack is emptyLG
return stack9''num:G
Page $ of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
=
1ote% /ecause assertions might be disabled in some cases* precondition checking can still
be performed by checks inside methods that result in e&ceptions such
as)llegal(rgu&ent03ception or FullPointer03ception.
4ostconditions
.n order to push an item on the stack) the stack must not be full.
his is a precondition. o add an item on the stack) we assign
the element to be added to the next index in the stack as
follows"
stack9numFF: H elementG
However) if you make a mistake and you write this statement as
stack9num: H element
then you have a bug. .n this case) we need to ensure that
invoking the push operation is working correctly. 1o the
postcondition here is to ensure that the new index in the stack is
the old index plus one. 0lso) we need to make sure that the
element has been added on the stack. he following snippet of
code shows the push operation with a precondition and a
postcondition.
public void push)int element+ ;
AA precondition
assert numWcapacity % Lstack is fullLG
int old1um H numG
stack9num: H elementG
AA postcondition
assert num HH old1umF7 ]] stack9num'7: HH element % Lproblem with counterLG
=
/ote that if a method has multiple return statements) then
postconditions should be evaluated before each of these return
statements.
$lass .nvariants
0 class invariant is a predicate that must be true before and
after any method completes. .n the stack example) the invariant
would be that the number of elements in the stack is greater
than or e(ual to 5ero and the number of elements should not
exceed the maximum capacity of the class. hese conditions)
for example) can be coded as follows"
Page ! of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
private boolean inv)+ ;
return )num XH K ]] num W capacity+G
=
o check that the stack should satisfy this predicate at all times)
each public method and constructor should contain the
assertion
assert inv)+G
right before each return.
1IT >
M/lti T.e,*in+?
#ava provides built'in support for multithreaded +rogramming. " multithreaded
program contains two or more parts that can run concurrently. .ach part of such a
program is called a thread* and each thread defines a separate path of e&ecution.
" multithreading is a speciali(ed form of multitasking. ?ultitasking threads
re-uire less overhead than multitasking processes.
" process consists of the memory space allocated by the operating system that
can contain one or more threads. " thread cannot e&ist on its ownG it must be a part of a
process. " process remains running until all of the non'daemon threads are done
e&ecuting.
?ultithreading enables you to write very efficient programs that make ma&imum
use of the $P* because idle time can be kept to a minimum.
4ife C0!le of , T.e,*?
" thread goes through various stages in its life cycle. ,or e&ample* a thread is
born* started* runs* and then dies. ,ollowing diagram shows complete life cycle of a
thread.
Page % of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
"bove mentioned stages are e&plained here%
1ew% " new thread begins its life cycle in the new state. It remains in this state
until the program starts the thread. It is also referred to as a born thread.
Sunnable% "fter a newly born thread is started* the thread becomes runnable. "
thread in this state is considered to be e&ecuting its task.
4aiting% 3ometimes a thread transitions to the waiting state while the thread waits
for another thread to perform a task." thread transitions back to the runnable state
only when another thread signals the waiting thread to continue e&ecuting.
Timed waiting% " runnable thread can enter the timed waiting state for a specified
interval of time. " thread in this state transitions back to the runnable state when
that time interval e&pires or when the event it is waiting for occurs.
Terminated% " runnable thread enters the terminated state when it completes its
task or otherwise terminates.
$reating a Thread%
#ava defines two ways in which this can be accomplished%
Rou can implement the Sunnable interface.
Rou can e&tend the Thread class* itself.
$reate Thread by Implementing Sunnable%
The easiest way to create a thread is to create a class that implements the Sunnable
interface.
To implement Sunnable* a class need only implement a single method called run) +*
which is declared like this%
Page & of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
public void run) +
Rou will define the code that constitutes the new thread inside run)+ method. It is
important to understand that run)+ can call other methods* use other classes* and declare
variables* just like the main thread can.
"fter you create a class that implements Sunnable* you will instantiate an object of type
Thread from within that class. Thread defines several constructors. The one that we will
use is shown here%
Thread)Sunnable threadOb* 3tring thread1ame+G
5ere threadOb is an instance of a class that implements the Sunnable interface and the
name of the new thread is specified by threadBame.
"fter the new thread is created* it will not start running until you call its start) + method*
which is declared within Thread. The start) + method is shown here%
void start) +G
.&ample%
5ere is an e&ample that creates a new thread and starts it running%
class 1ewThread implements Sunnable ;
Thread tG
1ewThread)+ ;
AA $reate a new* second thread
t H new Thread)this* LDemo ThreadL+G
3ystem.out.println)L$hild thread% L F t+G
t.start)+G AA 3tart the thread
=
public void run)+ ;
try ;
for)int i H MG i X KG i''+ ;
3ystem.out.println)L$hild Thread% L F i+G
AA 0et the thread sleep for a while.
Thread.sleep)MKK+G
=
= catch )Interrupted.&ception e+ ;
3ystem.out.println)L$hild interrupted.L+G
=
3ystem.out.println)L.&iting child thread.L+G
=
=
class ThreadDemo ;
public static void main)3tring args9:+ ;
new 1ewThread)+G AA create a new thread
try ;
Page " of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
for)int i H MG i X KG i''+ ;
3ystem.out.println)L?ain Thread% L F i+G
Thread.sleep)7KKK+G
=
= catch )Interrupted.&ception e+ ;
3ystem.out.println)L?ain thread interrupted.L+G
=
3ystem.out.println)L?ain thread e&iting.L+G
=
=
This would produce following result%
$hild thread% Thread9Demo Thread*M*main:
?ain Thread% M
$hild Thread% M
$hild Thread% I
?ain Thread% I
$hild Thread% C
$hild Thread% 8
?ain Thread% C
$hild Thread% 7
.&iting child thread.
?ain Thread% 8
?ain Thread% 7
?ain thread e&iting.
$reate Thread by .&tending Thread%
The second way to create a thread is to create a new class that e&tends Thread* and then
to create an instance of that class.
The e&tending class must override the run) + method* which is the entry point for the new
thread. It must also call start) + to begin e&ecution of the new thread.
.&ample%
5ere is the preceding program rewritten to e&tend Thread%
class 1ewThread e&tends Thread ;
1ewThread)+ ;
AA $reate a new* second thread
super)LDemo ThreadL+G
3ystem.out.println)L$hild thread% L F this+G
start)+G AA 3tart the thread
=
AA This is the entry point for the second thread.
public void run)+ ;
Page ' of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
try ;
for)int i H MG i X KG i''+ ;
3ystem.out.println)L$hild Thread% L F i+G
AA 0et the thread sleep for a while.
Thread.sleep)MKK+G
=
= catch )Interrupted.&ception e+ ;
3ystem.out.println)L$hild interrupted.L+G
=
3ystem.out.println)L.&iting child thread.L+G
=
=
class .&tendThread ;
public static void main)3tring args9:+ ;
new 1ewThread)+G AA create a new thread
try ;
for)int i H MG i X KG i''+ ;
3ystem.out.println)L?ain Thread% L F i+G
Thread.sleep)7KKK+G
=
= catch )Interrupted.&ception e+ ;
3ystem.out.println)L?ain thread interrupted.L+G
=
3ystem.out.println)L?ain thread e&iting.L+G
=
=
This would produce following result%
$hild thread% Thread9Demo Thread*M*main:
?ain Thread% M
$hild Thread% M
$hild Thread% I
?ain Thread% I
$hild Thread% C
$hild Thread% 8
?ain Thread% C
$hild Thread% 7
.&iting child thread.
?ain Thread% 8
?ain Thread% 7
?ain thread e&iting.
Thread ?ethods%
,ollowing is the list of important medthods available in the Thread class.
Page 2( of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
?ethods with Description
public void start)+
3tarts the thread in a separate path of e&ecution* then invokes the run)+ method on this
Thread object.
public void run)+
If this Thread object was instantiated using a separate Sunnable target* the run)+ method is
invoked on that Sunnable object.
public final void set1ame)3tring name+
$hanges the name of the Thread object. There is also a get1ame)+ method for retrieving
the name.
public final void setPriority)int priority+
3ets the priority of this Thread object. The possible values are between 7 and 7K.
public final void setDaemon)boolean on+
" parameter of true denotes this Thread as a daemon thread.
public final void join)long millisec+
The current thread invokes this method on a second thread* causing the current thread to
block until the second thread terminates or the specified number of milliseconds passes.
public void interrupt)+
Interrupts this thread* causing it to continue e&ecution if it was blocked for any reason.
public final boolean is"live)+
Seturns true if the thread is alive* which is any time after the thread has been started but
before it runs to completion.
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
public class Display?essage implements Sunnable
;
private 3tring messageG
public Display?essage)3tring message+
;
this.message H messageG
=
public void run)+
;
while)true+
;
3ystem.out.println)message+G
=
=
=
AA ,ile 1ame % Puess"1umber.java
AA $reate a thread to e&tentd Thread
public class Puess"1umber e&tends Thread
;
private int numberG
public Puess"1umber)int number+
;
this.number H numberG
=
public void run)+
;
int counter H KG
int guess H KG
do
;
guess H )int+ )?ath.random)+ B 7KK F 7+G
3ystem.out.println)this.get1ame)+
F L guesses L F guess+G
counterFFG
=while)guess ^H number+G
3ystem.out.println)LBB $orrect^ L F this.get1ame)+
F L in L F counter F L guesses.BBL+G
=
=
AA ,ile 1ame % Thread$lassDemo.java
public class Thread$lassDemo
;
public static void main)3tring 9: args+
Page 22 of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
;
Sunnable hello H new Display?essage)L5elloL+G
Thread thread7 H new Thread)hello+G
thread7.setDaemon)true+G
thread7.set1ame)LhelloL+G
3ystem.out.println)L3tarting hello thread...L+G
thread7.start)+G
Sunnable bye H new Display?essage)LPoodbyeL+G
Thread thread8 H new Thread)hello+G
thread8.setPriority)Thread.?I1VPSIOSITR+G
thread8.setDaemon)true+G
3ystem.out.println)L3tarting goodbye thread...L+G
thread8.start)+G
3ystem.out.println)L3tarting threadC...L+G
Thread threadC H new Puess"1umber)8J+G
threadC.start)+G
try
;
threadC.join)+G
=catch)Interrupted.&ception e+
;
3ystem.out.println)LThread interrupted.L+G
=
3ystem.out.println)L3tarting threadI...L+G
Thread threadI H new Puess"1umber)JM+G
threadI.start)+G
3ystem.out.println)Lmain)+ is ending...L+G
=
=
This would produce following result. Rou can try this e&ample again and again and you
would get different result every time.
3tarting hello thread...
3tarting goodbye thread...
5ello
5ello
5ello
5ello
5ello
5ello
5ello
5ello
Page 2# of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
5ello
Thread'8 guesses 8J
5ello
BB $orrect^ Thread'8 in 7K8 guesses.BB
5ello
3tarting threadI...
5ello
5ello
..........remaining result produced
Interrupting thrreads%
Interrupting a thread means stopping what it is doing before it has completed its task*
effectively aborting its current operation. 4hether the thread dies* waits for new tasks* or
goes on to the ne&t step depends on the application.
"lthough it may seem simple at first* you must take some precautions in order to achieve
the desired result. There are some caveats you must be aware of as well.
,irst of all* forget the Thread.stop method. "lthough it indeed stops a running thread* the
method is unsafe and was deprecated* which means it may not be available in future
versions of the #ava.
"nother method that can be confusing for the unadvised is Thread.interrupt. Despite what
its name may imply* the method does not interrupt a running thread )more on this later+*
as 0isting " demonstrates. It creates a thread and tries to stop it usingThread.interrupt.
The calls to Thread.sleep)+ give plenty of time for the thread initiali(ation and
termination. The thread itself does not do anything useful.
0isting "%
class .&ample7 e&tends Thread ;
public static void main) 3tring args9: + throws .&ception ;
.&ample7 thread H new .&ample7)+G
3ystem.out.println) L3tarting thread...L +G
thread.start)+G
Thread.sleep) CKKK +G
3ystem.out.println) LInterrupting thread...L +G
thread.interrupt)+G
Thread.sleep) CKKK +G
3ystem.out.println) L3topping application...L +G
3ystem.e&it) K +G
=
public void run)+ ;
while ) true + ;
3ystem.out.println) LThread is running...L +G
long time H 3ystem.currentTime?illis)+G
Page 2$ of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
while ) 3ystem.currentTime?illis)+'time W 7KKK + ;
=
=
=
=
If you run the code in 0isting "* you should see something like this on your console%
3tarting thread...
Thread is running...
Thread is running...
Thread is running...
Interrupting thread...
Thread is running...
Thread is running...
Thread is running...
3topping application...
.ven after Thread.interrupt)+ is called* the thread continues to run for a while.
Seally interrupting a thread
The best* recommended way to interrupt a thread is to use a shared variable to signal that
it must stop what it is doing. The thread must check the variable periodically* especially
during lengthy operations* and terminate its task in an orderly manner.0isting
/ demonstrates this techni-ue.
0isting /%
class 03a&ple> e3tends T9read {
#olatile boolean stop = false;
public static #oid &ain( String args:; ) t9rows 03ception {
03a&ple> t9read = new 03a&ple>();
S+ste&.out.println( !Starting t9read...! );
t9read.start();
T9read.sleep( ?%%% );
S+ste&.out.println( !(s'ing t9read to stop...! );
t9read.stop = true;
T9read.sleep( ?%%% );
S+ste&.out.println( !Stopping application...! );
S+ste&.e3it( % );
}
public #oid run() {
w9ile ( Jstop ) {
S+ste&.out.println( !T9read is running...! );
long ti&e = S+ste&.currentTi&e8illis();
w9ile ( (S+ste&.currentTi&e8illis()Iti&e < *%%%) KK (Jstop) ) {
}
}
S+ste&.out.println( !T9read e3iting under re1uest...! );
Page 2! of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
}
}
Sunning the code in 0isting / will generate output like this )notice how the thread e&its
in an orderly fashion+%
3tarting thread...
Thread is running...
Thread is running...
Thread is running...
"sking thread to stop...
Thread e&iting under re-uest...
3topping application...
"lthough this method re-uires some coding* it is not difficult to implement and give the
thread the opportunity to do any cleanup needed* which is an absolute re-uirement for
any multithreaded application. #ust be sure to declare the shared variable as volatile or
enclose any access to it into synchroni(ed blocksAmethods.
3o far* so good^ /ut what happens if the thread is blocked waiting for some eventT Of
course* if the thread is blocked* it can2t check the shared variable and can2t stop. There are
plenty of situations when that may occur* such as
calling Object.wait)+*3erver3ocket.accept)+* and Datagram3ocket.receive)+* to name a
few.
They all can block the thread forever. .ven if a timeout is employed* it may not be
feasible or desirable to wait until the timeout e&pires* so a mechanism to prematurely e&it
the blocked state must be used.
nfortunately there is no such mechanism that works for all cases* but the particular
techni-ue to use depends on each situation. In the following sections* I2ll give solutions
for the most common cases.
Interrupting a thread with Thread.interrupt)+
"s demonstrated in 0isting "* the method Thread.interrupt)+ does not interrupt a running
thread. 4hat the method actually does is to throw an interrupt if the thread is blocked* so
that it e&its the blocked state. ?ore precisely* if the thread is blocked at one of the
methods Object.wait* Thread.join* or Thread.sleep* it receives anInterrupted.&ception*
thus terminating the blocking method prematurely.
3o* if a thread blocks in one of the aforementioned methods* the correct way to stop it is
to set the shared variable and then call the interrupt)+ method on it )notice that it is
important to set the variable first+. If the thread is not blocked* calling interrupt)+ will not
hurtG otherwise* the thread will get an e&ception )the thread must be prepared to handle
this condition+ and escape the blocked state. In either case* eventually the thread will test
Page 2% of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
the shared variable and stop. 0ist in g $ is a simple e&ample that demonstrates this
techni-ue.
0isting $%
class 03a&ple? e3tends T9read {
#olatile boolean stop = false;
public static #oid &ain( String args:; ) t9rows 03ception {
03a&ple? t9read = new 03a&ple?();
S+ste&.out.println( !Starting t9read...! );
t9read.start();
T9read.sleep( ?%%% );
S+ste&.out.println( !(s'ing t9read to stop...! );
t9read.stop = true;
t9read.interrupt();
T9read.sleep( ?%%% );
S+ste&.out.println( !Stopping application...! );
S+ste&.e3it( % );
}
public #oid run() {
w9ile ( Jstop ) {
S+ste&.out.println( !T9read running...! );
tr+ {
T9read.sleep( *%%% );
} catc9 ( )nterrupted03ception e ) {
S+ste&.out.println( !T9read interrupted...! );
}
}
S+ste&.out.println( !T9read e3iting under re1uest...! );
}
}
"s soon as Thread.interrupt)+ is called in 0isting $* the thread gets an e&ception so that it
escapes the blocked state and determines that it should stop. Sunning this code produces
output like this%
3tarting thread...
Thread running...
Thread running...
Thread running...
"sking thread to stop...
Thread interrupted...
Thread e&iting under re-uest...
3topping application...
Interrupting an IAO operation
/ut what happens if the thread is blocked on an IAO operationT IAO can block a thread for
a considerable amount of time* particularly if network communication is involved. ,or
e&ample* a server may be waiting for a re-uest* or a network application may be waiting
for an answer from a remote host.
Page 2& of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
If you2re using channels* available with the new IAO "PI introduced in #ava 7.I* the
blocked thread will get a $losed/yInterrupt.&ception e&ception. If that is the case* the
logic is the same as that used in the third e&ampleUonly the e&ception is different.
/ut you might be using the traditional IAO available since #ava 7.K* since the new IAO is
so recent and re-uires more work. In this case* Thread.interrupt)+ doesn2t help* since the
thread will not e&it the blocked state. 0 isting D demonstrates that behavior. "lthough
the interrupt)+ method is called* the thread does not e&it the blocked state.
0isting D%
i&port 6a#a.io.L;
class 03a&ple$ e3tends T9read {
public static #oid &ain( String args:; ) t9rows 03ception {
03a&ple$ t9read = new 03a&ple$();
S+ste&.out.println( !Starting t9read...! );
t9read.start();
T9read.sleep( ?%%% );
S+ste&.out.println( !)nterrupting t9read...! );
t9read.interrupt();
T9read.sleep( ?%%% );
S+ste&.out.println( !Stopping application...! );
S+ste&.e3it( % );
}
public #oid run() {
Ser#erSoc'et soc'et;
tr+ {
soc'et = new Ser#erSoc'et(BM@A);
} catc9 ( )503ception e ) {
S+ste&.out.println( !.ould not create t9e soc'et...! );
return;
}
w9ile ( true ) {
S+ste&.out.println( !Naiting for connection...! );
tr+ {
Soc'et soc' = soc'et.accept();
} catc9 ( )503ception e ) {
S+ste&.out.println( !accept() failed or interrupted...! );
}
}
}
}
,ortunately* the #ava Platform provides a solution for that case by calling
the close)+method of the socket the thread is blocked in. In this case* if the thread is
blocked in an IAO operation* the thread will get a 3ocket.&ception e&ception* much like
theinterrupt)+ method causes an Interrupted.&ception to be thrown.
Page 2" of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
The only caveat is that a reference to the socket must be available so that
its close)+method can be called. That means the socket object must also be shared. 0 ist in g
.demonstrates this case. The logic is the same as in the e&amples presented so far.
"nd here2s the sample output you can e&pect from running 0isting .%
0isting .%
i&port 6a#a.net.L;
i&port 6a#a.io.L;
class 03a&ple@ e3tends T9read {
#olatile boolean stop = false;
#olatile Ser#erSoc'et soc'et;
public static #oid &ain( String args:; ) t9rows 03ception {
03a&ple@ t9read = new 03a&ple@();
S+ste&.out.println( !Starting t9read...! );
t9read.start();
T9read.sleep( ?%%% );
S+ste&.out.println( !(s'ing t9read to stop...! );
t9read.stop = true;
t9read.soc'et.close();
T9read.sleep( ?%%% );
S+ste&.out.println( !Stopping application...! );
S+ste&.e3it( % );
}
public #oid run() {
tr+ {
soc'et = new Ser#erSoc'et(BM@A);
} catc9 ( )503ception e ) {
S+ste&.out.println( !.ould not create t9e soc'et...! );
return;
}
w9ile ( Jstop ) {
S+ste&.out.println( !Naiting for connection...! );
tr+ {
Soc'et soc' = soc'et.accept();
} catc9 ( )503ception e ) {
S+ste&.out.println( !accept() failed or interrupted...! );
}
}
S+ste&.out.println( !T9read e3iting under re1uest...! );
}
}
3tarting thread...
4aiting for connection...
"sking thread to stop...
accept)+ failed or interrupted...
Thread e&iting under re-uest...
3topping application...
Page 2' of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
?ultithreading is a powerful tool* but it presents its own set of challenges. One of these is
how to interrupt a running thread. If properly implemented* these techni-ues make
interrupting a thread no more difficult than using the built'in operations already provided
by the #ava Platform.
Thread Priorities%
.very #ava thread has a priority that helps the operating system determine the order in
which threads are scheduled.
#ava priorities are in the range between ?I1VPSIOSITR )a constant of 7+ and
?"DVPSIOSITR )a constant of 7K+. /y default* every thread is given priority
1OS?VPSIOSITR )a constant of M+.
Threads with higher priority are more important to a program and should be allocated
processor time before lower'priority threads. 5owever* thread priorities cannot guarantee
the order in which threads e&ecute and very much platform dependentant.
3etting a threads priority can be very useful if one thread has more critical tasks to
perform than another.
The Thread class has a method called setPriority)int level+ with which you can alter the
priority a Thread instance has.
The priority level range from 7 )least important+ to 7K )most important+ and if no level is
e&plicitly set* a Thread instance has the priority level of M.
In the first e&ample below no priorites are set* so both threads have the priority level M.
The TestThread class implements the Sunnable interface and in its
run)+ method loops from 7 to 7K and output the number along with its Thread id* which is
passed to the constructor.
&/(li! !l,"" ?ain ;
&/(li! $oi* setPrioritiesOnThreads)+ ;
Thread thread7 H ne% Thread)ne% TestThread)7++G
Thread thread8 H ne% Thread)ne% TestThread)8++G
thread7.start)+G
thread8.start)+G
t0 ;
thread7.join)+G
thread8.join)+G
= !,t!. )Interrupted.&ception e&+ ;
e&.print3tackTrace)+G
Page #( of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
=
3ystem.out.println)LDone.L+G
=
&/(li! "t,ti! $oi* main)3tring9: args+ ;
ne% ?ain)+.setPrioritiesOnThreads)+G
=
!l,"" TestThread i-&le-ent" Sunnable ;
int idG
&/(li! TestThread)int id+ ;
t.i".id H idG
=
&/(li! $oi* run)+ ;
fo )int i H 7G i WH 7KG iFF+ ;
3ystem.out.println)LThreadL F id F L% L F i+G
=
=
=
=
3ince both threads have the same priority* the output will be a mi& between them and
could look like this%
Thread8% 7
Thread7% 7
Thread8% 8
Thread7% 8
Thread8% C
Thread7% C
Thread8% I
Thread7% I
Thread8% M
Thread7% M
Thread8% N
Thread7% N
Thread8% J
Thread8% Q
Page # of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Thread8% O
Thread8% 7K
Thread7% J
Thread7% Q
Thread7% O
Thread7% 7K
Done.
The output could look different from on e&ecution to another since we have no control of
how the $P will prioriti(e them.
If we set the priority on the threads we still haven2t got e&act control of the e&ecution* but
at least we can tell the $P which one we think is
most important. The ne&t e&ample is identical to the one above e&cept for the lines where
the priority of the threads are set%
&/(li! !l,"" ?ain ;
&/(li! $oi* setPrioritiesOnThreads)+ ;
Thread thread7 H ne% Thread)ne% TestThread)7++G
Thread thread8 H ne% Thread)ne% TestThread)8++G
AA3etting priorities on the Thread objects
thread7.setPriority)Thread.?"DVPSIOSITR+G
thread8.setPriority)Thread.?I1VPSIOSITR+G
thread7.start)+G
thread8.start)+G
t0 ;
AA4ait for the threads to finish
thread7.join)+G
thread8.join)+G
= !,t!. )Interrupted.&ception e&+ ;
e&.print3tackTrace)+G
=
3ystem.out.println)LDone.L+G
=
&/(li! "t,ti! $oi* main)3tring9: args+ ;
ne% ?ain)+.setPrioritiesOnThreads)+G
=
Page #2 of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
!l,"" TestThread i-&le-ent" Sunnable ;
int idG
&/(li! TestThread)int id+ ;
t.i".id H idG
=
&/(li! $oi* run)+ ;
fo )int i H 7G i WH 7KG iFF+ ;
3ystem.out.println)LThreadL F id F L% L F i+G
=
=
=
=
The output from the code looked like this when e&ecuted%
Thread7% 7
Thread7% 8
Thread7% C
Thread7% I
Thread7% M
Thread7% N
Thread7% J
Thread7% Q
Thread7% O
Thread7% 7K
Thread8% 7
Thread8% 8
Thread8% C
Thread8% I
Thread8% M
Thread8% N
Thread8% J
Thread8% Q
Thread8% O
Thread8% 7K
Done.
It is however not certain that the first thread will be prioriti(ed to finish before the second
thread starts every time. It is up to the $P to decide.
Page ## of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Thread 3ynchroni(ation %
4hen 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 synchroni(ation is achieved is called thread synchronization.
The synchroni(ed keyword in #ava creates a block of code referred to as a critical section.
.very #ava object with a critical section of code gets a lock associated with the object. To
enter a critical section* a thread needs to obtain the corresponding object2s lock.
This is the general form of the synchroni(ed statement%
synchroni(ed)object+ ;
AA statements to be synchroni(ed
=
5ere* object is a reference to the object being synchroni(ed. " synchroni(ed block
ensures that a call to a method that is a member of object occurs only after the current
thread has successfully entered object2s monitor.
5ere is an e&ample* using a synchroni(ed block within the run) + method%
class $allme ;
void call)3tring msg+ ;
3ystem.out.print)L9L F msg+G
try ;
Thread.sleep)7KKK+G
= catch )Interrupted.&ception e+ ;
3ystem.out.println)LInterruptedL+G
=
3ystem.out.println)L:L+G
=
=
AA ,ile 1ame % $aller.java
class $aller implements Sunnable ;
3tring msgG
$allme targetG
Thread tG
public $aller)$allme targ* 3tring s+ ;
target H targG
msg H sG
t H new Thread)this+G
t.start)+G
=
AA synchroni(e calls to call)+
public void run)+ ;
Page #$ of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
synchroni(ed)target+ ; AA synchroni(ed block
target.call)msg+G
=
=
=
AA ,ile 1ame % 3ynch.java
class 3ynch ;
public static void main)3tring args9:+ ;
$allme target H new $allme)+G
$aller ob7 H new $aller)target* L5elloL+G
$aller ob8 H new $aller)target* L3ynchroni(edL+G
$aller obC H new $aller)target* L4orldL+G
AA wait for threads to end
try ;
ob7.t.join)+G
ob8.t.join)+G
obC.t.join)+G
= catch)Interrupted.&ception e+ ;
3ystem.out.println)LInterruptedL+G
=
=
=
This would produce following result%
95ello:
94orld:
93ynchroni(ed:
Interthread $ommunication%
$onsider the classic -ueuing problem* where one thread is producing some data and
another is consuming it. To make the problem more interesting* suppose that the producer
has to wait until the consumer is finished before it generates more data.
In a polling system* the consumer would waste many $P cycles while it waited for the
producer to produce. Once the producer was finished* it would start polling* wasting more
$P cycles waiting for the consumer to finish* and so on. $learly* this situation is
undesirable.
To avoid polling* #ava includes an elegant interprocess communication mechanism via
the following methods%
wait) +% This method 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) +% This method wakes up the first thread that called wait) + on the same
object.
Page #! of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
notify"ll) +% This method wakes up all the threads that called wait) + on the same
object.c The highest priority thread will run first.
These methods are implemented as final methods in Object* so all classes have them. "ll
three methods can be called only from within a synchroni(ed conte&t.
These methods are declared within Object. >arious forms of wait) + e&ist that allow you
to specify a period of time to wait.
.&ample%
The following sample program consists of four classes% \* the -ueue that you2re trying to
synchroni(eG Producer* the threaded object that is producing -ueue entriesG $onsumer* the
threaded object that is consuming -ueue entriesG and P$* the tiny class that creates the
single \* Producer* and $onsumer.
The proper way to write this program in #ava is to use wait) + and notify) + to signal in
both directions* as shown here%
class \ ;
int nG
boolean value3et H falseG
synchroni(ed int get)+ ;
if)^value3et+
try ;
wait)+G
= catch)Interrupted.&ception e+ ;
3ystem.out.println)LInterrupted.&ception caughtL+G
=
3ystem.out.println)LPot% L F n+G
value3et H falseG
notify)+G
return nG
=
synchroni(ed void put)int n+ ;
if)value3et+
try ;
wait)+G
= catch)Interrupted.&ception e+ ;
3ystem.out.println)LInterrupted.&ception caughtL+G
=
this.n H nG
value3et H trueG
3ystem.out.println)LPut% L F n+G
notify)+G
=
=
Page #% of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
class Producer implements Sunnable ;
\ -G
Producer)\ -+ ;
this.- H -G
new Thread)this* LProducerL+.start)+G
=
public void run)+ ;
int i H KG
while)true+ ;
-.put)iFF+G
=
=
=
class $onsumer implements Sunnable ;
\ -G
$onsumer)\ -+ ;
this.- H -G
new Thread)this* L$onsumerL+.start)+G
=
public void run)+ ;
while)true+ ;
-.get)+G
=
=
=
class P$,i&ed ;
public static void main)3tring args9:+ ;
\ - H new \)+G
new Producer)-+G
new $onsumer)-+G
3ystem.out.println)LPress $ontrol'$ to stop.L+G
=
=
Inside get) +* wait) + is called. This causes its e&ecution to suspend until the Producer
notifies you that some data is ready.
4hen this happens* e&ecution inside get) + resumes. "fter the data has been obtained*
get) + calls notify) +. This tells Producer that it is okay to put more data in the -ueue.
Inside put) +* wait) + suspends e&ecution until the $onsumer has removed the item from
the -ueue. 4hen e&ecution resumes* the ne&t item of data is put in the -ueue* and notify)
+ is called. This tells the $onsumer that it should now remove it.
Page #& of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
5ere is some output from this program* which shows the clean synchronous behavior%
Put% 7
Pot% 7
Put% 8
Pot% 8
Put% C
Pot% C
Put% I
Pot% I
Put% M
Pot% M
Thread Deadlock%
" special type of error that you need to avoid that relates specifically to multitasking is
deadlock* which occurs when two threads have a circular dependency on a pair of
synchroni(ed objects.
,or e&ample* suppose one thread enters the monitor on object D and another thread enters
the monitor on object R. If the thread in D tries to call any synchroni(ed method on R* it
will block as e&pected. 5owever* if the thread in R* in turn* tries to call any synchroni(ed
method on D* the thread waits forever* because to access D* it would have to release its
own lock on R so that the first thread could complete.
.&ample%
To understand deadlock fully* it is useful to see it in action. The ne&t e&ample creates two
classes* " and /* with methods foo) + and bar) +* respectively* which pause briefly before
trying to call a method in the other class.
The main class* named Deadlock* creates an " and a / instance* and then starts a second
thread to set up the deadlock condition. The foo) + and bar) + methods use sleep) + as a
way to force the deadlock condition to occur.
class " ;
synchroni(ed void foo)/ b+ ;
3tring name H Thread.currentThread)+.get1ame)+G
3ystem.out.println)name F L entered ".fooL+G
try ;
Thread.sleep)7KKK+G
= catch).&ception e+ ;
3ystem.out.println)L" InterruptedL+G
=
3ystem.out.println)name F L trying to call /.last)+L+G
b.last)+G
Page #" of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
=
synchroni(ed void last)+ ;
3ystem.out.println)LInside ".lastL+G
=
=
class / ;
synchroni(ed void bar)" a+ ;
3tring name H Thread.currentThread)+.get1ame)+G
3ystem.out.println)name F L entered /.barL+G
try ;
Thread.sleep)7KKK+G
= catch).&ception e+ ;
3ystem.out.println)L/ InterruptedL+G
=
3ystem.out.println)name F L trying to call ".last)+L+G
a.last)+G
=
synchroni(ed void last)+ ;
3ystem.out.println)LInside ".lastL+G
=
=
class Deadlock implements Sunnable ;
" a H new ")+G
/ b H new /)+G
Deadlock)+ ;
Thread.currentThread)+.set1ame)L?ainThreadL+G
Thread t H new Thread)this* LSacingThreadL+G
t.start)+G
a.foo)b+G AA get lock on a in this thread.
3ystem.out.println)L/ack in main threadL+G
=
public void run)+ ;
b.bar)a+G AA get lock on b in other thread.
3ystem.out.println)L/ack in other threadL+G
=
public static void main)3tring args9:+ ;
new Deadlock)+G
=
=
5ere is some output from this program%
?ainThread entered ".foo
SacingThread entered /.bar
?ainThread trying to call /.last)+
SacingThread trying to call ".last)+
Page #' of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
/ecause the program has deadlocked* you need to press $TS0'$ to end the program.
Rou can see a full thread and monitor cache dump by pressing $TS0'/S."E on a P$ .
Rou will see that SacingThread owns the monitor on b* while it is waiting for the monitor
on a. "t the same time* ?ainThread owns a and is waiting to get b. This program will
never complete.
"s this e&ample illustrates* if your multithreaded program locks up occasionally*
deadlock is one of the first conditions that you should check for.
Thread $ontrol%
4hile the suspend) +* resume) +* and stop) + methods defined by Thread class seem to be
a perfectly reasonable and convenient approach to managing the e&ecution of threads*
they must not be used for new #ava programs and obsolete in newer versions of #ava.
The following e&ample illustrates how the wait) + and notify) + methods that are inherited
from Object can be used to control the e&ecution of a thread.
This e&ample is similar to the program in the previous section. 5owever* the deprecated
method calls have been removed. 0et us consider the operation of this program.
The 1ewThread class contains a boolean instance variable named suspend,lag* which is
used to control the e&ecution of the thread. It is initiali(ed to false by the constructor.
The run) + method contains a synchroni(ed statement block that checks suspend,lag. If
that variable is true* the wait) + method is invoked to suspend the e&ecution of the thread.
The mysuspend) + method sets suspend,lag to true. The myresume) + method sets
suspend,lag to false and invokes notify) + to wake up the thread. ,inally* the main) +
method has been modified to invoke the mysuspend) + and myresume) + methods.
.&ample%
AA 3uspending and resuming a thread for #ava 8
class 1ewThread implements Sunnable ;
3tring nameG AA name of thread
Thread tG
boolean suspend,lagG
1ewThread)3tring threadname+ ;
name H threadnameG
t H new Thread)this* name+G
3ystem.out.println)L1ew thread% L F t+G
suspend,lag H falseG
t.start)+G AA 3tart the thread
=
AA This is the entry point for thread.
public void run)+ ;
try ;
for)int i H 7MG i X KG i''+ ;
3ystem.out.println)name F L% L F i+G
Thread.sleep)8KK+G
Page $( of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
synchroni(ed)this+ ;
while)suspend,lag+ ;
wait)+G
=
=
=
= catch )Interrupted.&ception e+ ;
3ystem.out.println)name F L interrupted.L+G
=
3ystem.out.println)name F L e&iting.L+G
=
void mysuspend)+ ;
suspend,lag H trueG
=
synchroni(ed void myresume)+ ;
suspend,lag H falseG
notify)+G
=
=
class 3uspendSesume ;
public static void main)3tring args9:+ ;
1ewThread ob7 H new 1ewThread)LOneL+G
1ewThread ob8 H new 1ewThread)LTwoL+G
try ;
Thread.sleep)7KKK+G
ob7.mysuspend)+G
3ystem.out.println)L3uspending thread OneL+G
Thread.sleep)7KKK+G
ob7.myresume)+G
3ystem.out.println)LSesuming thread OneL+G
ob8.mysuspend)+G
3ystem.out.println)L3uspending thread TwoL+G
Thread.sleep)7KKK+G
ob8.myresume)+G
3ystem.out.println)LSesuming thread TwoL+G
= catch )Interrupted.&ception e+ ;
3ystem.out.println)L?ain thread InterruptedL+G
=
AA wait for threads to finish
try ;
3ystem.out.println)L4aiting for threads to finish.L+G
ob7.t.join)+G
ob8.t.join)+G
= catch )Interrupted.&ception e+ ;
Page $ of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
3ystem.out.println)L?ain thread InterruptedL+G
=
3ystem.out.println)L?ain thread e&iting.L+G
=
=
5ere is the output produced by the above program%
1ew thread% Thread9One*M*main:
One% 7M
1ew thread% Thread9Two*M*main:
Two% 7M
One% 7I
Two% 7I
One% 7C
Two% 7C
One% 78
Two% 78
One% 77
Two% 77
3uspending thread One
Two% 7K
Two% O
Two% Q
Two% J
Two% N
Sesuming thread One
3uspending thread Two
One% 7K
One% O
One% Q
One% J
One% N
Sesuming thread Two
4aiting for threads to finish.
Two% M
One% M
Two% I
One% I
Two% C
One% C
Two% 8
One% 8
Two% 7
One% 7
Two e&iting.
Page $2 of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
One e&iting.
?ain thread e&iting.
sing is"live)+ and join)+%
Typically* the main thread is the last thread to finish in a program. 5owever* there isn6t
any guarantee that the main thread won6t finish before a child thread finishes. In the
previous e&ample* we told the main method to sleep until the child threads terminate.
5owever* we estimated the time it takes for the child threads to complete processing. If
our estimate was too short* a child thread could terminate after the main thread
terminates. Therefore* the sleep techni-ue isn6t the best one to use to guarantee that the
main thread terminates last.
Programmers use two other techni-ues to ensure that the main thread is the last thread to
terminate. These techni-ues involve calling the is"live)+ method and the join)+ method.
/oth of these methods are defined in the Thread class.
The is"live)+ method determines whether a thread is still running. If it is* the is"live)+
method returns a /oolean true valueG otherwise* a /oolean false is returned. Rou can use
the is"live)+ method to e&amine whether a child thread continues to run. The join)+
method works differently than the is"live)+ method. The join)+ method waits until the
child thread terminates and Yjoins the main thread. In addition* you can use the join)+
method to specify the amount of time you want to wait for a child thread to terminate.
The following e&ample illustrates how to use the is"live)+ method and the join)+ method
in your program. This e&ample is nearly the same as the previous e&ample. The
difference lies in the main)+ method of the Demo class definition.
"fter the threads are declared using the constructor of the ?yThread class* the is"live)+
method is called for each thread. The value returned by the is"live)+ method is then
displayed on the screen. 1e&t* the join)+ method is called for each thread. The join)+
method causes the main thread to wait for all child threads to complete processing before
the main thread terminates.
class ?yThread implements Sunnable ;
3tring t1ameG
Thread tG
?yThread )3tring thread1ame+ ;
t1ame H thread1ameG
t H new Thread )this* t1ame+G
t.start)+G
=
public void run)+ ;
try ;
3ystem.out.println)LThread% L F t1ame +G
Thread.sleep)8KKK+G
= catch )Interrupted.&ception e + ;
3ystem.out.println)L.&ception% Thread L
F t1ame F L interruptedL+G
Page $# of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
=
3ystem.out.println)LTerminating thread% L F t1ame +G
=
=
class Demo ;
public static void main )3tring args 9:+ ;
?yThread thread7 H new ?yThread )L7L+G
?yThread thread8 H new ?yThread )L8L+G
?yThread threadC H new ?yThread )LCL+G
?yThread threadI H new ?yThread )LIL+G
3ystem.out.println)LThread 3tatus% "liveL+G
3ystem.out.println)LThread 7% L
F thread7.t.is"live)++G
3ystem.out.println)LThread 8% L
F thread8.t.is"live)++G
3ystem.out.println)LThread C% L
F threadC.t.is"live)++G
3ystem.out.println)LThread I% L
F threadI.t.is"live)++G
try ;
3ystem.out.println)LThreads #oining.L+G
thread7.t.join)+G
thread8.t.join)+G
threadC.t.join)+G
threadI.t.join)+G
= catch )Interrupted.&ception e+ ;
3ystem.out.println)
L.&ception% Thread main interrupted.L+G
=
3ystem.out.println)LThread 3tatus% "liveL+G
3ystem.out.println)LThread 7% L
F thread7.t.is"live)++G
3ystem.out.println)LThread 8% L
F thread8.t.is"live)++G
3ystem.out.println)LThread C% L
F threadC.t.is"live)++G
3ystem.out.println)LThread I% L
F threadI.t.is"live)++G
3ystem.out.println)
LTerminating thread% main thread.L+G
=
=
Page $$ of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
5ere is what is displayed on the screen when this program runs%
Thread 3tatus% "live
Thread 7% true
Thread 8% true
Thread C% true
Thread I% true
Threads #oining.
Thread% 7
Thread% 8
Thread% C
Thread% I
Terminating thread% 7
Terminating thread% 8
Terminating thread% C
Terminating thread% I
Thread 3tatus% "live
Thread 7% false
Thread 8% false
Thread C% false
Thread I% false
Terminating thread% main thread.
Thread Pools%
?ost of the e&ecutor implementations in java.util.concurrent use thread +ools* which
consist of worAer threads. This kind of thread e&ists separately from the Sunnable and
$allable tasks it e&ecutes and is often used to e&ecute multiple tasks.
sing worker threads minimi(es the overhead due to thread creation. Thread objects use
a significant amount of memory* and in a large'scale application* allocating and
deallocating many thread objects creates a significant memory management overhead.
One common type of thread pool is the fi6ed thread +ool. This type of pool always has a
specified number of threads runningG if a thread is somehow terminated while it is still in
use* it is automatically replaced with a new thread. Tasks are submitted to the pool via an
internal -ueue* which holds e&tra tasks whenever there are more active tasks than threads.
"n important advantage of the fi&ed thread pool is that applications using it degrade
gracefully. To understand this* consider a web server application where each 5TTP
re-uest is handled by a separate thread. If the application simply creates a new thread for
every new 5TTP re-uest* and the system receives more re-uests than it can handle
immediately* the application will suddenly stop responding to all re-uests when the
overhead of all those threads e&ceed the capacity of the system. 4ith a limit on the
number of the threads that can be created* the application will not be servicing 5TTP
re-uests as -uickly as they come in* but it will be servicing them as -uickly as the system
can sustain.
Page $! of !"
G
www.csetube.in
$allables%
$allables are a tweak to the e&isting runnable construct. $allables differ only by having a
generic return type ' most speciali(ed concurrency "PIs already available )such as
, o & t ro t + already have the concept of a runnable F return type )such as the fo&trot Task
and #ob classes+. 3ome of you may already have noticed that the .&ecutor3ervice "PI is
biased to $allable objects ' and some may consider that a problem since they have a lot
of code that already works with Sunnable .
public class $omple&$alculation implements $allableW0ongX ;
public $omple&$alculation)int value7* int value8* long valueC+ ;
AA ...
=
public 0ong call)+ ;
AA perform comple& calculation resulting in long
long result H AA...
return resultG AA autobo&ing^
=
=
java.util.concurrent
Interface $allableW>X
Type Parameters%
> ' the result type of method call
Page $% of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
public interface $allableW>X
" task that returns a result and may throw an e&ception. Implementors define a single
method with no arguments called call.
The $allable interface is similar to Sunn a ble * in that both are designed for classes whose
instances are potentially e&ecuted by another thread. " Sunnable* however* does not
return a result and cannot throw a checked e&ception.
.&ecutors%
There2s a close connection between the task being done by a new thread* as defined by its
Sunnable object* and the thread itself* as defined by a Thread object. This works well for
small applications* but in large'scale applications* it makes sense to separate thread
management and creation from the rest of the application. Objects that encapsulate these
functions are known as e6ecutors.
The .&ecutors class contains utility methods to convert from other common forms to
$allable classes.
> ca ll)+
$omputes a result* or throws an e&ception if unable to do so.
.&ample%
import java.util.concurrent.$ountDown0atchG
import java.util.concurrent..&ecutor3erviceG
import java.util.concurrent..&ecutorsG
class 3imp.&ec ;
public static void main)3tring args9:+ ;
$ountDown0atch cdl H new $ountDown0atch)M+G
$ountDown0atch cdl8 H new $ountDown0atch)M+G
$ountDown0atch cdlC H new $ountDown0atch)M+G
$ountDown0atch cdlI H new $ountDown0atch)M+G
.&ecutor3ervice es H .&ecutors.new,i&edThreadPool)8+G
es.e&ecute)new ?yThread)cdl* L"L++G
es.e&ecute)new ?yThread)cdl8* L/L++G
es.e&ecute)new ?yThread)cdlC* L$L++G
es.e&ecute)new ?yThread)cdlI* LDL++G
try ;
cdl.await)+G
cdl8.await)+G
cdlC.await)+G
Page $& of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
cdlI.await)+G
= catch )Interrupted.&ception e&c+ ;
3ystem.out.println)e&c+G
=
es.shutdown)+G
=
=
class ?yThread implements Sunnable ;
3tring nameG
$ountDown0atch latchG
?yThread)$ountDown0atch c* 3tring n+ ;
latch H cG
name H nG
new Thread)this+G
=
public void run)+ ;
for )int i H KG i W MG iFF+ ;
latch.countDown)+G
=
=
=
3ynchroni(ers%
#ava M introduces general purpose synchroni(er classes* including semaphores* mute&es*
barriers* latches* and e&changers* which facilitate coordination between threads. These
classes are a apart of the java.util.concurrent package. " brief description of each of these
follows%
3emaphores
" counting semaphore maintains a set of permits. .ach ac-uire)+ blocks if
necessary until a permit is available* and then takes it. .ach release)+ adds a permit*
potentially releasing a blocking ac-uirer. 5owever* no actual permit objects are usedG the
3emaphore just keeps a count of the number available and acts accordingly.
Page $" of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
3emaphores are often used to restrict the number of threads than can access some
)physical or logical+ resource.
.&ample%
import java.util.concurrent.3emaphoreG
import java.util.SandomG
AA3olving the mutual e&clusion problem using 3emaphore class
class Process8 e&tends Thread
;
private static final Sandom rand H new Sandom)+G
private int idG
private 3emaphore semG
public Process8)int i* 3emaphore s+
;
id H iG
sem H sG
=
private void busy)+
;
try
;
sleep)rand.ne&tInt)MKK++G
= catch )Interrupted.&ception e+
;
=
=
private void noncritical)+
;
3ystem.out.println)LThread L F id F L is 1O1 criticalL+G
busy)+G
=
private void critical)+
;
3ystem.out.println)LThread L F id F L entering critical sectionL+G
busy)+G
3ystem.out.println)LThread L F id F L leaving critical sectionL+G
Page $' of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
=
public void run)+
;
for )int i H KG i W 8G FFi+
;
noncritical)+G
try
;
sem.ac-uire)+G
= catch )Interrupted.&ception e+
;
AA ...
=
critical)+G
sem.release)+G
=
=
public static void main)3tring9: args+
;
final int 1 H IG
3ystem.out.println)L/usy waiting...L+G
AA3emaphore)int permits* boolean fair+
3emaphore sem H new 3emaphore)1* true+G
Process89: p H new Process891:G
for )int i H KG i W 1G iFF+
;
p9i: H new Process8)i* sem+G
p9i:.start)+G
=
=
=
/arrier
" synchroni(ation aid that allows a set of threads to all wait for each other to
reach a common barrier point. $yclic/arriers are useful in programs involving a fi&ed
si(ed group of threads that must occasionally wait for each other. The barrier is called
cyclic because it can be re'used after the waiting threads are released.
Page !( of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
,or the java.util.concurrent class see $yclic/arr ier
" barrier is a type of synchroni(ation method. " barrier for a group of threads or
processes in the source code means any threadAprocess must stop at this point and cannot
proceed until all other threadsAprocesses reach this barrier.97:
The basic #ava synchroni(ation mechanism centers on the keyword synchr o ni(ed * which
predicates methods. In java* all objects can be used like monitors )protected types+.
That means that given an object "* no more than one thread can e&ecute a synchroni(ed
method of " at any time.
/arrier implementation
AB
B Piven object "* no more than one thread can e&ecute a synchroni(ed
method of " at any time.
BA
public class /arrier
;
public synchroni(ed void block)+ throws Interrupted.&ception
;
wait)+G
=
public synchroni(ed void release)+ throws Interrupted.&ception
;
notify)+G
=
public synchroni(ed void release"ll)+ throws Interrupted.&ception
;
notify"ll)+G
=
=
"nd an e&ample with two threads.
class /arrier.&ample
;
static class ?yThread7 implements Sunnable
;
public ?yThread7)/arrier barrier+
;
this.barrier H barrierG
=
Page ! of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
public void run)+
;
try
;
Thread.sleep)7KKK+G
3ystem.out.println)L?yThread7 waiting on barrierL+G
barrier.block)+G
3ystem.out.println)L?yThread7 has been releasedL+G
= catch )Interrupted.&ception ie+
;
3ystem.out.println)ie+G
=
=
private /arrier barrierG
=
static class ?yThread8 implements Sunnable
;
/arrier barrierG
public ?yThread8)/arrier barrier+
;
this.barrier H barrierG
=
public void run)+
;
try
;
Thread.sleep)CKKK+G
3ystem.out.println)L?yThread8 releasing blocked threads`nL+G
barrier.release)+G
3ystem.out.println)L?yThread7 releasing blocked threads`nL+G
= catch )Interrupted.&ception ie+
;
3ystem.out.println)ie+G
=
=
=
public static void main)3tring9: args+ throws Interrupted.&ception
;
/arrier /S H new /arrier)+G
Page !2 of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
Thread t7 H new Thread)new /arrier.&ample.?yThread7)/S++G
Thread t8 H new Thread)new /arrier.&ample.?yThread8)/S++G
t7.start)+G
t8.start)+G
t7.join)+G
t8.join)+G
=
=
.&changers
" synchroni(ation point at which two threads can e&change objects. .ach thread
presents some object on entry to the e&change method* and receives the object presented
by the other thread on return.
.&ample%
import java.util.concurrent..&changerG
class .&grDemo ;
public static void main)3tring args9:+ ;
.&changerW3tringX e&gr H new .&changerW3tringX)+G
new se3tring)e&gr+G
new ?ake3tring)e&gr+G
=
=
class ?ake3tring implements Sunnable ;
.&changerW3tringX e&G
3tring strG
?ake3tring).&changerW3tringX c+ ;
e& H cG
str H new 3tring)+G
new Thread)this+.start)+G
=
public void run)+ ;
char ch H 2"2G
Page !# of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
for )int i H KG i W CG iFF+ ;
for )int j H KG j W MG jFF+
str FH )char+ chFFG
try ;
str H e&.e&change)str+G
= catch )Interrupted.&ception e&c+ ;
3ystem.out.println)e&c+G
=
=
=
=
class se3tring implements Sunnable ;
.&changerW3tringX e&G
3tring strG
se3tring).&changerW3tringX c+ ;
e& H cG
new Thread)this+.start)+G
=
public void run)+ ;
for )int i H KG i W CG iFF+ ;
try ;
str H e&.e&change)new 3tring)++G
3ystem.out.println)LPot% L F str+G
= catch )Interrupted.&ception e&c+ ;
3ystem.out.println)e&c+G
=
=
=
=
0atches
" synchroni(ation aid that allows one or more threads to wait until a set of
operations being performed in other threads completes. " $ountDown0atch is initiali(ed
with a given count. The await methods block until the current count reaches (ero due to
Page !$ of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
invocations of the countDown)+ method* after which all waiting threads are released and
any subse-uent invocations of await return immediately.
0atching variables specify conditions that once set never change. This provides a way to
start several threads and have them wait until a signal is received from a coordinating
thread. 97:
The following program creates a set of threads* but doesn2t let any thread start until all the
threads are created.
import java.util.concurrent.BG
public class 0atchTest
;
private static final int $O1T H 7KG
private static class 4orker implements Sunnable
;
$ountDown0atch start0atchG
$ountDown0atch stop0atchG
3tring nameG
4orker)$ountDown0atch start0atch* $ountDown0atch stop0atch* 3tring name+
;
this.start0atch H start0atchG
this.stop0atch H stop0atchG
this.name H nameG
=
public void run)+
;
try
;
start0atch.await)+G AA wait until the latch has counted down to
AA (ero
= catch )Interrupted.&ception e&+
;
e&.print3tackTrace)+G
=
3ystem.out.println)LSunning% L F name+G
stop0atch.countDown)+G
=
=
Page !! of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
public static void main)3tring args9:+
;
AA $ountDown0atch)int count+
AA $onstructs a $ountDown0atch initiali(ed with the given count.
$ountDown0atch start3ignal H new $ountDown0atch)7+G
$ountDown0atch stop3ignal H new $ountDown0atch)$O1T+G
for )int i H KG i W $O1TG iFF+
;
new Thread)new 4orker)start3ignal* stop3ignal* Integer.to3tring)i+++
.start)+G
=
3ystem.out.println)LPoL+G
start3ignal.countDown)+G
try
;
stop3ignal.await)+G
= catch )Interrupted.&ception e&+
;
e&.print3tackTrace)+G
=
3ystem.out.println)LDoneL+G
=
=
Thread and event driven programming%
The single'thread rule%
5ere2s the rule%
Once a 9wing com+onent has been realized1 all code that might affect or de+end on the
state of that com+onent should be e6ecuted in the e.ent5dis+atching thread/
This rule might sound scary* but for many simple programs* you don2t have to worry
about threads. /efore we go into detail about how to write 3wing code* let2s define two
terms% realized and e.ent5dis+atching thread.
Healized means that the component2s paint)+ method has been or might be called. "
3wing component that2s a top'level window is reali(ed by having one of these methods
invoked on it% set>isible)true+* show)+* or )this might surprise you+ pack)+. Once a
window is reali(ed* all components that it contains are reali(ed. "nother way to reali(e a
component is to add it to a container that2s already reali(ed. Rou2ll see e&amples of
reali(ing components later.
The e.ent5dis+atching thread is the thread that e&ecutes drawing and event'handling
code. ,or e&ample* the paint)+ and actionPerformed)+ methods are automatically e&ecuted
Page !% of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
in the event'dispatching thread. "nother way to e&ecute code in the event'dispatching
thread is to use the 3wingtilities invoke0ater)+ method.
.&ample%
import java.awt.,low0ayoutG
import java.lang.reflect.InvocationTarget.&ceptionG
import java&.swing.#,rameG
import java&.swing.#0abelG
import java&.swing.#PanelG
import java&.swing.3wingtilitiesG
public class Invoke"nd4aitDemo e&tends Object ;
private static void print)3tring msg+ ;
3tring name H Thread.currentThread)+.get1ame)+G
3ystem.out.println)name F L% L F msg+G
=
public static void main)3tring9: args+ ;
final #0abel label H new #0abel)L''''''''L+G
#Panel panel H new #Panel)new ,low0ayout)++G
panel.add)label+G
#,rame f H new #,rame)LInvoke"nd4aitDemoL+G
f.set$ontentPane)panel+G
f.set3i(e)CKK* 7KK+G
f.set>isible)true+G
try ;
print)Lsleeping for C secondsL+G
Thread.sleep)CKKK+G
print)Lcreating code block for event threadL+G
Sunnable setTe&tSun H new Sunnable)+ ;
public void run)+ ;
print)Labout to do setTe&t)+L+G
label.setTe&t)L1ew te&t^L+G
Page !& of !"
G
www.csetube.in
www.csetube.in
#*)+*AMM,-+ #A*A(,+MS
=
=G
print)Labout to invoke"nd4ait)+L+G
3wingtilities.invoke"nd4ait)setTe&tSun+G
print)Lback from invoke"nd4ait)+L+G
= catch )Interrupted.&ception i&+ ;
print)Linterrupted while waiting on invoke"nd4ait)+L+G
= catch )InvocationTarget.&ception &+ ;
print)Le&ception thrown from run)+L+G
=
=
=
Page !" of !"
G
www.csetube.in

Das könnte Ihnen auch gefallen