0% found this document useful (0 votes)
5 views

java(Oops)

The document outlines the curriculum for an Object-Oriented Programming course using Java, covering topics such as OOP concepts, classes, objects, methods, inheritance, interfaces, exception handling, multithreading, file management, GUI programming, and JDBC. It includes detailed explanations of class definitions, object creation, method syntax, and examples of code. Recommended textbooks for the course are also provided.

Uploaded by

sachintaba9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

java(Oops)

The document outlines the curriculum for an Object-Oriented Programming course using Java, covering topics such as OOP concepts, classes, objects, methods, inheritance, interfaces, exception handling, multithreading, file management, GUI programming, and JDBC. It includes detailed explanations of class definitions, object creation, method syntax, and examples of code. Recommended textbooks for the course are also provided.

Uploaded by

sachintaba9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

I

MTU-NEPIMPLEMENTATION
BCASecondYear
/II
ISEMESTER
Subj
ect
:Obj
ectOr
ient
edPr
ogr
ammi
ngUs
ingJava Cour
seCode:
BCA-
NEP-
301

Uni
t Cont
ent
s

I I
ntroductiontoOOPsandJava:Top- DownAppr oachandBot tom- UpAppr oach,
OOPsConcept s,Hist
or yofJava,Feat ur
esofJava,Byt eCode,JavaTechnol ogy
(JVM,JRE,JDK,JI T),Java Appl i
cations,CharacterSet,Identifi
ers,Comment s,
Keywor d,Pr i
mi t
ives and Non- Pri
mitives Dat
a Type,Type Conver sion i
n Java,
Oper at
ors,ScannerCl ass,Conditi
onalSt at
ements,LoopingSt atement s,Gar
bage
Collect
ion.
Array and St ri
ng: Ar ray Declarat
ion, Creati
on, Ini
ti
ali
zat
ion, Command- Li
ne
Argument s,Str
ing:Decl arat
ion,Pr
edefinedmethodsofSt r
ing

I
I Cl
asses,ObjectsandMet hods:Defini
ngClas s,Def i
ningObj ect,AddingVariabl
es,
Adding Methods,Cr eati
ng Object
s ,Access Pr otecti
on,Const r
uctors,Types of
Constr
uctor
s,t hi
s& st at
ic keyword,Inheri
tance:Def ini
ng Inheri
tance,Typesof
I
nherit
ance,Creating Si
ngle,Multi
l
eveland Mul ti
pleI nheri
tance,superkeywor d,
MethodOver l
oading&Over ridi
ng,f
inalkeywor d,AbstractClass.
I
II I
nterfaces and Packages: Def i
ning I nt
er f
aces, Ext ending and I mpl ement i
ng
I
nterfaces,Def ini
ngPackages ,I mpor ti
ngPackages,Pr edef i
nedandUser -
defined
Packages,subpackage.
Exception Handl ing:Int r
oduction ofExcept i
on,Except i
on Types,Mul t
iple Catch
Clauses,Nest edTr yStat ements ,Thr ow,Thr ows,Fi nall
y,Java’ sBuil
t-i
nExcept i
ons .
Multi
threadedPr ogrammi ng:Thr eadLi feCycl e,Creat i
ngThr eads,ThreadMet hods ,
ThreadPr iori
ty
V Managi
I ng I/O Files:Introducti
on,St r
eams,St r
eam Cl asses,FileCl ass,Cr eati
onof
Fi
les,Readi ngandWr i
tingtoFile,Buf f
eringFiles,Random AccessFi les.
GUIPr ogrammi ng:GUIComponent s,AWTI ntroduction,Di f
ferencebet weenAWTand
Swing,
Swing:I ntr
oduct i
on,Feat ur
esofSwi ng,Swi ngHi erarchy,Swi ngComponent ,Event
Handl i
ng.
V Introduct i
ont oAppl etPr ogrammi ng:I ntr
oduct iont oAppl et,AppletAr chitecture,
AppletLifeCycl e,Appl etClass,Appl etMet hods ,Runningt heAppl et.
JDBC:Accessi ngDat abaseswi t
hJavaDat abaseConnect i
vit
y

TextBooks:
Patri
ckNaught onandHerber
tzSchi
l
dt,“
Java-2TheCompleteRef
erence”,McGrawHill
.
IvorHor t
on,“Begi
nni
ngJava-
2”,Wil
eyPubli
shi
ng.
E-Bal aguruswamy,“
Progr
ammingwithJava:APri
mer”
,TataMcGrawHi l
lEducat
ion.
UNI
T-I
ICLASSANDI
NHERI
TANCE

CLASS
A cl
assisauserdef i
nedbl ueprintorpr ototypef r
om whi chobj ectsar ecr eated.I
ngener al,class
decl
arati
onscani ncludet hesecomponent s,inorder:
1. Modifier s:Aclasscanbepubl i
corhasdef aultaccess.
2.Cl assname:Thenameshoul dbegi nwi t
hani ni
ti
al l
ett
er(capitali
zedbyconvent i
on).
3.Super class( i
fany) :Thenameoft heclass’sparent( super
cl ass)
,ifany,precededbyt he
keywor dext ends .Acl asscanonl yext end(subclass)onepar ent.
4.Interfaces( i
fany) :Acomma- separ atedli
stofinterfacesimpl ement edbythecl ass,ifany,
precededbyt hekeywor di mpl
ement s.Aclasscani mplementmor et hanoneint
erface.
5.Body:Thecl assbodysur roundedbybr aces,{}.

Thenewoper
atori
nst
ant
iat
esaclassbyal
locat
ingmemoryforanewobj
ectandr
etur
ningar
efer
ence
tot
hatmemor
y.Thenewoperat
oralsoi
nvokesthecl
assconst
ruct
or.

Defi
neaClasswi thvar i
ableandmet hods
Whenyoudef i
neacl ass,thenitmeansyouar especif
yingtwopar t
s:
 Vari
abledecl arati
on
 MethodDef ini
ti
on
Var
iabl
edeclarationmeanst odeclarevar i
ablesandtheirtypes.
MethodDefi
nit
ionmeanst ospecifythecodet hatwil
loperateonthatdat
a.
cl
asscl
ass_name
{
typevar1;
typevar2;
……………
Typen;
typemet hod_name( )
{
BodyofMet hod;
}
}
CreateaCl assandaddVar i
able/Methodincl
ass
ASimpleObjectConsi derthissimpleclassdef ini
ti
on:
cl
assT
{
privateStri
ngmsg=" Wow! ";
publ i
cvoidpr i
ntMsg( )
{
Syst
em. out.pri
ntl
n(msg);
}
publi
cstat i
cvoidmai n(Stri
ng[ ]args)
{
Tt est=newT( );
test.pri
ntMsg();
}
}
Aclasspr
ovidesapat
ter
nthatyoucanusetocreat
eoneormor eobject
s.Thei
temsthatmakeupt
he
cl
assareknownasmember s.Membersareaccessi
blebyonl
ycert
ainpart
sofyourprogr
am.

OBJECT
Anobjectconsi stsof :
 St ate:Iti
sr epresentedbyat t
ri
butesofanobj ect.Italsor efl
ect
sthepr opert
iesofanobject
.
 Behavi or:Itisrepresentedbymet hodsofanobj ect .Italsoref
lectstheresponseofanobj ect
withotherobj ects.
 Ident i
ty:Itgivesauni quenamet oanobjectandenabl esoneobj ecttointer
actwithot
herobjects.
I
nJava,anobj ecti screat
edf rom aclass.Wehaveal readycr eatedtheclassnamedFi rst
,sonowwe
canuset hi
st ocr eateobjects.TocreateanobjectofFi rst,speci f
ytheclassname,f ol
l
owedbyt he
obj
ectname,anduset hekeywor dnew:
cl
assFirst
{
i
ntx=5;

publ
i
cstat
icvoi
dmain(St
ri
ng[]ar
gs )
{
Fir
stmyObj=newFi r
st()
;
System.
out
.pri
ntl
n(myObj.
x);
}
}

Multi
pleObjects
Youcancr eatemul t
ipl
eobjectsofoneclass:
Example
Creat
et woobjectsofFirst
:
cl
assFirst
{
intx=5;
publi
cstati
cvoidmai n(Str
ing[
]args)
{
Fi
rstmyObj 1=newFi r
st(
);//Obj
ect1
Fi
rstmyObj 2=newFi r
st(
);//Obj
ect2
System.out.
print
ln(
myObj1.x)
;
System.out.
print
ln(
myObj2.x)
;
}
}
Exampl
e:
cl
assFi
rst
{
i
ntx=5;
voi
ddi spl ay()
{
Syst em.out.
print
ln(
"ValueofXis:
"+x)
;
}
}
cl
assT
{
pri
vateSt ri
ngmsg=" Wow! ";
publi
cvoi dpr i
ntMsg()
{
Syst em.out.
print
ln(
msg) ;
}
publi
cst at i
cvoidmai n(Str
ing[]args
)
{
Firstf=newFi r
st()
;
f.displ
ay();
Tt est=newT( );
tes t
.pri
ntMsg();

}
}

METHOD
AJavamet hodisacol
l
ecti
onofst at
ementsthatar
egroupedtoget
hertoperf
orm anoperat
ion.When
youcal
ltheSystem.
out
.pri
ntl
n()method,f
orexample,t
hesyst
em actual
l
yexecut
esseverals
tatement
s
i
nordert
odi spl
ayamessageont heconsol
e.

Cr
eat
ingMet
hod

Synt
ax
modif
ierr
etur
nTypenameOf
Met
hod(
Par
amet
erLi
st)
{
//methodbody
}

Thesyntaxshownabovei ncl
udes−
modifi
er−Itdefinestheaccesst ypeofthemethodandi ti
sopti
onal
touse.
ret
urnType−Met hodmayr eturnavalue.
nameOf Method−Thi sisthemet hodname.
ParameterList−Thel i
stofparameters,i
tist
hetype,or
der,andnumberofparamet
ersofamet
hod.
Theseareopt i
onal,methodmaycont ainzeroparameters.
methodbody−Themet hodbodydefineswhatthemet hoddoeswit
hthest
atement
s.

Exampl
e
Herei
sthesour
cecodeoftheabovedef
inedmet
hodcal
l
edmax(
).Thi
smet
hodt
akest
wopar
amet
ers
num1andnum2andr et
urnst
hemaximum bet
weent
hetwo−

publ
i
cintmi
nFunct
ion(
intn1
,intn2)
{
intmin;
if(n1>n2)
min=n2;
else
min=n1;

ret
urnmi
n;
}

Met hodCal l
ing
Ther ear et wowaysi nwhi chamet hodi scal
ledi.
e.,methodret
urnsaval
ueorr et
urningnot hi
ng(no
returnval ue) .
Thepr ocessofmet hodcal l
i
ngi ssimpl e.Whenapr ogram i
nvokesamethod,theprogr am contr
olgets
transfer redt othecall
edmet hod.Thiscal l
edmet hodthenret
urnscont
rolt
othecallerintwocondi t
ions
,
when–
 t her eturnstat
ementi sexecut ed.
 i tr eachest hemet hodendi ngcl osi
ngbrace.
Followi ngi stheexampl et odemonst ratehowtodef i
neamet hodandhowt ocall
it−
publ i
ccl assExampl eMi nNumber
{
publicst aticvoidmai n(St r
ing[]args )
{
ExampleMi nNumbere=newExampl eMinNumber (
);
i
nta=1 1 ;
i
ntb=6;
i
ntc=e. mi nFunct i
on(a,b) ;
Syst
em. out.print
ln("
Mi nimum Value="+c) ;
}
/ *r eturnsthemi nimum oft wonumber s*/
publ icintminFunct i
on(intn1,intn2)
{
i
ntmin;
i
f(n1>n2)
min=n2;
el
se
min=n1 ;

r
etur
nmi
n;
}
}
Thi
swi
l
lpr
oducet
hef
oll
owi
ngr
esul
t− Mi
nimum val
ue=6

Passi
ngParameter
sbyVal
ue
Passi
ngParameter
sbyVal
uemeanscal
l
ingamet
hodwi
thapar
amet
er.Thr
ought
his,t
hear
gument
val
ueispassedt
othepar
ameter
.

Example
publ
iccl
assswappi
ngExampl
e
{
publi
cst
ati
cvoi
dmain(St
ri
ng[
]ar
gs)
{
i
nta=30;
i
ntb=45;
Syst
em.
out
.pr
int
ln(
"Bef
oreswappi
ng,a="+a+"andb="+b)
;

//I
nvoketheswapmet hod
swapFuncti
on(
a,b);
Syst
em.out.
pri
ntl
n("
\n*
* Now,Befor
eandAf
terswappi
ngval
ueswi
l
lbesameher
e**
:")
;
Syst
em.out.
pri
ntl
n("
Aft
erswapping,a="+a+"andbi s"+b);
}
publ
i
cvoidswapFuncti
on(i
nta,i
ntb)
{
Syst
em.out
.pr
intl
n("
Befor
eswappi
ng(
Insi
de)
,a="+a+"b="+b)
;

//Swapn1withn2
i
ntc=a;
a=b;
b=c;
Syst
em.out
.pr
int
ln(
"Af
terswappi
ng(
Insi
de)
,a="+a+"b="+b)
;
}
}
Out
put
Befor
eswapping,a=30andb=45
Befor
eswapping(Insi
de),a=30b=45
Aft
erswappi
ng(Inside)
,a=45b=30
ACCESSPROTECTI
ON

Acces
slevel
modi
fi
ersdet
ermi
newhet
herot
hercl
assescanuseapar
ti
cul
arf
iel
dori
nvokeapar
ti
cul
armet
hod.

Atthememberl evel
,youcanal souset hepublicmodifi
erornomodif i
er(package-
pr i
vat
e)justaswit
h
t
op- l
evelclasses,and wi t
ht he same meani ng.Formember s,there aretwo additi
onalaccess
modifi
ers:pri
vateandpr ot
ected.Thepr ivat
emodi fi
erspeci
fi
esthatt
hemembercanonl ybeaccessed
i
nitsowncl ass.Theprotect
edmodi f
ierspecifi
esthatt
hemembercanonl ybeaccessedwi thi
nitsown
package( aswithpackage-pri
vate)and,i naddi
ti
on,byasubclassofi
tsclassinanotherpackage.

Modi
fi
er Cl
ass Package Subcl
ass
publ
i
c Y Y Y
prot
ect
ed Y Y Y
nomodif
ier Y Y N
pr
ivat
e Y N N

Thef i
rstdatacolumni ndi
cateswhet herthecl assit
selfhasaccesstot hememberdefinedbyt he
accesslevel.Asyoucansee,acl assalwayshasaccesst oi
tsownmember s.Thesecondcolumn
i
ndicateswhetherclassesinthesamepackageast hecl asshaveaccesstot
hemember .Thethi
rd
col
umni ndi
cateswhethersubclassesofthecl assdeclaredoutsi
dethi
spackagehaveaccesst othe
member .Thefourthcolumnindi
cateswhet herallcl
asseshaveaccesstothemember.

Nest
edCl
assesi
nJava

I
nj ava,itis possi bl
et o def ine a cl ass wi thi
n anot hercl ass,such cl asses ar e known
asnestedclasses.Theyenabl eyout ological
lygr oupcl assest hatareonlyusedi nonepl ace,
thust
hisi
ncreasest heuseofencapsul ati
on,andcr eatemor ereadabl eandmai ntainablecode.
 Thes copeofanest edcl assi sboundedbyt hescopeofi t
senclosingcl ass.Thusi n
aboveexampl e,cl assNest edClassdoesnotexi stindependent l assOut
yofcl erClass.
 An estedcl asshasaccesst othemember s,includingpr ivatemember s,oft heclassin
whichi tisnested.However ,reversei snott ruei .
e.t heencl osingcl
assdoesnothave
accesst othemember soft henest edcl ass.
 An est
edcl assisal soamemberofi tsencl osingcl ass.
 As a me mber of i ts encl osing cl ass, a nest ed cl ass can be
decl edpr
ar i
vate,publ i
c,pr otected,orpackagepr ivat
e(def aul
t).
 Nestedcl assesar edi videdi ntotwocat egor i
es:
1.st ati
c nest ed cl ass:Nest ed clas ses t hatar e decl edst
ar ati
car e cal l
ed st at
ic
nes t
edcl asses .
2.innercl ass:Ani nnercl assisanon- staticnest edclass.

Synt
ax:
cl
assOut
erCl
ass

{
..
. cl
assNest
edCl
ass

{ .
..}

}
CONSTRUCTORS
Aconst ruct
orini
ti
ali
zesanobj ectwheniti
screat
ed.I thasthesamenameasi t
sclassandis
syntacti
call
ysimi
lartoamet hod.However,constructorshavenoexpli
citretur
ntype.
Allcl
asseshaveconst ructors,whetheryoudefi
neoneornot ,becauseJavaaut omati
call
yprovi
desa
defaultconstr
uct
ort hati
niti
ali
zesallmembervariablestozero.However ,onceyoudef i
neyourown
constructor
,thedefaultconstructori
snolongerused.

Example
Her ei
sasimpleexamplet
hatusesaconst
ruct
orwi
thoutpar
amet
ers−
//Asimpleconst
ruct
or.
classMyClass
{
i
ntx;

/
/Fol
l
owingistheconst
ruct
or
MyCl
ass()
{
/
/x=1 0;
}
}
//
Youwil
lhavetocal lconstr
uctortoinit
ial
i
zeobj
ectsasf
oll
ows−
cl
assConsDemo
{
publi
cstati
cvoi dmain(Str
ingar gs[
])
{
MyCl asst1=newMyCl ass(
);
MyCl asst2=newMyCl ass(
);
System. out
.pr
int
ln(t
1.x+""+t 2.
x);
}
}
Output
1010
PARAMETERIZEDCONSTRUCTOR
Par
ameter
sareaddedtoaconstr
uctori
nthesamewaythatt
heyar
eaddedt
oamet
hod,j
ustdecl
are
t
hem i
nsi
dethepar
ent
hesesaf
tertheconst
ruct
or'
sname.

Example
Her ei
sasi
mpleexamplet
hatusesaconst
ruct
orwi
thapar
amet
er−
//Asimpl
econst
ruct
or.
classMyCl
ass
{
i
ntx;

//Fol
lowingistheconst r
uctor
MyClass (
inti)
{
x=i ;
}
}
//
Youwi l
lneedt ocallaconst ructortoinit
ial
izeobject
sasf
oll
ows−
publ
icclassCons Demo
{
publi
cstaticvoidmai n(Str
ingar gs[]
)
{
MyCl asst1=newMyCl ass(10) ;
MyClasst2=newMyCl ass(20) ;
System.out .
printl
n(t1
.x+""+t 2.
x);
}
}
Thi
swillproducethef oll
owingr esult−
Out put
1 020
SCANNERCLASS
Scanneri st he complementofFor matt
er.Added byJDK 5,Scannerr eads
formatt
edi nputandconver t
sitintoi t
sbinar
yfor
m.Al thoughithasalwaysbeen
possibl
et oreadf or
mattedinput,itrequi
redmoreef f
ortthanmostprogrammer s
wouldpr efer
.Becauseoft headdi ti
onofScanner,iti
snoweasyt oreadalltypes
ofnumer icvalues,st
ri
ngs,andot hertypesofdata,whetheritcomesfrom adisk
fi
le,t
hekeyboar d,oranothersource.

Thi
sispr
obabl
ythemostpr
efer
redmet
hodt
otakei
nput
.Themai
npur
poseoft
heScanner
cl
assist
oparsepr
imit
ivetypesandst
ri
ngsusi
ngr
egularexpr
essi
ons
;however
,iti
sal
socan
beusedtor
eadinputf
r om t
heuseri
nthecommandl
ine.

Ex:
//Javapr
ogr
am t
odemonst
rat
ewor
kingofScanneri
nJava

i
mportjava.ut
il
.Scanner ;
cl
assGet I
nputFromUser
{
publi
cstati
cvoi dmai n(St
ri
ngargs[
])
{
Scannerin=new Scanner (
System.in)
;//Usi
ngScannerf
orGet
ti
ngI
nput
fr
om User
Str
ings=i n.nextLine();
System.out.pri
ntln("Youent
eredstri
ng"+s) ;
i
nta=i n.nextI
nt();
System.out.pri
ntln("Youent
eredinteger"+a);
fl
oatb=i n.nextFloat()
;
System.out.pri
ntln("Youent
eredfloat"+b);

i
n.cl
ose(
); /
/cl
osi
ngscanner
}
}

Ex:Wr
it
eapr
ogr
am t
oinputt
hear
eaofasquar
eandf
indi
tsper
imet
er.

i
mportj
ava. ut
il
.*;
cl
assArea_Perimet er
{
publi
cstaticvoi dmai n(
Stri
ngargs[])
{
Scannersc=newScanner (Syst
em.in)
;
doubl ea,s,p;
System. out.pri
ntl
n(“
Entert
hear eaofasquar
e:”
);
a=sc. nextDouble()
;
s=Mat h.
sqrt(a)
;
p=4* s;
System. out.pri
ntl
n(“
Perimeter
=”+p);
}
}
STATI
CKEYWORD

Thest
ati
ckeywor
dinJavai
sused f
ormemor
ymanagementmai
nly.Wecan
appl
yst
ati
ckeywor
dwi
thvar
iabl
es,met
hods,bl
ocksandnest
edcl
ass
es.The
st
ati
ckeywor
dbel
ongst
othecl
asst
hanani
nst
anceoft
hecl
ass.
Thest
ati
ccanbe:
1
.Var
iabl
e(al
soknownasacl
assvar
iabl
e)
2.Met
hod(
alsoknownasacl
assmet
hod)
3.Bl
ock
st
ati
cvar
iabl
e
I
fyoudecl
areanyvar
iabl
easst
ati
c,i
tisknownasast
ati
cvar
iabl
e.
o Thest
ati
cvar
iabl
ecanbeusedt
oref
ert
othecommonpr
oper
tyofal
l
obj
ect
s(whi
chi
snotuni
quef
oreachobj
ect
),f
orexampl
e,t
hecompany
nameofempl
oyees,col
l
egenameofst
udent
s,et
c.
o Thest
ati
cvar
iabl
eget
smemor
yonl
yoncei
nthecl
assar
eaatt
het
imeof
cl
assl
oadi
ng.
Exampl
e:
cl
assCount er2
{
st
ati
ci ntcount=0;//
wi l
lgetmemor yonl
yonceandretai
nit
sval
ue
Counter 2(
)
{
count++;/
/incr
ement ingtheval
ueofst
ati
cvar
iable
System.out.pr
intl
n(count)
;
}
publ
i
cstati
cvoi dmai n(St
ringargs[])
{
//
creatingobjects
Counter 2c1=new Count er2(
);
Counter 2c2=new Count er2()
;
Count
er2c3=new Count
er2(
);
}
}

st
ati
cmet
hod
I
fyouapplystat
ickeywor
dwithanymet hod,i
tisknownasst
aticmethod.
o Astat
icmet hodbel
ongstothecl
assrathert
hantheobj
ectofaclass.
o Astati
cmet hodcanbeinvokedwi t
houttheneedforcreat
ingani nst
ance
ofaclass.
o Astati
cmet hodcanaccessstat
icdatamemberandcanchanget hevalue
ofi
t.
Exampl
e:1

cl
assMai n
{
stati
cinti=10;
publicstati
cvoi dmai n(St
ring[]args)
{
display()
;/ /calli
ngwi thoutobject
Mai nt=new Mai n(
);
t.
show( );/ /calli
ngusingobj ect
}
stati
cvoiddi splay()
{
System. out.printl
n("
Pr ogrammi ngisamazi
ng.")
;
System. out.printl
n("
Val ueofIis:.
"+i)
;
}
voidshow( )
{
Syst
em. out.pr
intl
n("Javaisawesome.")
;

}
}
Exampl
e:2
cl
assCalcul
ate
{
st
atici
ntcube(
intx)
{
ret
urnx*
x*x;
}
publ
i
cst
ati
cvoidmain(Stri
ngar gs[
])
{
intr
esul
t=Calculat
e.cube(5)
;
Syst
em.out.
pr i
ntl
n(r
esult
);
}
}

st
ati
cbl
ock

o I
susedt
oini
ti
ali
zet
hest
ati
cdat
amember
.
o I
tisexecut
edbef
oret
hemai
nmet
hodatt
het
imeofcl
assl
oadi
ng.

cl
assMai
n
{

st
ati
cinta=1 0;
st
ati
c
{
System.out
.pr
int
ln(
"Val
ueofai
s:"+a)
;

}
publ
i
cstat
icvoi
dmai
n(Str
ing[
]ar
gs)
{
/
/Mainobj1=newMain(
);
}
}

Example2:
cl
assMain
{
st
ati
cint[
]numAr ray=newi nt[1 0];
st
ati
c
{
Sys t
em.out.
print
ln("Runni ngst ati
cini
ti
ali
zat
ionblock.
");
for(i
nti=0;i <numAr ray.length;i++)
{
numArray[i]=( i
nt)( 100.0*Mat h.r
andom() )
;
}
}
voi
dprintArr
ay()
{
Sys t
em.out.
print
ln("Thei nit
ial
izedvaluesare:"
);
for(i
nti=0;i <numAr ray.length;i++)
{
Syst
em. out.pri
nt(numAr ray[
i]+"");
}
Syst
em.
out
.pr
int
ln(
);
}
publ
icstaticvoidmain(St
ri
ng[]args)
{
Mainobj 1=newMai n()
;
System. out
.pri
ntl
n("
Forobj1:
");
obj1.
printArr
ay()
;
Mainobj 2=newMai n()
;
System. out
.pri
ntl
n("
\nForobj2:
");
obj2.pr
intArr
ay();
}
}

THI
SKEYWORD
thi
sisakeywordinJavawhichisusedasar efer
encet
ot heobj
ectoft
hecurrentcl
ass,wi
thi
nan
i
nstancemethodoraconstruct
or.Usingthi
syoucanref
erthemember sofaclasssuchas
constr
uct
ors,var
iabl
esandmet hods.
Note−Thekeywor dthi
sisusedonlywithi
ninst
ancemethodsorconst
ruct
ors

AccessI
nst
anceVar
iabl
eUsi
ng‘
thi
s’
cl
assStudent
{
intage;
St
udent
(intage)
{
this.
age=age;
}
}
Accessconst
ruct
orUsi
ng‘
thi
s’
publ
iccl
assMain
{
i
ntage;
Main()
{
t
his(20)
;
System.out
.pr
int
ln(
"Youarei
ndef
aul
tconstr
uct
or:
"+age);
}
Main(i
ntage)
{
t
his.
age=age;
System.out
.pr
int
ln(
"Youarei
nPar
ameter
izedconst
ruct
or:
"+age)
;
}
publi
cstati
cvoidmain(Str
ing[
]ar
gs)
{
Mai
nM=newMai
n()
;
}
}
AccessMet
hodusi
ng‘
thi
s’
cl
assTest_thi
s
{
voidpri
nt()
{
/
/call
i
ngf ucti
onshow( )
t
his.
show( )
;
Syst
em. out.
pri
ntl
n("Test
_thi
s:
:pr
int"
);
}
voidshow( )
{
System.out
.pri
ntl
n("
Test
_thi
s::
show"
);
}
}

cl
assMai
n
{
publ
icstat
icvoidmain(
Str
ingar
gs[])
{
Test_thi
st1=newTest_t
his
();
t1
.print(
);
}
}

Exampl
e:1

cl
assThis_Example
{
//Inst
ancevari
ablenum
intnum =10;

Thi
s_Example()
{
System.out.
pri
ntl
n("
Thisisanexampl
epr
ogr
am onkeywor
dthi
s")
;
}
Thi
s_Example(i
ntnum)
{
//I
nvokingthedefaultconst
ruct
or
thi
s();

/
/Assigni
ngthel
ocal
var
iabl
enum t
othei
nst
ancevar
iabl
enum
t
his.
num =num;
}
publ
i
cvoidgreet
()
{
Syst
em.out.
pri
ntl
n("
HiWel
come.
");
}

publ
i
cvoidpr
int(
)
{
/
/Localvari
abl
enum
i
ntnum =20;

//Pri
nti
ngt
heinstancevar
iabl
e
Syst
em.out
.pr
int
ln("
val
ueoflocal
var
iabl
enum i
s:"
+num)
;

/
/Pri
nti
ngthelocalvari
abl
e
Syst
em.out.
pri
ntl
n("val
ueofi
nst
ancevar
iabl
enum i
s:"
+thi
s.num)
;

/
/Invoki
ngthegr
eetmet
hodofacl
ass
thi
s.gr
eet(
);
}

publ
i
cstat
icvoidmain(
Stri
ng[]ar
gs )
{
//I
nst
anti
ati
ngtheclass
Thi
s_Exampleobj1=newThi
s_Exampl
e()
;

//I
nvokingthepr
intmet
hod
obj
1.pr
int(
);

//Passi
nganewval
uet
othenum var
iablet
hroughpar
amet
ri
zedconst
ruct
or
Thi
s_Exampl
eobj
2=newThis
_Example(30)
;

//I
nvoki
ngt hepr
intmet
hodagai
n
obj
2.pri
nt(
);
}
}
Output
Thi
sisanexamplepr ogr
am onkeywor
dthi
s
val
ueoflocalvar
iabl
enum i
s:20
val
ueofinst
ancevariabl
enum i
s:10
HiWelcome
Thi
sisanexamplepr ogr
am onkeywor
dthi
s
val
ueoflocalvar
iabl
enum i
s:20
val
ueofinst
ancevariabl
enum i
s:30
I
NHERI
TANCE

I
nheritanceisoneoft hefeat
uresofObj ect-OrientedPr ogrammi ng(OOPs) .Inheri
tanceall
owsacl ass
touset heproperti
esandmet hodsofanot herclass.Inotherwor ds,t
heder ivedclassinher
itsthestates
andbehavi orsf
rom thebaseclass.Theder i
vedcl assisalsocalledsubclassandt hebasecl assisalso
knownassuper -cl
ass.Thederivedclasscanaddi t
sownaddi t
ionalvari
ablesandmet hods.These
addit
ionalvari
abl
eandmet hodsdiff
erentiatetheder ivedclassfrom thebasecl ass.

Thekeywor
dusedf
ori
nher
it
ancei
sext
ends
.

Synt
ax:
publ
icclassChil
dCl
assextendsBaseCl
ass{
//der
ivedclassmethodsextendandpossi
blyover
ri
de
}

Si
ngl
eInher
it
ance

Whenaclassext
endsanotheronecl
assonl
ythenwecall
itasi
ngl
einher
it
ance.Thebelowf
low
di
agr
am showsthatclassBext
endsonl
yoneclasswhi
chisA.Her
eAi saparentcl
assofBandB
woul
dbeachildclassofA.

Si
ngl
eInher
it
anceexampl
epr
ogr
am i
nJava

Cl
assA
{
publ
icvoi
dmethodA()
{
Sys
tem.out
.pr
int
ln(
"Basecl
assmet
hod"
);
}
}
Cl
assBextendsA
{
publ
icvoidmethodB()
{
Sys
tem.out.pr
int
ln(
"Chil
dclassmethod"
);
}
publ
icst
aticvoi
dmai n(St
ri
ngar gs
[])
{
Bobj=newB( );
obj
.methodA();/
/cal
li
ngsuperclassmethod
obj
.methodB();/
/cal
li
nglocalmethod
}
}

2)Mul
ti
pleI
nher
it
ances

“Mul
ti
pleInheri
tance”r
eferst
otheconceptofoneclassext
endi
ng(Orinher
it
s)morethanonebase
cl
ass.Theinherit
ancewelearntear
li
erhadtheconceptofonebasecl
assorparent
.Theprobl
em wit
h
“mul
ti
plei
nherit
ance”isthatt
hederivedcl
asswil
lhavetomanagethedependencyontwobaseclasses.

Note1:Mult
ipl
eInher
it
ancesisveryrar
elyusedins
oft
warepr
oject
s.Usi
ngMult
iplei
nheri
tanceoft
en
l
eadstoproblemsint
hehierarchy.Thi
sresul
tsi
nunwant
edcomplexi
tywhenf
urtherext
endingthe
cl
ass.

Not
e2:Mostofthenewobject
- or
ient
edl
anguages
;Java,C#doesnotsuppor
tMul
ti
pleI
nher
it
ances.
Mul
ti
pleI
nher
it
ancesissuppor
tedinC++.

3)Mul
ti
l
evel
Inher
it
ance

Mult
il
eveli
nheri
tancerefer
stoamechanism i
nOOt echnol
ogywhereonecani nher
itf
rom aderi
ved
cl
ass,t
herebymaki ngthi
sderivedcl
asst
hebasecl
assforthenewclass.Asyoucanseeinbelowfl
ow
di
agram Cissubclassorchil
dclassofBandBisachil
dclassofA.
Mul
ti
l
evelI
nher
it
anceexampl
epr
ogr
am i
nJava

ClassX
{
publ i
cvoi dmethodX( )
{
System.out.pr
intl
n("ClassXmet hod");
}
}
ClassYext endsX
{
publicvoidmet hodY()
{
System. out.
pri
ntl
n("classYmet hod"
);
}
}
ClassZext endsY
{
publ i
cvoi dmethodZ( )
{
System.out.pr
intl
n("cl
assZmet hod");
}
publ i
cstaticvoi
dmai n(Str
ingargs[])
{
Zobj =newZ( );
obj.
met hodX()
;//calli
nggr andparentclassmet
hod
obj.
met hodY()
;/ /
calli
ngpar entcl
assmet hod
obj.
met hodZ();//
calli
nglocal method
}
}

4)Hi
erar
chi
cal
Inher
it
ance

I
nsuchki
ndofi
nher
it
anceonecl
assi
sinher
it
edbymanysubcl
asses.I
nbel
owexampl
ecl
assB,Cand
Dinher
it
sthe

samecl
assA.Ai
spar
entcl
ass(
orbasecl
ass)ofB,C&D.

5)Hybr
idI
nher
it
ance

I
ns i
mpl et
ermsyoucansaythatHybri
dinheri
tanceisacombinat
ionofSi
ngleandMult
ipl
einher
it
ances.
Atypicalf
lowdiagr
am woul
dlookl
ikebelow.Byus i
ngint
erf
aces,youcanhavemult
ipl
easwellas
hybr
idinheri
tancei
nJava.
Feat
uresofI
nher
it
ance

 Privatemember soft hesuperclassarenoti nher


it
edbythesubcl
assandcanonl ybeindir
ectl
y
accessed.
 Member sthathavedef aul
taccessibi
l
ityinthesupercl
assareal
sonotinher
it
edbysubcl assesi
n
otherpackages,ast hesemember sareonlyaccessibl
ebythei
rsi
mplenamesi nsubclasses
withinthesamepackageast hesupercl ass.
 Sinceconst r
uctorsarenotmember sofacl ass,t
heyarenoti
nher
it
edbyasubcl ass.
 Asubcl asscanext endonlyonesupercl ass
 Javadoesnotsuppor tmul
ti
pleinheri
tances.
SUPERKEYWORD
-Wecanusesuperkeywor
dtoaccesst
hedat amemberorf
iel
dofpar
entcl
ass.I
tisusedi
f
par
entcl
assandchi
ldcl
asshavesamefi
elds.

classAnimal
{
Str
ingcolor="white";
}
classDogext endsAni mal
{
Str
ingcolor="black";
voi
dpr i
ntColor()
{
Syst
em. out.pr
intl
n(color)
;//
pr i
ntscolorofDogclass
Syst
em. out.pr
intl
n(super.color)
;//pr
int
scolorofAni
malcl
ass
}
}
classTestSuper1
{
publi
cstaticvoidmai n(Str
ingar gs[])
{
Dogd=new Dog( )
;
d.
printCol
or();
}
}
-superisusedt oinvokepar entclassconst ruct
or.

cl
assAni
mal
{
Ani
mal
()
{
Syst
em.
out
.pr
int
ln(
"ani
mali
scr
eat
ed"
);
}
}
cl
assDogextendsAni mal
{
Dog()
{
super(
);
Syst
em. out.
pri
ntl
n("
dogi
screated"
);
}
}
cl
assTest
Super3
{
publ
i
cstati
cvoi dmain(St
ri
ngar
gs[]
)
{
Dogd=new Dog( );
}}
-
supercanbeusedt
oinvokepar
entcl
assmet
hod
cl
assAnimal
{
voi
deat ()
{
System.out.pri
ntl
n("
eating...
");
}
}
cl
assDogext endsAni mal
{
voi
deat ()
{
System.out.pr
intl
n("eati
ngbread..
."
);
}
voi
dbar k()
{
System.out.pr
intl
n("barki
ng.
..
");
}
voi
dwor k()
{
super.eat
();
bark()
;
}
}
cl
assTestSuper2
{
publ
icstaticvoidmai n(St
ringar gs[]
)
{
Dogd=new Dog(
);
d.
work(
);
}
}

POLYMORPHI
SM
METHODOVERLOADI
NG

Whenacl asshastwoormor emet


hodsbythesamenamebutdi ff
erentpar
ameters,i
tisknownas
met
hodover l
oadi
ng.
I
nover
ri
ding,amet hodhast
hesamemethodname,t
ype,numberofparamet
ers,et
c.

Example:If,l
et’
ssaywewantt ofindt hemini
mum numberofdoubl
etypes.Thent
heconceptof
overl
oading wil
lbei ntr
oduced to createtwo ormor
emet hodswi
ththesamenamebutdi f
fer
ent
parameters.
Thefoll
owingexampl eexplainst
hesame−
Example
publi
cclassExampl eOverl
oading
{
publi
cstati
cvoidmai n(St
ri
ng[]args)
{
i
nta=1 1
; i
ntb=6;
doublec=7. 3; doubl
ed=9.4;
i
ntresult
1=mi nFuncti
on(a,b);

//samefuncti
onnamewi thdif
ferentpar
ameters
doubl
eresul
t2=mi nFunct
ion(
c,d);
Syst
em.out.
pri
ntl
n("
Minimum Value="+r esul
t1)
;
Syst
em.out.
pri
ntl
n("
Minimum Value="+r esul
t2)
;
}

//f
orinteger
publi
cstaticintminFunct
ion(
intn1
,intn2)
{
i
ntmi n;
i
f( n1>n2)
min=n2;
else
min=n1 ;
returnmin;
}
//f
ordouble
publi
cstat
icdoublemi
nFunct
ion(
doubl
en1
,doubl
en2)
{
doubl
emi n;
i
f(n1>n2)
min=n2;
el
se
min=n1;

r
etur
nmi
n;
}
}
Out
put
Mi
nimum Val
ue=6
Mi
nimum Val
ue=7.
3

METHODOVERRI
DING

Whenwedecl ar
et hesamemet hodinchi
ldcl
asswhichi
sal
readypresentint
heparentclasst
het hi
sis
cal
l
edmet hodoverri
ding.I
nthiscasewhenwecallt
hemethodfrom chil
dclassobject
,thechi
ldclass
ver
sionoft
hemet hodiscall
ed.Howeverwecancall
thepar
entcl
assmet hodusingsuperkeyword.

cl
assParent
Cl ass
{
//
Parentcl
assconst ructor
ParentClass()
{
System. out.pr
int
ln("ConstructorofParent"
);
}
voi
ddi sp()
{
System. out.pr
int
ln("ParentMet hod")
;
}
}
cl
assJavaExampl eext endsPar ent Cl
ass
{
JavaExampl e()
{
System. out.pr
int
ln("ConstructorofChil
d");
}
voiddisp()
{
System. out.pr
int
ln("Chi
ldMet hod");
/
/Calli
ngt hedisp()met hodofpar entclass
super.disp();
}
publi
cst ati
cvoi dmai n(Stri
ngar gs[])
{
//
Creat i
ngt heobjectofchi ldclass
JavaExampl eobj =newJavaExampl e();
obj.
disp( )
;
}
}
Not
e:pr
ivat
e,st
ati
candf
inal
met
hodscannotbeover
ri
ddenast
heyar
elocal
tot
hecl
ass.

FI
NALKEYWORD
Thef
inalkeywor
dinj
avai
susedt
orest
ri
ctt
heuser
.Fi
nal
canbe:
1.variabl
e
2.met hod
3.class

Fi
nalVari
able:
I
fyoumakeanyvar i
abl
easf i
nal,youcannotchanget
heval
ueoff
inalvar
iabl
e(I
twi
l
lbe
const
ant)
.
I
njava,anon-stat
icfi
nalvari
ablecanbeassignedaval
ueatt
woplaces.
 Attheti
meofdeclar at
ion.
 Inconst
ruct
or

Exampl
e1:

publi
cclassMain
{
fi
nali
ntspeedlimi
t=90;//f
inalvar
iabl
e
voi
dr un()
{
//
speedlimi
t=400;//eRROR
System.out
.pri
ntl
n("Val
ueofspeedl i
miti
s:"+speedl
i
mit
);
}
publi
cstati
cvoidmai n(St
ringargs[]
)
{
Mainobj=new Mai n();
obj.
run()
;
}
}

Example:2
publ
icclassMain
{
fi
nalintA;
/
/Scenari
o1:assi
gnmentatt
imeofdecl
arat
ion
f
inal
intB=2;

publi
cMai n()
{
//Scenari
o2:assi gnmentinconst r
uctor
A=1 ;
}
publi
cvoiddi splay()
{
System. out.pr
int
ln(
A+" ,"+B);
}
publi
cstati
cvoi dmai n(Str
ing[]args)
{
Maintester=newMai n();
tes
ter.display(
);
}
}
STATI
CFINALVARI
ABLE
Exampl
e:3

publ
i
cclassMai n
{
st
ati
cfinalintA;
//
Scenario1 :assignmentatt i
meofdecl arat
ion
fi
nali
ntB=2;
publ
icMai n()
{
//Scenar io2:assignmentinconstruct
or
A=1 ;/
/ERROR
}
publi
cvoi ddi splay(
)
{
Syst em. out.
pri
ntl
n(A+" ,"+B) ;
}
publi
cstat i
cvoi dmai n(St
ri
ng[]args)
{
Mai nt ester=newMai n(
);
tester .
displ
ay();
}
} OUTPUT:ERRORI NVARIABLEA

Fi
nalMet
hod:
I
fyoumakeanymet
hodasf
inal
,youcannotover
ri
dei
t.

Example4:
cl
assBike
{
f
inal voi
drun(
){Syst
em.
out
.pr
int
ln(
"runni
ng"
);}
}
cl
assMainextendsBi
ke
{
voi
drun()
{
Syst
em.out
.pr
int
ln(
"runni
ngsaf
elywi
th1
00kmph"
);
}

publ
i
cstati
cvoidmai
n(St
ri
ngar
gs[
])
{
Mainh1=newMain()
;
h1
.run(
);
}
}

FI
NALCLASS

Whenaclassisdecl
aredwi
thf
inalkeywor
d,i
tiscal
l
edaf
inal
class.Af
inal
classcannotbe
ext
ended(
inher
it
ed).

EXAMPLE5:
fi
nalcl
assBike
{
}
cl
assHonda1extendsBi ke
{
voi
drun()
{
Syst
em. out
.pri
ntl
n("
runni
ngsafelywi
th1
00kmph"
);
}
publ
icstat
icvoidmain(Str
ingargs[
])
{
Honda1honda=new Honda1 ()
;
honda.r
un();
}
}
ABSTRACTCLASS

Abst
ract
ionisaprocessofhi
dingt
hei
mpl
ement
ati
ondet
ail
sandshowi
ngonl
y
f
uncti
onali
tyt
otheuser.

Abst r
actclassinJava
Acl asswhi chisdecl aredasabs tractisknownasanabst ractcl
ass.I
tcanhave
abstractandnon- abst ractmethods.I tneedst obeext endedandi tsmethod
i
mpl ement ed.Itcannotbei nstant
iated.
PointstoRemember
 Anabst ractclassmustbedecl aredwi t
hanabstractkeyword.
I tcanhaveabst ractandnon- abstractmethods.
I tcannotbei nstantiat
ed.
I tcanhaveconst ructorsandst at
icmet hodsal
so.
I tcanhavef i
nalmet hodswhi chwi llf
orcethesubclassnottochangethe
bodyoft hemet hod

Exampl
eofAbst
ractcl
asst
hathasanabst
ractmet
hod
abst
ractcl
assBi
ke
{
abst
ractvoi
drun(
);
}
cl
assHonda4ext
endsBi
ke
{
voi
drun(
)
{
Syst
em.
out
.pr
int
ln(
"runni
ngsaf
ely"
);
}
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
Bi
keobj=new Honda4(
);
obj
.r
un(
);
}
}
Most
ly,wedon'
tknowaboutt
hei
mpl
ement
ati
oncl
ass(
whi
chi
shi
ddent
othe
enduser
),andanobj
ectoft
hei
mpl
ement
ati
oncl
assi
spr
ovi
dedbyt
hef
act
ory
met
hod.

abst
ractcl
assBank
{
abst
racti
ntget
Rat
eOf
Int
erest
();
}
cl
assSBIext
endsBank
{
i
ntget
Rat
eOf
Int
erest
(){
ret
urn7;
}
}
cl
assPNBext
endsBank
{
i
ntget
Rat
eOf
Int
erest
(){
ret
urn8;
}
}
cl
assTest
Bank
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
Bankb;
b=new SBI
()
;
Syst
em.
out
.pr
int
ln(
"Rat
eofI
nter
esti
s:"
+b.
get
Rat
eOf
Int
erest
()
+"%"
);

b=new PNB(
);
Syst
em.
out
.pr
int
ln(
"Rat
eofI
nter
esti
s:"
+b.
get
Rat
eOf
Int
erest
()
+"%"
);

}
}

Anabst
ractcl
asscanhaveadat
amember
,abst
ractmet
hod,met
hodbody(
non-
abst
ractmet
hod)
,const
ruct
or,andevenmai
n()met
hod.

/
/Ex
ampl
eofanabst
ractcl
asst
hathasabst
ractandnon-
abst
ractmet
hods
abstractclassBike
{
Bike(
)
{
Syst
em.out.pri
ntl
n("
bikeiscr
eated");
}
abst r
actvoidrun();
voidchangeGear (
)
{
Syst
em.out.pri
ntl
n("
gearchanged");
}
}+
/
/CreatingaChi l
dclasswhi chinher
it
sAbstractclass
classHondaext endsBi ke
{
voi
drun()
{
Syst
em.
out
.pr
int
ln(
"runni
ngsaf
ely.
."
);
}
}

//Creat i
ngaTestcl asswhi chcal l
sabst r
actandnon- abst
ractmet
hods
classTes t
Abstracti
on2
{
publ i
cstaticvoidmai n(Stri
ngar gs[])
{
Bikeobj=new Honda( );
obj.run()
;
obj.changeGear ();
}
}
THEABSTRACTCLASScanal sobeusedt oprovi
desomei mplementat
ionof
thei nterface.Insuchcase,t heendusermaynotbef or
cedtooverr
ideallt
he
met hodsoft hei nt
erf
ace.
i
nt erfaceA
{
voida( ); voi
db( ); voi dc(); voidd( )
;
}
abst ractclassBi mpl
ement sA
{
publ i
cvoidc( )
{
System.out.pr
intl
n("Iam c");
}
}
classM ext endsB
{
publ i
cvoida( ){
System. out.
print
ln("
Iam a");
}
publ i
cvoidb( ){
System. out.pr
int
ln("Iam b"
);}
publ i
cvoidd( ){
System. out.pr
int
ln("Iam d"
);}
}
classTest 5
{
publ i
cstaticvoidmai n(Stri
ngar gs[])
{ Aa=new M( );
a.
a()
;
a.
b()
;
a.
c()
;
a.
d()
;
}
}
UNI
T-I
II

I
NTERFACE
Sometimeswewantt oi
nheri
tthef
eaturesoftwoclassesatt
hesamet i
me.Buti
tisnotpossibl
einjava
becauseJavadoesnotsupportmul
ti
pleinher
it
ance.So,inor
dertoaccompli
sht
histask,Javaprovides
uswithtwoways.Theyare:

1
.Ei
therweext
endbot
hcl
assesonebyonebyusi
ngsi
ngl
einher
it
ance.

Cl
assI
{
---
-Body----
}
Cl
assJextendsI
{
---
-Body----
}
Cl
assM extendsJ
{
---
-Body----
}
2.
Secondwaybywhi chyoucani
mpl
ementmul
ti
plei
nher
it
ancei
susi
ngI
nter
faces.

I
tissi
mil
artoclas
s.Ascl
asscont
ainsmethodsandvar
iabl
es,i
nter
faceal
socontains.Butt
hedif
fer
ence
i
sthati
nclassyoucandefi
neanytypeofvari
abl
eandbodyofmet hodbutinI
nter
faceyouonlydefine
methodnameandi t
sparamet
eri.
e.,youcanonl
ydecl
arethem butyoucannotdefi
nebodyofmet hod.

I
tisacoll
ect
ionofabstr
actmethods.Aclassimplementsani
nt er
face,t
herebyinher
it
ingtheabstr
act
methodsoft
heinter
face.Wri
ti
ngani nt
erfaceissi
mi l
art
owri
tingaclass.Butaclassdescri
besthe
at
tri
but
esandbehaviorsofanobject
.Andani nterf
acecont
ainsbehaviorsthatacl
assimplements.

Unl
esstheclassthatimpl
ement
sthei
nter
facei
sabst
ract
,al
lt
hemet
hodsoft
hei
nter
faceneedt
obe
def
inedint
hecl ass.

Ani
nter
facei
ssi
mil
art
oacl
assi
nthef
oll
owi
ngways–

 Ani
nter
facecancont
ainanynumberofmet
hods
.

 Anint
erf
acei
swrit
teni
naf
il
ewi
tha.
javaex
tensi
on,wi
tht
henameoft
hei
nter
facemat
chi
ngt
he
nameofthef
il
e.

 Thebyt
ecodeofani
nter
faceappear
sina.
classf
il
e.

 I
nter
facesappeari
npackages
,andt
hei
rcor
respondi
ngbyt
ecodef
il
emustbei
nadi
rect
ory
st
ruct
uret
hatmat
chest
hepackagename.

I
nterf
aceisdecl
aredbytheuseofint
erf
acekeyword.Onceaninter
faceisdefi
ned,anynumberof
cl
assescanimplementit
.Ifacl
asswantst
oimplementanint
erf
ace,theniti
sessenti
alf
oracl
asst
o
defi
neal
lmethodsdeclaredint
heint
erf
ace.

Def
ini
ngI
nter
face:

int
erf
aceExampl e
{
voidexample(i
ntvalue);
}
Thisexamplecreatesasimpleint
erfacenamedExampl
e.I
tincl
udesonl
yonemet
hodnamedexampl
e()
thatt
akessingl
eintegerval
ue.

I
mpl
ement
ingI
nter
face:

I
faclasswant
stoi
mpl
ementani
nter
face,t
eni
tcani
mpl
ementani
nter
facebyusi
ngi
mpl
ement
s
keyword.

cl
assshowi
mplementsExample
{
publ
i
cvoidexampl
e(inte)
{
Syst
em.out
.pr
int
ln(
“I
mplement
ingI
nter
face”
);
Syst
em.out
.pr
int
ln(
“Val
ueofei
s:”+e);
}
}

Accessi
ngi
nter
facemet
hod:

cl
assShowi mplementsExampl e
{
publi
cvoidexample(inte)
{
Syst
em.out.
pri
ntln(
“I
mpl ement
ingInt
erf
ace”
);
Syst
em.out.
pri
ntln(
“Valueofeis:
”+e);
}
}
cl
asstest
{
publi
cstat
icvoidmain(Str
ingargs[
])
{
Shows=newShow( );
s.
example(1
0)
}
}
Usecl
assandi
nter
face:

i
nter
faceExampl e
{
voi
dshow( intvalue);
}
cl
assFirst
{
inta,b,c;
publicvoi dsum()
{
a=50;b=60;c=a+b;
Syst em.out.
printl
n("Sum="+c) ;
}
}
cl
assSecondext endsFi r
stimplement sExampl
e //
mul
ti
plei
nher
it
ance
{
publicvoi dshow( i
ntd)
{
System.out.pri
ntl
n("Valueofd="+d);
}
}
cl
assMai n
{
publicstaticvoi
dmai n(Str
ingargs[
])
{
Secondob=newSecond( )
;
ob.show(10);
ob.sum();
}
}
Usecl
assandi nterf
ace(withmor ethan01met hod)

i
nter
faceExampl
e /
/havi
ngt
hreemet
hod
{
voi
dshow(intvalue)
;
voi
dsubtr
act();
voi
dpr
int
Hel
l
o()
;
}
cl
assFi
rst //anotherclass
{
i
nta,b,c;
publi
cvoi dsum( )
{
a=50;b=60;c=a+b;
System.out .pri
nt l
n("Sum="+c) ;
}
}
cl
assSecondext endsFi rstimpl ement sExampl
e //mul
ti
plei
nher
it
ance
{
publi
cvoi dshow( intd)
{
Syst em. out.print
ln(
"Valueofd="+d)
;
}
publi
cvoi dsubt ract (
)
{
inta=1 0, b=5,c;c=a- b;
Syst em. out.printl
n("
ValueofC="+c);
}
publi
cvoi dpr i
ntHel lo()
{
Syst em. out.print
ln(
"Hello")
;
}
}
cl
assMain
{
publi
cstaticvoi dmai n(Stri
ngar gs[]
)
{
Secondob=newSecond( );
ob.show( 1
0) ;
ob.sum( );
ob.subtract();
ob.printHello();
}
}
Usecl
assandi
nter
face(
wit
hmor
ethanmet
hodonewi
thwi
thoutdef
ini
ti
on)

i
nter
faceExampl e //havi
ngf ourmethod
{
voidshow( i
ntvalue) ;voidsubt ract();voidprint
Hello()
;
publicvoidempt y( ); /
/Nodef ini
ti
onneeded
}
cl
assFirst //anothercl ass
{
inta,b,c;
publicvoidsum( )
{
a=50;b=60;c=a+b;
System. out.
printl
n("Sum="+c) ;
}
}
cl
assSecondext endsFirstimpl ement sExampl e / /mult
iplei
nheri
tance
{
publicvoidshow( i
ntd)
{ System. out.
printl
n("Val
ueofd="+d) ; }
publicvoidsubt r
act (
)
{
i
nta=1 0,b=5,c;c=a- b;
Syst
em. out .
printl
n("
Val ueofC="+c) ;
}
publicvoidpr i
ntHello()
{ System.out.pri
ntl
n("Hell
o")
;}
publicvoidempt y(){}
}
cl
assMai n
{
publ
i
cstati
cvoidmai n(
Str
ingar
gs[]
)
{
Secondob=newSecond( );
ob.
show( 10);
ob.
sum( );
ob.
subtract(
);
ob.
print
Hello()
;
}
}
Accessi
ngInterfaceVar iables
I
nter
facecanonl ybeusedt odecl areconst ant
s.Valuegiventovari
abl
esof
i
nter
facescannotbechangedbycl assimpl ementingtheseint
erf
aces.These
val
uescanbeusedbyanyonemet hod.
i
nter
faceExampl e
{
intValue=20;
publi
cvoi dempt y();
}
cl
assXi mplement sExampl e
{
publi
cvoi dempt y()
{
System. out .
printl
n("Empt yMet hod");
}
publi
cvoi dtabl e()
{
i
nttable=Val ue,j ;
for(i
nti=1 ;
i<=1 0;i
++)
{
j
=table* i
;
System. out.
print
ln(
j);
}
}
}
cl
assMai n
{
publi
cst at
icvoi dmai n(Stri
ngar gs[]
)
{
Xob=newX( );
ob.
empty();
ob.
tabl
e()
;
}
}

Ext
endingInt
erf
ace
Asoneclasscaninheri
tspr
opert
yofanothercl
ass,si
mil
arl
yonei
nter
facecan
i
nheri
tanotheri
nter
facebyusi
ngextendskeyword.

i
nter
faceI
{
voidshow1()
;
voidshow2()
;
}
i
nter
faceJextendsI
{
voi
dshow3();
}

cl
assDispl
ayimplementsJ
{
publi
cvoidshow1()
{
Syst
em.out
.pri
ntl
n("
insi
dei
nter
faceI
:show1()
");
}
publi
cvoidshow2()
{
Syst
em.out
.pri
ntl
n("
insi
dei
nter
faceI
:show2()
");
}
publi
cvoidshow3()
{
Syst
em.out
.pri
ntl
n("
insi
dei
nter
faceJ:show3(
)")
;
}
}
cl
assMain
{
publ
i
cst at
icvoi
dmain(
Str
ingargs[
])
{
Displ
ayob=newDisplay(
);
ob.show1();
ob.show2();
ob.show3();
}
}

ASSI
GNMENT:
5
1.Evaluat
e,howdoesanexcept i
onpr opagateinthecode?
2.Compar eCheckedExcept i
onwi thUncheckedExcept i
on.
3.Willthefi
nall
ybl ockgetexecutedwhent her etur
nst atementis
writ
tenattheendoft r
yblockandcat chblock?
4.Compar ethediffer
encesbetweent hrowandt hrows.
5.Compar eabstractcl
asswit
hinterfaceinJava.
6.I
ll
ustrat
ethesyntaxerror
sinJava.Gi veanytwoexampl es.
7.WhyanI nter
facemet hodcannotbedecl aredasf i
nali nJava?
Supportyouranswerwi t
hsuit
ableexampl e.
8.Canweputast ati
cmethodini nterf
aces?Explainwithasui t
able
example.
PACKAGES
Packagesar
eusedi
nJavai
nor
dert
opr
eventnami
ngconf
li
cts,t
ocont
rolaccess,t
omake
sear
chi
ng/
locat
ingandusageofcl
asseseasi
er,et
c.

Packagei
sthenamegi
vent
ogr
oupofcl
asses
.Itact
sasacont
ainerf
orcl
asses.Apackagei
s
consi
stsofgr
oupofcl
assesput
ti
ngt
oget
heratonepl
aceandwhol
egr
oupi
sdef
inedbya
uni
quename.
Ther
ear
etwot
ypesofpackages:

 Syst
em packages:Packagesal
readydef
inedi
nJava

 Userdef
inedpackages:Packagesdef
inedbyt
heuser
.

SYSTEM PACKAGES
Pr
edef
inedpackage,someoft
heexi
sti
ngpackagesi
nJavaar
e–

 l
angpackage
l
angpackagei
ncl
udescl
assesf
orpr
imi
ti
vet
ypes,st
ri
ngs
,mat
hfunct
ions,t
hreadand
except
ion.Thi
spackagei
simpor
tedbydef
aul
t.Li
ke;Bool
ean,Byt
e,Doubl
e,Long,
Thr
ead,Mat
het
c.
 i
opackage
cl
assesf
ori
nput,out
putf
unct
ionsar
ebundl
edi
nthi
spackage.Li
ke;Dat
aInput
Str
eam,
Dat
aOut
put
Str
eam,Buf
fer
edI
nput
Str
eam,Buf
fer
edOut
put
Str
eam,I
nput
Str
eam,
Pt
int
Str
eam et
c.
 ut
il
package
ut
il
packagei
ncl
udescl
assesf
orut
il
i
tyf
unct
ionsl
i
kevect
or,hasht
abl
es,r
andom
number
s,dat
eet
c.l
i
ke;Dat
e,Vect
or,Random,HashTabl
eet
c.
 awtpackage
awti
ncl
udescl
assest
hatar
eusedf
ori
mpl
ement
inggr
aphi
cal
useri
nter
face.
Like;
But
ton,Col
or,Fr
ame,Gr
aphi
cset
c.
 netpackage
netpackagei
ncl
udescl
assesf
ornet
wor
king.Li
ke;Dat
agr
amSocket
,Dat
agr
amPacket
,
Socket
,URLet
c.
 appl
etpackage
appl
etpackagei
ncl
udescl
assesf
orcr
eat
ingnet
wor
king.Li
ke;Dat
agr
amSocket
,
Dat
agr
amPacket
,Socket
,URLet
c.

USI
NGSYSTEM PACKAGE
Wecanusepackagei
nourpr
ogr
am byi
mpor
ti
ngt
hem.Apackagei
simpor
tedbyusi
ng
i
mpor
tkeywor
d;as:
i
mpor
tpackagename;
Now,wehavet
wowayst
oaccesscl
assesofpackages:
1
.wecani
mpor
tonl
ythatpar
ti
cul
arcl
asst
hatwewantt
ousei
nourpr
ogr
am.
i
mpor
tpkg.
classname;
i
mpor
tjava.
awt
.But
ton;
2.I
nst
eadofspeci
fyi
nganame,wewr
it
e‘*
’.I
tmeanst
hatj
avacompi
l
ershoul
dimpor
tal
l
t
hepackages.
i
mpor
tjava.
uti
l
.*;

Exampl
e:
/
/JavaPr
ogr
am t
oDi
spl
ayCur
rentDat
e
/
/Usi
ngut
ilpackage /
/Usi
ngDat
eCl
ass

i
mpor
tjava.
uti
l
.Dat
e;
i
mpor
tjava.
uti
l
.*;
cl
assMai
n
cl
assMai
n
{
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
{
Dat
ecur
rent
_Dat
e=newDat
e()
;
Dat
ecur
rent
_Dat
e=newDat
e()
;
/
/"Dat
e"cl
ass
/
/"Dat
e"cl
ass
/
/"cur
rent
_Dat
e"i
sanobj
ect
/
/"cur
rent
_Dat
e"i
sanobj
ect
Syst
em.
out
.pr
int
ln(
cur
rent
_Dat
e);
Syst
em.
out
.pr
int
ln(
cur
rent
_Dat
e);
}
}
}
}

USERDEFI
NEDPACKAGE
Pr
ogr
ammer
scandef
inet
hei
rownpackages.

CREATI
NGAPACKAGE
Whi
l
ecr
eat
ingapackage,youshoul
dchooseanamef
ort
hepackageandi
ncl
udeapackage
st
atemental
ongwi
tht
hatnameatt
het
opofever
ysour
cef
il
e.
packagepackagename;
packageabc;
Thepackagest
atementshoul
dbet
hef
ir
stl
i
nei
nthesour
cef
il
e.Ther
ecanbeonl
yone
packagest
atementi
neachsour
cef
il
e.

Tocompi
l
etheJavapr
ogr
amswi
thpackagest
atement
s,youhavet
ouse-
dopt
ionasshown
bel
ow.
j
avac-
dDest
inat
ion_f
olderf
il
e_name.
java

Thenaf
olderwi
tht
hegi
venpackagenamei
scr
eat
edi
nthespeci
fi
eddest
inat
ion,andt
he
compi
l
edcl
assf
il
eswi
l
lbepl
acedi
nthatf
older
.

Exampl
e-1

Cr
eat
eapackagecal
l
edani
mal
s.I
tisagoodpr
act
icet
ousenamesofpackageswi
thl
ower
casel
ett
erst
oavoi
danyconf
li
ctswi
tht
henamesofcl
assesandi
nter
faces.

Fol
l
owi
ngpackageexampl
econt
ainsi
nter
facenamedani
mal
s–

St
ep1
:
/
*Fi
l
ename:Ani
mal
.j
ava*
/
packageani
mal
s;
i
nter
faceAni
mal
{
publ
i
cvoi
deat
()
;
publ
i
cvoi
dtr
avel
()
;
}

St
ep2:

Now,l
etusi
mpl
ementt
heabovei
nter
facei
nthesamepackageani
mal
s−
packageani
mal
s;
/
*Fi
l
ename:Demo.
java*
/
publ
i
ccl
assDemoi
mpl
ement
sAni
mal
{
publ
i
cvoi
deat
()
{
Syst
em.
out
.pr
int
ln(
"Ani
mal
seat
s")
;
}
publ
i
cvoi
dtr
avel
()
{
Syst
em.
out
.pr
int
ln(
"Ani
mal
str
avel
s")
;
}
}
St
ep3:
/
/cl
assuseDemo.
javaf
orusi
ngpackagesavei
nbi
nfol
der
i
mpor
tani
mal
.*
;
cl
assUseDemo
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
Demom =newDemo(
);
m.
eat
();
m.
tr
avel
()
;
}
}
Nowcompi
l
ethej
avaf
il
esasshownbel
ow−
$j
avac-
d.Ani
mal
.j
ava
$j
avac-
d.Demo.
java
Nowapackage/
fol
derwi
tht
henameani
mal
swi
l
lbecr
eat
edi
nthecur
rentdi
rect
oryandt
hese
cl
assf
il
eswi
l
lbepl
acedi
nit
.
Youcanexecut
ethecl
assf
il
ewi
thi
nthepackageandgett
her
esul
tasshownbel
ow.
$j
avacUseDemo.
java
$j
avaUseDemo

Ani
mal
seat
s
Ani
mal
str
avel
s

Exampl
e-2
St
ep1:
Cal
cul
ator
.j
avaf
il
ecr
eat
edi deapackagel
nsi etmecal
cul
ate
packagel
etmecal
cul
ate;
publ
i
ccl
assCal
cul
ator
{
publ
i
cintadd(
inta,i
ntb)
{
r
etur
na+b;
}
}
Not
e:SaveasCal
cul
ator
.j
avai
nbi
nfol
der
,ForRunni
nguset
hiscommand:
Bi
n>j
avac–d .Cal
cul
ator
.j
ava

Not
e:Thi
scommandwi
l
lcr
eat
eapackagenamel
etmecal
cul
atei
nsi
debi
nfol
der
,butf
orusi
ng
t
hisCal
cul
atorcl
assyouhavet
ousei
mpor
tst
atementi
nanot
herpr
ogr
am.

St
ep2:Nowl
etsseehowt
ouset
hispackagei
nanot
herpr
ogr
am.
i
mpor
tlet
mecal
cul
ate.
Cal
cul
ator
;
publ
i
ccl
assDemo
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
Cal
cul
atorobj
=newCal
cul
ator
();
Sys
tem.
out
.pr
int
ln(
obj
.add(
100,200)
);
}
}
Not
e:SaveasDemo.
javai
nbi
nfol
der
ForRunni
nguset
hiscommand:
Bi
n>j
avacDemo.
java
Bi
n>j
avaDemo

Touset
hecl
assCal
cul
ator
,Ihavei
mpor
tedt
hepackagel
etmecal
cul
ate.I
ntheabovepr
ogr
am
Ihavei
mpor
tedt
hepackageasl
etmecal
cul
ate.Cal
cul
ator
,thi
sonl
yimpor
tst
heCal
cul
ator
cl
ass.Howeveri
fyouhavesever
alcl
assesi
nsi
depackagel
etmecal
cul
atet
henyoucani
mpor
t
t
hepackagel
i
ket
his,t
ouseal
lt
hecl
ass
esoft
hispackage.
i
mpor
tlet
mecal
cul
ate.
*;

Subpackagesi
nJava
Apackagei
nsi
deanot
herpackagei
sknownassubpackage.Forexampl
eIfIcr
eat
ea
packagei
nsi
del
etmecal
cul
atepackaget
hent
hatwi
l
lbecal
l
edsubpackage.
Let
ssayIhavecr
eat
edanot
herpackagei
nsi
del
etmecal
cul
ateandt
hesubpackagename
i
smul
ti
ply.Soi
fIcr
eat
eacl
assi
nthi
ssubpackagei
tshoul
dhavet
hispackagedecl
arat
ioni
n
t
hebegi
nni
ng:
packagel
etmecal
cul
ate.
mul
ti
ply;

/
/Mul
ti
pli
cat
ion.
java
packagel
etmecal
cul
ate.
mul
ti
ply;
publ
i
ccl
assMul
ti
pli
cat
ion
{
publ
i
cintpr
oduct
(i
nta,i
ntb)
{
r
etur
na*
b;
}

}
Compi
l
efi
l
e
Not
e:SaveasMul
ti
pli
cat
ion.
javai
nbi
nfol
der
,ForRunni
nguset
hiscommand:
Bi
n>j
avac–d .Mul
ti
pli
cat
ion.
java
Bi
n>j
ava l
etmecal
cul
ate.
mul
ti
ply.
Mul
ti
pli
cat
ion
Nowi
fIneedt
ouset
hisMul
ti
pli
cat
ioncl
assIhavet
oei
theri
mpor
tthepackagel
i
ket
his:
i
mpor
tlet
mecal
cul
ate.
mul
ti
ply.
*;
orIcanusef
ull
yqual
i
fi
ednamel
i
ket
his
:
l
etmecal
cul
ate.
mul
ti
ply.
Mul
ti
pli
cat
ionobj
=
newl
etmecal
cul
ate.
mul
ti
ply.
Mul
ti
pli
cat
ion(
);
i
mportletmecalcul
ate.multi
ply.*
;
publ
i
ccl assDemo
{
publ
icstati
cvoidmai n(Str
ingar gs[
])
{
Mult
ipl
i
cat i
onm =newMul ti
pli
cati
on()
;
Syst
em. out.
pri
nt l
n(m.product
(5,6)
);
}
}

Runt
hispr
ogr
am:
Bi
n>j
avacDemo.
java
SYSTEM PACKAGEPROGRAMS

Pr
ogr
am 1
:MyCl
ass.
java
i
mpor
tjava.
uti
l
.Scanner
;
cl
assMai
n
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs)
{
ScannermyObj
=newScanner
(Syst
em.
in)
;
Syst
em.
out
.pr
int
ln(
"Ent
eruser
name"
);
St
ri
nguser
Name=myObj
.next
Line(
);
Syst
em.
out
.pr
int
ln(
"User
namei
s:"+user
Name)
;
}
}

Pr
ogr
am 2:Gener
ateRandomNumber
.j
ava
i
mpor
tjava.
uti
l
.*;

publ
i
cclassGenerateRandomNumber
{
publ
icstat
icvoidmain(St
ring[]args)
{
Random r=new Random( );
intnum =r.next
Int
(10);
System.out.
pri
ntl
n("
Gener atedRandom Numberbet
ween0t o1 0is:
"
+num) ;
intnumNoRange=r .nextI
nt()
;
System.out.
pri
ntl
n("
Gener atedRandom Numberwit
houtspeci
fyi
nga
myr angeis:"+numNoRange) ;
}
}
USERDEFI
NEDPACKAGEPROGRAMS
Pr
ogr
am 1
:cr
eat
eapackageandcal
l

packagemypack;
cl
assMyPackageClass
{
publi
cst
ati
cvoidmain(Str
ing[
]ar
gs)
{
Syst
em.out.
pri
ntl
n("
Thisi
smypackage!
")
;
}
}

Save
MyPackage. j
ava
Compileli
ke:
C:\
..
..
.\
bin>javac-d.MyPackageCl
ass.
java

Runpr
ogr
am:

C:
\.
..
..
\bi
n>j
avamypack.
MyPackageCl
ass

Out
put
:

Thi
sismypackage!

Pr
ogr
am 2cr
eat
eapackageandcal
li
nanot
hercl
ass
Fi
rstwecr
eat
eadi
rect
orymyPackage(
nameshoul
dbesameast
henameof
t
hepackage)
.Thencr
eat
etheMyCl
assi
nsi
det
hedi
rect
orywi
tht
hef
ir
st
st
atementbei
ngt
hepackagenames.

St
ep1
:
/
/Nameoft
hepackagemustbesameast
hedi
rect
ory
/
/underwhi
cht
hisf
il
eissaved

packagemyPackage;
publi
cclassMyClass
{
publi
cvoidget
Names(
Str
ings)
{
Syst
em.
out
.pr
int
ln(
s);
}
}
Save
MyClass.
java
Compileli
ke:
C:\
..
..
.\
bin>javac-
d.MyCl
ass.
java

St
ep2:
/
*Nowwecanuset
heMyCl
asscl
assi
nourpr
ogr
am.i
mpor
t'MyCl
ass'cl
ass
f
rom '
names'myPackage*
/

i
mpor
tmyPackage.
MyCl
ass;
publ
i
ccl
assPr
int
Name
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
St
ri
ngname="
Hel
l
oII
MT"
;
MyCl
assobj
=newMyCl
ass(
);
obj
.get
Names(
name)
;
}
}
Save
Pri
ntName.java
Compileli
ke:
C:\
..
..
.\
bin>javacPr
int
Name.
java

Runpr
ogr
am:

C:
\.
..
..
\bi
n>j
avaPr
int
Name

Out
put
:

Hel
l
oII
MT

Pr
ogr
am 3cr
eat
etwopackageandcal
li
nacl
ass
St
ep1
:Cl
assOne.
java
packagepackage1;
publ
i
ccl
assCl
assOne
{
publ
i
cvoi
dmet
hodCl
assOne(
)
{
Syst
em.
out
.pr
int
ln(
"Hel
l
o,Iam i
nCl
assOne"
);
}
}
St
ep2:Cl
assTwo.
java
packagepackage2;
publ
i
ccl
assCl
assTwo
{
publ
i
cvoi
dmet
hodCl
assTwo(
)
{
Syst
em.
out
.pr
int
ln(
"Hel
l
o,Iam i
nCl
assTwo"
);
}
}
St
ep3:i
mpor
tbot
hpackageandsavet
hiscl
assasTest
.j
ava
i
mportpackage2.Cl
assTwo;
i
mportpackage1.Cl
assOne;
publ
i
cclassTest
{
publ
icstat
icvoi
dmai n(St
ri
ng[]ar
gs)
{
ClassTwoa=newCl assTwo()
;
ClassOneb=newCl assOne()
;
a.methodClassTwo(
);
b.methodClassOne(
);
}
}
Pr
ogr
am 4:Exampl
eofpackagebyi
mpor
tful
l
yqual
i
fi
edname

St
ep1
:A.
java
packagepack;

publ
i
ccl
assA

publ
i
cvoi
dmsg(
)

Syst
em.
out
.pr
int
ln(
"Hel
l
o")
;

Compi
l
ethi
sfi
l
e.
bi
n>j
avac–d.A.
java

St
ep2:B.
java
packagemypack;

cl
assB

publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])

pack.
Aobj=new pack.
A()
;/
/usi
ngf
ull
yqual
i
fi
edname

obj
.msg(
);

/
/compi
l
eandr
unt
hisf
il
e
/
javac–d.B.
java
/
Javamypack.
B
PROGRAM 5:

STATI
CIMPORTI
NJAVA

Stati
cimportf
eat
urewasint
roducedi
nJavaf
rom ver
sion5.I
tfaci
l
it
atest
heJava
programmertoaccessanyst
ati
cmemberofaclassdi
rect
lywit
houtusi
ngthe
ful
lyqual
if
iedname.

packageMyPackage;
i
mpor
tst
ati
cjava.
lang.
Mat
h.*
;//
stat
ici
mpor
t
i
mpor
tst
ati
cjava.
lang.
Syst
em.
*;/
/st
ati
cimpor
t
publ
i
ccl
assSt
ati
cImpor
tDemo
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
doubl
eval
=64.
0;
doubl
esqr
oot=sqr
t(val
);/
/Accesssqr
t()met
hoddi
rect
ly
out
.pr
int
ln(
"Sq.r
ootof"+val
+"i
s"+sqr
oot
);
/
/Wedon'
tneedt
ouse'
Syst
em.
out
}
}
PROGRAM 6:cr
eat
e2cl
assi
napackgeandcal
lwi
thanot
hercl
ass
Step1:Demo.j
ava
packagepack;

cl
asspack_add
{
publi
cvoidadd(i
ntx,i nty)
{
Syst
em.out.pri
ntl
n("
TheAddof"
+x+"&"
+y+"i
s:-"
+(x+y))
;
}
}
publ
iccl
asspack_subextendspack_add
{
publ
icvoi
dsub(intx,inty)
{
//
super
.add(x,y);
Syst
em.out.pri
ntl
n("
TheSubof"
+x+"&"
+y+"i
s:-"
+(x-y)
);
}
}

St
ep2:
//
importj
ava. i
o.*; //
importj
ava.ut
il
.*;
i
mportpack. pack_sub;
cl
asscall
ing_pack_sub
{
publ
ics t
aticvoidmai n(Stri
ngarr[
])
{
/
*i nta,b;
Scannerob=newScanner( Syst
em.in);
System.out .
print
ln(
"Entert
hesameval ueforaddandsub:
-")
;
a=ob.nextInt()
;
b=ob.nextInt()
;*/
inta=1 0,b=1 5;
pack_subob1=newpack_sub( )
;
ob1.sub(a,b);
ob1 .
add( a,b);
}
}
EXCEPTI
ONHANDLI
NG

EXCEPTI
ON

Anexcept
ioni
sapr
obl
em t
hatar
isesdur
ingt
heexecut
ionofapr
ogr
am.An
except
ioncanoccurf
ormanydi
ff
erentr
easons,i
ncl
udi
ngt
hef
oll
owi
ng:

Auserhasent
eredi
nval
i
ddat
a.
Af
il
ethatneedst
obeopenedcannotbef
ound.
Anet
wor
kconnect
ionhasbeenl
osti
nthemi
ddl
eofcommuni
cat
ions,ort
he
JVM hasr
unoutofmemor
y.

AnExcept
ioni
sanunwant
edeventt
hati
nter
rupt
sthenor
mal
flowoft
hepr
ogr
am.
Whenanexcept
ionoccur
spr
ogr
am execut
ionget
ster
minat
ed.I
nsuchcaseswe
getasyst
em gener
ateder
rormessage.Thegoodt
hingaboutexcept
ionsi
sthat
t
heycanbehandl
ed i
nJava.Byhandl
i
ng t
heexcept
ionswecanpr
ovi
dea
meani
ngf
ulmessaget
otheuseraboutt
hei
ssuer
athert
hanasyst
em gener
ated
message,whi
chmaynotbeunder
standabl
etoauser
..

Cat
egor
iesofexcept
ions:

Checked except
ions:Checked except
ionsast
he compi
l
ercheckst
hem
dur
ingcompi
l
ati
ont
oseewhet
hert
hepr
ogr
ammerhashandl
edt
hem or
not
.Ift
heseexcept
ionsar
enothandl
ed/
decl
aredi
nthepr
ogr
am,youwi
l
l
getcompi
l
ati
oner
ror
.Forexampl
e,i
faf
il
eist
obeopened,butt
hef
il
e
cannotbef
ound,anexcept
ionoccur
s.Theseexcept
ionscannotsi
mpl
ybe
i
gnor
edatt
het
imeofcompi
l
ati
on.
Anot
herexampl
e,SQLExcept
ion,I
OExcept
ion,Cl
assNot
FoundExcept
ionet
c.
Unchecked/
Runt
imeexcept
ions:A r
unt
imeexcept
ioni
sanexcept
iont
hat
occur
sthatpr
obabl
ycoul
d havebeenavoi
ded byt
hepr
ogr
ammer
.As
opposed t
o checked except
ions,r
unt
imeexcept
ionsar
eignor
ed att
he
t
imeofcompi
l
ati
on.
For exampl
e, Ar
it
hmet
icExcept
ion, Nul
l
Poi
nter
Except
ion,
Ar
rayI
ndexOut
OfBoundsExcept
ionet
c.

NOTE:Er
ror
s:Thesear
enotexcept
ionsatal
l
,butpr
obl
emst
hatar
isebeyondt
he
cont
roloft
heuserort
hepr
ogr
ammer
.Forexampl
e,i
fast
ackover
fl
ow occur
s,
aner
rorwi
l
lar
ise.Theyar
eal
soi
gnor
edatt
het
imeofcompi
l
ati
on.

Er
ror
sar
e notnor
mal
l
ytr
apped f
orm t
he Java pr
ogr
ams.These condi
ti
ons
nor
mal
l
yhappeni
ncaseoff
ail
ures,whi
char
enothandl
edbyt
hej
avapr
ogr
ams.
Nor
mal
l
ypr
ogr
amscannotr
ecoverf
rom er
ror
s.

Advant
ageofExcept
ionHandl
i
ng:
Thecor
eadvant
ageofexcept
ionhandl
i
ngi
stomai
ntai
nthenor
mal
flowoft
he
appl
i
cat
ion.Anexcept
ionnor
mal
l
ydi
srupt
sthenor
mal
flowoft
heappl
i
cat
ion
t
hati
swhyweuseexcept
ionhandl
i
ng.Exampl
e:
st
atement1
;

st
atement2;

st
atement3;

st
atement4;

st
atement5;
//except
ionoccur
s

st
atement6;

st
atement7;

st
atement8;

st
atement9;

st
atement1
0;
Supposether
eare1 0st
atement
sinyourpr
ogram andther
eoccur
sanexceptionatst
atement
5,t
herestofthecodewil
lnotbeexecut
edi.
e.st
atement6to10wil
lnotbeexecut
ed.Ifwe
per
for
m except
ionhandl
i
ng,t
her
estoft
hest
atementwi
l
l ed.
beexecut

Except
ionHi
erar
chy:

Al
lexcept
ionander
ror
stypesar
esubcl
assesofcl
assThr
owabl
e,whi
chi
sbas
e
cl
assofhi
erar
chy.
Onebr
anchi
sheadedbyExcept
ion.Thi
scl
assi
susedf
or
except
ionalcondi
ti
onst
hatuserpr
ogr
amsshoul
dcat
ch.Nul
l
Poi
nter
Except
ioni
s
anexampl
eofsuchanexcept
ion.
Anot
herbr
anch,Er
rorar
eusedbyt
heJavar
un
-
timeMachi
nesyst
em(
JVM)t
oindi
cat
eer
ror
shavi
ngt
odowi
tht
her
un-
time
envi
ronmenti
tsel
f(
JRE)
.St
ackOver
fl
owEr
rori
sanexampl
eofsuchaner
ror
.

JavaExcept
ionHandl
i
ngKeywor
ds

Javapr
ovi
desspeci
fi
ckeywor
dsf
orexcept
ionhandl
i
ngpur
poses,wewi
l
llook
af
tert
hem f
ir
standt
henwewi
l
lwr
it
easi
mpl
epr
ogr
am showi
nghowt
ouset
hem
f
orexcept
ionhandl
i
ng.

t
hrow –Weknowt
hati
fanyexcept
ionoccur
s,anexcept
ionobj
ecti
sget
ti
ng
cr
eat
edandt
henJavar
unt
imest
art
spr
ocessi
ngt
ohandl
ethem.Somet
imewe
mi
ghtwantt
ogener
ateexcept
ionexpl
i
cit
lyi
nourcode,f
orexampl
einauser
aut
hent
icat
ionpr
ogr
am weshoul
dthr
owexcept
iont
ocl
i
enti
fthepasswor
dis
nul
l
.thr
ow keywor
disusedt
othr
owexcept
iont
other
unt
imet
ohandl
eit
.

t
hrows–Whenwear
ethr
owi
nganyexcept
ioni
namet
hodandnothandl
i
ngi
t,
t
henweneedt
ouset
hrowskeywor
dinmet
hodsi
gnat
uret
oletcal
l
erpr
ogr
am
knowt
heexcept
ionst
hatmi
ghtbet
hrownbyt
hemet
hod.Thecal
l
ermet
hod
mi
ghthandl
etheseexcept
ionsorpr
opagat
eitt
oit
’scal
l
ermet
hodusi
ngt
hrows
keywor
d.Wecanpr
ovi
demul
ti
pleexcept
ionsi
nthet
hrowscl
auseandi
tcanbe
usedwi
thmai
n()met
hodal
so.

t
ry-
cat
ch–Weuset
ry-
cat
chbl
ockf
orexcept
ionhandl
i
ngi
nourcode.t
ryi
sthe
st
artoft
hebl
ockandcat
chi
satt
heendoft
rybl
ockt
ohandl
etheexcept
ions.
Wecanhavemul
ti
plecat
chbl
ockswi
that
ryandt
ry-
cat
chbl
ockcanbenest
ed
al
so.cat
chbl
ockr
equi
resapar
amet
ert
hatshoul
dbeoft
ypeExcept
ion.

f
inal
l
y–f
inal
l
ybl
ocki
sopt
ional
andcanbeusedonl
ywi
tht
ry-
cat
chbl
ock.Si
nce
except
ionhal
tst
hepr
ocessofexecut
ion,wemi
ghthavesomer
esour
cesopen
t
hatwi
l
lnotgetcl
osed,sowecanusef
inal
l
ybl
ock.f
inal
l
ybl
ockget
sexecut
ed
al
ways,whet
herexcept
ionoccur
redornot
.

CATCHI
NGEXCEPTI
ONS
A met
hod cat
chesan except
ion usi
ng a combi
nat
ion oft
he t
ry and cat
ch
keywor
ds.At
ry/
cat
chbl
ocki
spl
acedar
oundt
hecodet
hatmi
ghtgener
atean
except
ion.Codewi
thi
nat
ry/
cat
chbl
ocki
sref
err
edt
oaspr
otect
edcode,andt
he
synt
axf
orusi
ngt
ry/
cat
chl
ooksl
i
ket
hef
oll
owi
ng:
t
ry
{
/
/Pr
otect
edcode
}
cat
ch(
Except
ionNamee1
)
{
/
/Cat
chbl
ock
}
Acat
chst
atementi
nvol
vesdecl
ari
ngt
het
ypeofexcept
ionyouar
etr
yingt
o
cat
ch.I
fanexcept
ionoccur
sinpr
otect
edcode,t
hecat
chbl
ock(
orbl
ocks)t
hat
f
oll
owt
het
ryi
schecked.I
fthet
ypeofexcept
iont
hatoccur
redi
sli
stedi
nacat
ch
bl
ock,t
heexcept
ioni
spassedt
othecat
chbl
ockmuchasanar
gumenti
spassed
i
ntoamet
hodpar
amet
er.

Exampl
e:Thef
oll
owi
ngi
sanar
rayi
sdecl
aredwi
th2el
ement
s.Thent
hecode
t
ri
est
oaccesst
he3r
del
ementoft
hear
raywhi
cht
hrowsanexcept
ion.
/
/Fi
l
eName:
Excep.
java
i
mpor
tjava.
io.
*;
publ
i
ccl
assExcep
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
t
ry
{
i
nta[
]=newi
nt[
2];
Sys
tem.
out
.pr
int
ln(
"Accessel
ementt
hree:
"+a[
3])
;
}
cat
ch(
Arr
ayI
ndexOut
OfBoundsExcept
ione)
{
Syst
em.
out
.pr
int
ln(
"Except
iont
hrown:
"+e)
;
}
Syst
em.
out
.pr
int
ln(
"Outoft
hebl
ock"
);
}
}
MULTI
PLECATCHBLOCK

t
ry
{
/
/Protect
edcode
}
cat
ch(Excepti
onType1e1)
{
/
/Catchblock
}
cat
ch(Excepti
onType2e2)
{
//Cat
chbl ock
}
cat
ch(Excepti
onType3e3)
{
//Cat
chbl ock
}

Thethrows/thr
owKeywor ds:Ifamethoddoesnothandleacheckedexcepti
on,
themethodmustdecl areitusi
ngthethr
owskeywor d.Thethr
owskeyword
appearsattheendofamet hod'ssi
gnat
ure.
Youcant hrowanex cepti
on,eit
heranewlyinst
ant
iatedoneoranexcept
iont
hat
youjustcaught,byusi
ngt hethr
owkeywor d.

FI
NALLYKEYWORD

Thefi
nal
lykeywor
disusedt
ocreat
eablockofcodethatf
oll
owsatrybl
ock.A
fi
nal
l
yblockofcodeal
waysexecut
es,whet
herornotanexcept
ionhasoccur
red.

Af i
nall
yblockappear satt
heendoft
hecat
chbl
ocksandhast
hef
oll
owi
ng
syntax:tr
y
{
/
/Protect
edcode
}catch(Excepti
onType1e1)
{
/
/Catchblock
}
catch(Excepti
onType2e2)
{
//Catchblock
}
catch(Excepti
onType3e3)
{
//
Catchblock
}
f
inal
ly
{
//
Thef i
nall
yblockal
waysexecut
es.
}

Not
e:
Acat
chcl
aus
ecannotexi
stwi
thoutat
ryst
atement
.
I
tisnotcompul
sor
ytohavef
inal
l
ycl
auseswheneverat
ry/
cat
chbl
ocki
spr
esent
.
Thet
rybl
ockcannotbepr
esentwi
thoutei
thercat
chcl
auseorf
inal
l
ycl
ause.
Anycodecannotbepr
esenti
nbet
weent
het
ry,cat
ch,f
inal
l
ybl
ocks.

Exampl
e;
i
mpor tjava.io.*;
/*
Thisisabui l
t-in-classpresentinjava.langpackage.Thi
sexcept
ionoccur
s
whenani ntegeri sdi vi
dedbyzer o.
* /
cl
assMai n
{
publicst ati
cvoi dmai n(
Stri
ngargs[ ]
)
{
t
ry
{
i
ntnum1 =30,num2=0;
i
ntout put=num1 /
num2;
System. out.pri
ntl
n("Result:"+output
);
}
catch( Ari
thmet icExcepti
one){
Syst em. out.pri
nt l
n("YouShoul dn'tdivi
deanumberbyzero")
;
}
fi
nal
ly
{
Syst
em.out
.pr
int
ln(
"I
nsi
def
inal
l
y")
;
}
}
}
Exampl
es:

Exampl
e1:Ar
it
hmet
icexcept
ion

Cl
ass:Java.
lang.
Ari
thmet
icExcept
ion
/
*Thi
sisabui
l
t-i
n-cl
asspr
esenti
njava.
langpackage.Thi
sexcept
ionoccur
s
whenani
ntegeri
sdi
vi
dedbyzer
o.*
/
cl
assExampl
e1
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
t
ry{
i
ntnum1
=30,num2=0;
i
ntout
put
=num1
/num2;
Syst
em.
out
.pr
int
ln(
"Resul
t:"
+out
put
);
}
cat
ch(
Ari
thmet
icExcept
ione)
{
Syst
em.
out
.pr
int
ln(
"YouShoul
dn'
tdi
vi
deanumberbyzer
o")
;
}
}
}
Exampl
e2:Ar
rayI
ndexOut
OfBoundsExcept
ion

Cl
ass:Java.
lang.
Arr
ayI
ndexOut
OfBoundsExcept
ion
Thi
sexcept
ionoccur
swhenyout
ryt
oaccesst
hear
rayi
ndexwhi
chdoesnot
exi
st.Forexampl
e,I
far
rayi
shavi
ngonl
y5el
ement
sandwear
etr
yingt
odi
spl
ay
7t
hel
ementt
heni
twoul
dthr
owt
hisexcept
ion.
cl
assExcept
ionDemo2
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
Tr
y
{
i
nta[
]=newi
nt[
10]
;
/
/Ar
rayhasonl
y10el
ement
s
a[
11]=9;
}
cat
ch(
Arr
ayI
ndexOut
OfBoundsExcept
ione)
{
Syst
em.
out
.pr
int
ln(
"Ar
rayI
ndexOut
OfBounds"
);
}
}
}
Exampl
e3:Number
For
matExcept
ion
Cl
ass:Java.
lang.
Number
For
mat
Except
ion
Thi
sexcept
ionoccur
swhenast
ri
ngi
spar
sedt
oanynumer
icvar
iabl
e.
Forexampl
e,t
hest
atementi
ntnum=I
nteger
.par
seI
nt(
"XYZ"
);woul
d
t
hrow Number
For
mat
Except
ionbecaus
eSt
ri
ng“
XYZ”cannotbepar
sedt
oint
.
cl
assExcept
ionDemo3
{
publ
i
cst
ati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
t
ry
{
i
ntnum=I
nteger
.par
seI
nt(
"XYZ"
);
Syst
em.
out
.pr
int
ln(
num)
;
}
cat
ch(
Number
For
mat
Except
ione)
{
Syst
em.
out
.pr
int
ln(
"Numberf
ormatexcept
ionoccur
red"
);
}
}
}

Di
ff
erencebet
weent
hrowandt
hrowsi
nJava

Ther
ear
emanydi
ff
erencesbet
weent
hrowandt
hrowskeywor
ds.Al
i
stof
di
ff
erencesbet
weent
hrowandt
hrowsar
egi
venbel
ow:
No t
hrow t
hrows
.

1 Javat
hrowkeywor
disused Javat
hrowskeywor
disusedt
odecl
arean
t
oexpl
i
cit
lyt
hrowan except
ion.
except
ion.

2 Thr
owi
sfol
l
owedbyan Thr
owsi
sfol
l
owedbycl
ass.
i
nst
ance.

3 Thr
owi
susedwi
thi
nthe Thr
owsi
susedwi
tht
hemet
hodsi
gnat
ure.
met
hod.

4 Youcannott
hrowmul
ti
ple Youcandecl
aremul
ti
pleexcept
ionse.
g.
except
ions. publ
i
cvoi
dmet
hod(
)thr
ows
I
OExcept
ion,
SQLExcept
ion.

Exampl
e:t
hrowkeywor
d
publ
iccl assMain
{
publ i
cvoidcheckAge(
intage)
{
i
f(age<1 8)
thr
ownewAr i
thmeti
cExcept
ion(
"NotEl
i
gibl
eforvot
ing"
);
else
Syst
em.
out
.pr
int
ln(
"El
i
gibl
eforvot
ing"
);
}
publ
icstat
icvoi
dmai n(St
ringar
gs[
])
{
Mainobj =newMai n();
obj.
checkAge(13);
System.out
.pr
intl
n("
EndOfPr ogr
am")
;
}
}

Exampl
e:t
hrowskeywor
d

publ
i
cclassMai n
{
publ
icintdivision(i
nta,i
ntb)t hrowsAr i
thmet i
cExcept
ion
{
intt=a/ b;
returnt ;
}
publ
icstati
cvoi dmain(Str
ingar gs[]
)
{
Mai nobj =newMai n()
;
try
{
Syst em.out.
print
ln(obj.
divi
si
on(15,0));
}
catch( Arithmeti
cExcept i
one)
{
Syst em.out.
print
ln("Youshouldn'tdivi
denumberbyzer
o")
;
}
}
}
MULTI
THREADI
NG
Javaprovidesbui l
t-i
ns upportformulti
thr
eadedpr ogrammi ng.Multi
thr
eadingisapr ocessof
executi
ngmul ti
plethreadssimultaneousl
y.Athreadisal i
ghtweightsubprocess
,asmal l
estuni
t
ofprocessing.I
tisasepar at
epat hofexecuti
on.Itsharesthememor yareaofprocess.So,in
short
,Multit
hreadingisat echni
quet hatal
lowsapr ogram orapr ocesstoexecutemanyt asks
concurr
ently.
Wecandi videal ongpr ogram i
ntonumberoft hreadsandexecut esthem inparal
l
el.

TheMai
nThr
ead:

Whenoursimpleprogram st
art
sonesi ngl
ethr
eadbegi
nsrunni
ngi
mmedi
atel
y.
Thi
siscal
l
edoursinglemainthread.
Themainthr
eadcreatesautomatical
l
ywhenpr ogr
am i
sst
art
ed.
I
tisver
yimport
antthreadbecauseoft woreas
ons.

1)Fr
om themainthreadotherchi
ldthr
eadwil
lbecreated.
2)Mainthr
eadisall
mostever yti
mestoprunni
nglast
lybecausei
thast
oremoveorshut
down
fewresour
cesaswel l
asfewact i
ons.

Cont
rol
ourmai
nthr
ead:

Act
ual
l
ybycal
l
ingt
hemet
hodcur
rent
Thr
ead(
)ofThr
eadcl
asswecancont
rol
ourmai
nthr
ead.

publ
iccl
assMai n_Thread
{
publ
icstati
cvoidmai n(Str
ingargs[])
{
Threadt=Thr ead.currentThr
ead();
System.out.
pri
ntln("Curr
entthread:"+t)
;
/
/changet henameoft hethread
t.
setName( "
MyThr ead");
System.out.
pri
ntln("Aft
ernamechange:"+t)
;
tr
y
{
for(i
ntn=5;n>0;n- -)
{
System.out.
pri
ntl
n(n);/
/pri
ntnumberwit
hint
erval
of1sec.
Thread.
sleep(1
000) ; //Thr
eadisgoi
ngtosl
eepf or1sec.
}
}
cat
ch(I
nter
ruptedExcept
ione)
{
Syst
em.out.
print
ln(
"Maint
hreadi
nter
rupt
ed"
);
}
}
}
Out
put:

Herefi
rstofal
lwegi
veref
erenceofourcur
rentmai
nsi
ngl
ethr
eadt
otbyt
hreadobj
ectand
cur
rent
Thread()met
hod.

Thenumber5t
o1wi
l
lbepr
intati
nter
val
of1secondduet
osl
eepmet
hod.

Thr
eadwi
l
lgot
osl
eepf
or1
000ms.duet
osl
eepmet
hod

Someoft
hecommonl
yusedmet
hodsf
ort
hreadsar
e:

Met
hod Descr
ipt
ion

st
art
() Thi
smethodst
art
stheexecut
ionofthethreadand
JVM cal
l
sther
un()met
hodont hethread.

Sl
eep(
intmi
l
li
seconds) Thismethodmakest hethreadsleephencet he
thr
ead'sexecut
ionwill
pausef ormi l
l
iseconds
provi
dedandaf t
erthat,agai
nthet hreadstart
s
executi
ng.Thi
shelpinsynchronizati
onoft hethr
eads
.

get
Name(
) I
tret
urnst
henameoft
het
hread.

set
Pri
ori
ty(
intnewpr
ior
it
y) I
tchangest
hepr
ior
it
yoft
het
hread.

yi
eld(
) I
tcausescur
rentt
hreadonhal
tandot
hert
hreadst
o
execut
e.
Thr
eadLi
feCycl
e:

Threadhasmanydi ff
erentst
atethr
oughouti
tsl
i
fe.
1.Newbor nStat
e
2.RunnableState
3.RunningState
4.BlockedState
5.DeadSt at
e
Threadshouldbeinanyonest at
eofaboveanditcanbemovef
rom onest
atet
oanot
herby
dif
ferentmethodsandways .

1
.Newbor
nSt
ate

Whenwecreateathreaditwil
lbei
nNewbor nStat
e.
Thet
hreadi
sjustcr
eatedsti
ll
it
snotrunni
ng.
Wecanmovei tt
orunningmodebyi nvoki
ngthest
art
()met
hodandi
tcanbeki
l
ledbyusi
ng
st
op(
)method.
2.Runnabl
eSt
ate

I
tmeanst
hatt
hreadisnowreadyforrunni
nganditswait
ingt
ogi
vecont
rol
.
Wecanmovecontrolt
oanothert
hreadbyyiel
d()method.

3.Runni
ngSt
ate

I
tmeansthr
eadi
sini
tsexecut
ionmodebecauset
hecont
rolofCPUi
sgi
vent
othatpar
ti
cul
ar
t
hread.

I
tcanbemovei
nthr
eedi
ff
erentsi
tuat
ionsf
rom r
unni
ngmode.
Theseallar
edif
ferentmet
hodswhi
chcanbeapplyonrunningthr
eadandhow t
hest at
eis
changi
ngandhow wecancomei nouror
igi
nalpr
evi
ousstateusi
ngdi
ffer
entmethodsare
showninabovefi
gure.

4.Bl
ockedSt ate
Athr
eadiscal l
edinBlockedSt at
ewhenitisnotal
lowedtoenteringinRunnableStateorRunni
ngState.
I
thappenswhent hr
eadi sinwait
ingmode,suspendedorinsleepingmode.
5.DeadState
Whenat hreadiscompl etedexecuti
ngi
tsrun()methodt
helifecycleofthatpart
iculart
hreadi
send.
Wecanki l
lthreadbyinvokingstop()methodfort
hatpar
ti
cularthreadandsendi ttobeinDeadStat
e

Creati
ngThr ead:
Wecancr eatethreadinj
avawi t
htwodiff
erentways.
1.Ext
endingt heThreadClass.
2.Implement srunnabl
einterface.
1.Ext
endingt heThreadclass:
I
nt hi
smet hodonenor mal classextendst
heinbui
ltcl
asst
hreadandover
ri
dei
tsr
un(
)met
hodwi
tht
he
coderequiredbyt hatpar
ticularthr
ead.

Herewearegoi
ngtoextendclassjava.l
ang.
Thr
ead.So,wecanaccessal
lt
hemet
hodsoft
hreadcl
ass.
Creat
eonecl
asswhichextendsthethreadcl
ass.

Over
ri
det
her
unmet
hodandputl
i
nesofcodei
nsi
det
hreadmet
hodt
hatwi
l
lbeper
for
m byt
hread.
Creat
eanobj
ectofcl
asswhi
chwecr
eat
edwi
thext
endi
ngt
het
hreadcl
assandcal
lt
hest
art(
)met
hod
t
oexecut
ethethr
ead.

ClassMyThreadext
endsThr ead
{
………………..
………………..
}
Sonowwehaveonet hreadnamedMyThr
ead.
-I
mpl ementi
ngtherun()method
publi
cvoidrun()
{ ………
//Thr
eadcodeher e
}

St
art
ingnewThr
ead

MyThr
eadaTh=newMyThr
ead(
);/
/iti
nst
ant
iat
esanewobj
ectofcl
assMyThr
ead

aTh.
star
t()
; /
/invokesr
un(
)met
hod

EX:
1

cl
assMultiext
endsThr ead
{
publi
cvoidr un()
{
System.out.pr
intl
n("
threadi sr
unni
ng..
."
);
}
publi
cstati
cvoi dmai n(St
ringargs
[])
{
Multit1=new Mul t
i(
);
t1.
start
();
}
}
EX:
2

cl
assAext
endsThr
ead

publ
i
cvoi
drun(
)

Syst
em.
out
.pr
int
ln(
"Thr
eadA"
);

f
or(
inti
=1;
i<=5;
i++)

{
Syst
em.
out
.pr
int
ln(
"Fr
om t
hreadAi
="+i
);

Syst
em.
out
.pr
int
ln(
"Exi
tfr
om A"
);

cl
assBext
endsThr
ead

publ
i
cvoi
drun(
)

Syst
em.
out
.pr
int
ln(
"Thr
eadB"
);

f
or(
inti
=1;
i<=5;
i++)

Syst
em.
out
.pr
int
ln(
"Fr
om t
hreadBi
="+i
);

Syst
em.
out
.pr
int
ln(
"Exi
tfr
om B"
);

publ
i
ccl
assThr
ead_Cl
ass

publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs)

newA(
).
star
t()
; /
/cr
eat
ingAcl
asst
hreadobj
ectandcal
l
ingr
unmet
hod

newB(
).
star
t()
; /
/cr
eat
ingBcl
asst
hreadobj
ectandcal
l
ingr
unmet
hod

Syst
em.
out
.pr
int
ln(
"Endofmai
nthr
ead"
);

Output1:
ThreadA
From t
hreadAi
=1
From t
hreadAi
=2
From thr
eadAi =3
From thr
eadAi =4
From thr
eadAi =5
Exitf
rom A
Endofmai nt
hread
ThreadB
From thr
eadBi =1
From thr
eadBi =2
From thr
eadBi =3
From thr
eadBi =4
From thr
eadBi =5
Exitf
rom B

Out
put2:

ThreadA
From thr
eadAi =1
From thr
eadAi =2
Endofmai nt
hread
From thr
eadAi =3
From thr
eadAi =4
ThreadB
From thr
eadAi =5
From thr
eadBi =1
Exitf
rom A
From thr
eadBi =2
From thr
eadBi =3
From thr
eadBi =4
From thr
eadBi =5
Exitf
rom B

Hereyoucanseet hatbot
houtputsaredi
ff
erentt
houghourprogram codeissame.
Ithappensi
nt hr
eadpr ogram becauset
heyarerunni
ngconcurrent
lyonthei
rown.
Threadsarerunningindependentl
yofoneanotherandeachexecuteswheneveri
thasachance.

2.I mplement ingtheRunnableinterf


ace:
I
nt hi
smet hodwehaveonei nter
facenamedr unnableandwei mplementt hisint
erf
acefori
mplementa
thread.
Cr eateonecl asswhichimplement srunnableint
erface.
Over ri
det her un()methodandputsomel ineofcodef orthatparti
cularthread.
Now cr eateanobj ectofinbuil
tthreadclassandcr eateanobj ectofcl assthatimpl
ementsrunnable
i
nt erf
ace.
Givet her eferenceofobjecttothreadobjectbypassi nganar gument( argumentmustbet heobjectof
classwhi chi mplementstherunnableinter
face)whilecr eati
ngat hreadobj ect.
Cal lt
hest art()methodtorunthet hr
ead.
EX: 1
classMul t
iimplementsRunnabl e
{
publ i
cvoidrun()
{
Syst
em.
out
.pr
int
ln(
"thr
eadi
srunni
ng.
..
");
}

publ
i
cstati
cvoidmai n(St
ri
ngargs
[])
{
Multim1 =new Mul
ti
()
;
Threadt1=new Thread(
m1 )
;
t1
.star
t()
;
}
}

EX:
2
publ
i
ccl
assThr
ead_I
nter
face

publ
i
cst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs)

Xx1=newX(
);/
/cl
assobj
ect

Thr
eadxthr
ead=newThr
ead(
x1)
;//
creat
ingt
hreadobj
ectandgi
vi
ngr
efer
enceofcl
assobj
ect
t
othr
eadobject

xt
hread.
star
t()
;

Syst
em.
out
.pr
int
ln(
"Endofmai
nThr
ead"
);

cl
assXi
mpl
ement
sRunnabl
e

publ
i
cvoi
drun(
)

Syst
em.
out
.pr
int
ln(
"I
nsi
deXt
hread"
);

f
or(
inti
=1;
i<=1
0;i
++)

Syst
em.
out
.pr
int
ln(
"Fr
om xt
hreadi
="+i
);

Syst
em.
out
.pr
int
ln(
"Exi
tfr
om X"
);

}
}

Out
put:

Endofmai nThread
I
nsideXthread
From xt
hreadi=1
From xt
hreadi=2
From xt
hreadi=3
From xt
hreadi=4
From xt
hreadi=5
From xt
hreadi=6
From xt
hreadi=7
From xt
hreadi=8
From xt
hreadi=9
From xt
hreadi=1 0
Exitf
rom X

JavaThr
eadPr
ior
it
y:

Eachjavathreadhasitsownpr i
ori
tywhichdeci
destheorderofthr
eadtobeschedule.
Thethreadsofequalpriori
tywi
llbegivensametreat
mentbyjavaschedul
er.Andtheywil
lfol
l
owt
he
FCFS( Fi
rstComeFi r
stServe)al
gorit
hm.
Usercanal sosett
hepr i
ori
tyoft
hreadbyusingthesetPr
ior
it
y()methodasfol
low:

Thr
eadName.
set
Pri
ori
ty(
intNumber
);

Her
ethenumberi
sint
egerval
uebet
ween1t
o10,Her
e1i
smi
nimum pr
ior
it
y10i
smaxi
mum pr
ior
it
y.

TheThr
eadclassdef
inesf
ewpr
ior
it
yconst
ant
s:
MIN_PRI
ORITY=1
NORM_PRIORITY=5
MAX_PRIORI
TY=1 0

I
nanyThr
eadt
hedef
aul
tpr
ior
it
yisNORM_PRI
ORI
TY

I
nmul t
it
hreadi
ngbyass
igni
ngpri
ori
ty,wecanansweraninputasqui
ckl
yaswewant .
Whenevermor et
hanonethr
eadsarereadyt
orunjavasyst
em sel
ectt
hehi
ghestpr
iori
tyt
hreadand
execut
eit

I
fanotherthr
eadofhi
gherpr
ior
it
ycomestherunni
ngt
hreadwi
l
lbepr
eempt
edbyt
hei
ncomi
ngt
hread
andcurrentt
hreadwi
l
lmovetorunnabl
est
ate.

cl
assAext
endsThr
ead
{

publ
icvoi
drun()
{
Syst
em.out.
pri
ntl
n("
Thr
eadAst
rat
ed"
);
for
(i
nti=1 ;i
<=5;i++)
{
System.out.
pri
ntl
n("
\ tFrom ThreadAi
="+i
);
}
System.out.
pri
ntl
n("
Exitfrom A")
;
}
}

cl
assBext endsThr ead
{
publi
cvoi drun()
{
System. out.
print
ln("
ThreadBst rat
ed");
for(i
ntj=1 ;j
<=5;j ++)
{
System.out.pr
intl
n("\tFrom ThreadBj="+j
);
}
System. out.
print
ln("
Exitfrom B");
}
}
publ
icclassThread_Pr ior
it
y
{
publi
cst at
icvoidmai n(St
ring[]args)
{
At hreadA=newA( );
Bt hreadB=newB( );

t
hreadA.
set
Pri
ori
ty(
Thread.
MIN_PRIORITY)
;
t
hreadB.
set
Pri
ori
ty(
thr
eadA.get
Pri
ori
ty(
)+3)
;

Syst
em.out.
pri
ntl
n("
Star
tThr
eadA"
);
t
hreadA.
star
t()
;

Syst
em.out.
pri
ntl
n("
Star
tThr
eadB"
);
t
hreadB.
star
t()
;

Syst
em.
out
.pr
int
ln(
"Endofmai
nThr
ead"
);
}
}

Out
put
:

StartThreadA
StartThreadB
Endofmai nThread
ThreadBst r
ated
From ThreadBj=1
From ThreadBj=2
From ThreadBj=3
From ThreadBj
=4
From ThreadBj
=5
Exi
tfr
om B
Thr
eadAstrated
From ThreadAi
=1
From ThreadAi
=2
From ThreadAi
=3
From ThreadAi
=4
From ThreadAi
=5
Exi
tfr
om A

HereYoucansee thatwestar
tThr
eadAfir
stbutthenalsoThr
eadBcomplet
edit
staskfi
rstbecauseof
hi
gherpri
orit
y.
Butagai
nitsmult
it
hreadi
ngsoweallknowthatoutputmaybevaryeacht
imeyourunthepr ogr
am.

You might also like