Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Java Lab (r19) Pullaiah

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Java Lab (r19) Pullaiah

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 128

JAVAPROGRAMMI

NGLAB

ForB.
TechCSEI
IYear
I
ISemest
er(
R-19)
COURSESTRUCTUREANDSYLLABUS
For

COMPUTERSCI
ENCEANDENGI
NEERI
NG
(
Appl
i
cabl
eforbat
chesadmi
tt
edf
rom 2016-
2017)

JAWAHARLALNEHRUTECHNOLOGI
CALUNI
VERSI
TY:
KAKI
NADA
KAKI
NADA-533003,
Andhr
aPr
adesh,
Indi
a
I
IYear–I
ISemest
er L T P C
0 0 3 2

JAVAPROGRAMMINGLAB
(
JNTUKSyl
labus)

Exercise-1( Basi cs)


a).Wr it
eaJAVApr ogram t odi spl aydef aultv al ueofal lprimiti
v edat at ypeofJAVA
b).Wr it
eaj av apr ogr am thatdi spl ayt her oot sofaquadr aticequat ionax 2+bx=0.Cal culate
thedi scriminateDandbasi ngonv alueofD, descr ibet henat ureofr oot .
c).FiveBi kersCompet einar acesucht hatt heydr iveatac onstantspeedwhi chmayorma
y
notbet hesameast heot her .Toqual if
yt her ace,t hespeedofar acermustbe
mor et hant heav er agespeedofal l5r acer s.Takeasi nputt hespeedofeachr acer
andpr i
ntbackt hespeedofqual i
f yingr acer s.
d)Wr i
teacasest udyonpubl icst at i
cv oidmai n( 250wor ds)
Exercise-2( Oper ations, Expressi ons, Cont rol-flow, Stri
ngs)
a).Wr it
eaJAVApr ogram t osear chf oranel ementi nagi venlistofel ement susi ngbi nary
searchmechani sm.
b).Wr it
eaJAVApr ogram t osor tf oranel ementi nagi venl i
stofel ement susingbubbl e
sort
(c).Wr i
teaJAVApr ogram t os or tf oranel ementi nagi venlistofel ement susing
mer gesor t
.(d)Wr i
teaJAVApr ogr am usi ngSt r i
ngBuf fertodel ete,remov echaract er.
Exercise-3( Class, Obj ects)
a).Wr it
eaJAVApr ogram t oimpl ementcl assmechani sm.–Cr eateacl ass,met hodsand
i
nv oket hem i nsidemai nmet hod.
b).Wr it
eaJAVApr ogram t oimpl ementconst ruc t
or .
Exercise-4( Met hods)
a).Wr it
eaJAVApr ogram t oimpl ementconst ruc t
orov erloading.
b).Wr it
eaJAVApr ogram i mplementmet hodov er loadi ng.
Exercise-5( Inher itance)
a).Wr it
eaJAVApr ogram t oimpl ementSi ngl eI nher it
ance
b).Wr it
eaJAVApr ogram t oimpl ementmul tilevel Inher i
tance
c).Wr it
eaj av apr ogr am forabst ractcl asst of indar easofdi ff
er entshapes
Exercise-6( Inher itance-Cont i
nued)
a).Wr it
eaJAVApr ogram gi veex ampl ef or“ super ”key wor d.
b).Wr it
eaJAVApr ogram t oimpl ementI nter face.Whatki ndofI nheritancecanbeachi eved?
Exercise-7( Ex cept ion)
a).Wr i
teaJAVApr ogr am thatdescr i
besex cept ionhandl ingmechani sm
b).Wr i
teaJAVApr ogr am Ill
ust ratingMul ti
pl ecat chcl auses
Exercise–8( Runt imePol ymor phi sm)
a).Wr it
eaJAVApr ogram t hati mpl ement sRunt imepol ymor phism
b).Wr it
eaCasest udyonr unt imepol ymor phi sm, inher i
tancet hatimpl ementsi nabov e
problem
Exercise–9( Userdef inedEx cept ion)
a).Wr it
eaJAVApr ogram f orcr eat i
onofI ll
ust rat ing
throwb) .Wr i
teaJAVApr ogr am f orcr eationof
Il
lustratingfinally
c).Wr it
eaJAVApr ogram f orcr eat ionofJav aBui lt-i
n
Except ionsd) .Wr iteaJAVApr ogr am f orcr eat ionofUser
Def i
nedEx ception
Exercise–10( Thr eads)
a).Wr it
eaJAVApr ogram t hatcr eat est hreadsbyex tendi ngThr eadcl ass.Fir
stt hread
display
“GoodMor ning“ever
y1sec, t
hesecondthreaddisplays“
Hell
o“ever
y2seconds
andt hethi
rddispl
ay“Welcome”every3seconds,(Repeatthesameby
i
mpl ementingRunnable)b)
.Wr i
teaprogr
am il
lustr
atingi
sAli
veandjoi
n()
c).Wr i
teaProgram i
ll
ustr
ati
ngDaemonThr eads.
Exerci
se-11( Thr eadscont inuity )
a).Wri
teaJAVApr ogr am Pr oducerConsumerPr oblem
b).Wri
teacasest udyont hreadSy nchr onizationaf tersolvi
ngtheabov eproducer
consumerpr oblem
Exerci
se–12( Pack ages)
a).Writ
eaJAVApr ogram illustrat ecl asspat h
b).Writ
eacasest udyoni ncl udi ngi ncl asspat hiny ourosenv i
ronmentofy our
package.c).WriteaJAVApr ogr am t hati mpor tanduset hedefinedy ourpackage
i
nt heprevi
ousPr oblem
Exerci
se-13( Appl et )
a).Wri
teaJAVApr ogr am topai ntlikepai ntbr ushinappl et.
b)Wr i
teaJAVApr ogr am todi spl ayanal ogcl ockusi ngApplet.
c).Wri
teaJAVApr ogram tocr eat edi fferentshapesandf i
l
lcolorsusi ngApplet.
Exerci
se-14( Ev entHandl ing)
a).Wri
teaJAVApr ogr am thatdi splayt hexandyposi ti
onofthecur sormov ement
using
Mouse.
b).Wri
teaJAVApr ogr am thati dent ifi
eskey -upkey -
downev entuserent er
ingtexti
n
a
Applet.
Exerci
se-15( Swi ngs)
a).Wri
teaJAVApr ogr amtobui ldaCal culatori nSwi ngs
b).Writ
eaJAVApr ogram todi splayt hedi gital watchi nswingtut or
ial.
Exerci
se–16( Swi ngs-Cont inued)
a).Writ
eaJAVApr ogram thatt ocr eat easi nglebal lbouncinginsidea
JPanel.b)
.Wr i
teaJAVApr ogr am JTr eeasdi splayi
ngar ealt
reeupsi de
down
JAVAPROGRAMMI NG
LABCycl
e-IPr
ogr
ams
Exer
cise-1(
Basi
cs)

a).WriteaJAVApr ogram todi spl


aydef aultvalueofallpri
miti
vedat aty
peofJAVA
b).Writeajav aprogram thatdisplaytherootsofaquadr ati
cequationax2+bx=0.Cal
culat
e
thediscri
mi nateDandbas ingonv alueofD, describethenatureofroot.
c).Fiv
eBi kersCompet einar acesucht hattheydr iv
eataconst antspeedwhichmayormay
notbet hesameast heot her.Toqual i
fyther ace,thespeedofar acermustbemor ethanthe
averagespeedofal l
5r acers.Takeasi nputt hespeedofeachr acerandpr i
ntbackthe
speedofqual i
fyi
ngracers.
d)Wr i
teacasest udyonpubl icstati
cv oidmai n(250wor ds)
Exer
cise-2(
Oper
ati
ons,
Expr
essi
ons,
Cont
rol
-f
low,
Str
ings)
a).Writ
eaJAVAprogram tosearchf oranelementinagi v
enl istofelementsusi
ngbinar
y
searchmechani
sm.
b).Writ
eaJAVAprogram tosortforanelementinagi venlistofelement susi
ngbubblesor
t
(c).Wri
teaJAVAprogram t
osor tforanelementinagi venlistofelementsusingmergesor
t.
(d)Writ
eaJAVAprogram usingStringBuff
ertodelete,
remov echaracter
.
Exer
cise-3(
Class,
Obj
ect
s)
a)
.Writ
eaJAVApr ogr
am t
oimplementcl
assmechanism.–Cr
eat
eacl
ass
,met
hodsand
i
nvokethem i
nsi
demainmethod.
b)
.Writ
eaJAVApr ogr
am t
oimplementconst
ruct
or.
Exer
cise-4(
Met
hods)
a)
.Wr
it
eaJAVApr
ogr
am t
oimplementconst
ruct
orover
loadi
ng.
b)
.Wr
it
eaJAVApr
ogr
am i
mplementmethodoverl
oadi
ng.
Exer
cise-5(
Inher
it
ance)
a)
.Wr
it
eaJAVAprogr
am toi
mplementSingleInher
itance
b)
.Wr
it
eaJAVAprogr
am toi
mplementmul t
ilevelI
nherit
ance
c)
.Wr
it
eaj
avapr
ogram f
orabst
ractc
lasstof i
ndareasofdi f
fer
ents
hapes
Exerci
se-6(
Inher
it
ance-Cont i
nued)
a).Wri
teaJAVAprogram giv
eex amplef
or“super”k
eyword.
b).Wri
teaJAVAprogram toimplementI
nter
face.Whatki
ndofI
nher
it
anc
ecanbeachi
eved?
Exerci
se-7(Ex
cepti
on)
a).
Wr i
teaJAVAprogr
am t
hatdescri
besexcept
ionhandl
ingmechani
sm
b).
Wr i
teaJAVAprogr
am I
ll
ust
rati
ngMulti
plecatchcl
auses
Exer
cise–8(
Runt
imePol
ymor
phi
sm)
a)
.Wri
teaJAVAprogr
am t
hati
mpl
ementsRunti
mepolymorphism
b)
.Wri
teaCasest
udyonrunti
mepol
ymorphi
sm,inher
it
ancethati
mpl
ement
sinabov
e
pr
obl
em
Exer
cise–9(
Userdef
inedEx
cept
ion)
a).Writ
eaJAVAprogram f
orcreationofIl
lust
rat
ing
throwb).Wri
teaJAVAprogram forcreat
ionof
I
llust
rat
ingf
inal
l
y
c).Writ
eaJAVAprogram f
orcreati
onofJav aBuilt
-i
nEx
ceptions
d).Wri
teaJAVAprogr
am forcr
eat i
onofUserDef i
nedExcept
ion
Exer
cise–10(
Pack
ages)
a)
.Wr
it
eaJAVApr
ogr
am i
ll
ust
rat
ecl
asspat
h
b)
.Wr
iteacasest
udyoni
ncludi
ngincl
asspat
hinyourosenvironmentofy
ourpackage.
c)
.Wr
it
eaJAVAprogr
am t
hatimpor
tanduset
hedef
inedyourpackagei
ntheprevi
ousPr
obl
em
JAVAPROGRAMMI NG
LABCycl
e-I
IPr
ogr
ams

Exer
cise–11(
Thr
eads)

a).Writ
eaJAVApr ogr am thatcreat
esthr
eadsbyex tendi
ngThreadclass.Fi
rstt
hread
displ
ay“GoodMor ning“ every1sec, t
hesecondthreaddispl
ays“Hel
lo“every2secondsand
thethi
rddisplay“Wel come”ev er
y3seconds,(Repeatthesamebyi mplementi
ngRunnable)
b).Writ
eapr ogram illustr
at i
ngisAli
veandjoi
n()
c).Wri
teaPr ogram illustr
at i
ngDaemonThr eads.

Exer
cise-12(
Thr
eadscont
inui
ty)

a)
.Wr
it
eaJAVAprogr
am Pr
oducerConsumerProbl
em
b)
.Wr
it
eacasest
udyonthr
eadSynchr
onizat
ionaft
ersol
vi
ngt
heabov
epr
oducerconsumer
pr
obl
em

Exer
cise-13(
Appl
et)

a).Wr
it
eaJAVAprogr
am topaintlik
epai ntbr
ushi nappl
et.
b)Writ
eaJAVAprogr
am todisplayanalogclockusingApplet.
c).Wri
teaJAVApr
ogram t
ocr eatedif
ferentshapesandfil
lcolor
sus
ingAppl
et.

Exer
cise-14(
EventHandl
i
ng)

a)
.Wri
teaJAVApr
ogr
am t
hatdi
spl
aythexandyposit
ionoft
hecursormovementusi
ng
Mouse.
b)
.Wri
teaJAVApr
ogr
am t
hati
dent
if
ieskey
-upkey
-downeventus
erenter
ingtex
tinaAppl
et.

Exer
cise-15(
Swi
ngs)

a)
.Wr
it
eaJAVAprogram tobui
ldaCal
cul
atori
nSwings
b)
.Wri
teaJAVAprogram t
odispl
ayt
hedigi
tal
wat
chi nswi
ngt
utor
ial
.

Exer
cise–16(
Swi
ngs-Cont
inued)

a)
.Wr
it
eaJAVApr
ogr
am thatt
ocreat
easingl
eballbounci
ngins
ideaJPanel
.
b)
.Wr
it
eaJAVApr
ogr
am JTreeasdis
play
ingareal
treeupsi
dedown
CONTENTS

S.
n Descr
ipt
i PageNo
1o Ex
erci
se-
1Basi
cs on 1
a)
Dis
play
ingdef
aul
tval
ueofal
lpr
imi
ti
vedat
aty
pes -
1
4
b)
Root
sofaquadr
ati
cequat
ion 2
c)
BikeRac
e 3
d)
Acasest
udyonpubl
i
cst
ati
cvoi
dmai
n 4
2 Exer
cise-2(
Oper
ati
ons,
Expr
essi
ons,
Cont
rol
-f
low,
Str
ings) 5
a)
Impl
ement
ati
onofBi
nar
ysear
chmechani
sm -
5
8
b)
Bubbl
esor
t 6
c)
Mer
gesor
t 7
d)
Impl
ement
ingSt
ri
ngBuf
fer 8
3 Exer
cise-3(
Class,
Obj
ect
s) 9-
a)
Impl
ement
ingCl
ass&Obj
ect
s 19
1
b)
Impl
ement
ingConst
ruct
or 1
4 Exer
cise-4(
Met
hods) 1
12-
13
a)Const
ruct
orOv
erl
oadi
ng 1
b)Met
hodOv
erl
oadi
ng 2
1
5 Exer
cise-5(
Inher
it
ance) 3
14-
16
a)
Impl
ement
ingSi
ngl
eInher
it
ance 1
b)
Mul
til
evel
Inher
it
ance 4
1
c)
Abst
ractCl
ass 5
1
6 Exer
cise-6(
Inher
it
ance-Cont
inued) 6
17-
21
a)
superkey
wor
dimpl
ement
ati
on 1
b)I
mpl
ement
ingi
nter
face 7
1
7 Exer
cise-7(
Except
ion) 9
22-
23
a)Ex
cept
ionhandl
i
ngmechani
sm 2
b)I
l
lust
rat
ingmul
ti
plecat
chc
lass
es 2
2
8 Exer
cise–8(
Runt
imePol
ymor
phi
sm) 3
24-
25
a)
Runt
imePol
ymor
phi
sm 2
b)
Casest
udyonRunt
imePol
ymor
phi
sm 4
2
9 Exer
cise–9(
Userdef
inedEx
cept
ion) 5
26-
31
a)
creat
ionofi
l
lust
rat
ingt
hrow 2
b)
creat
ionofi
l
lust
rat
ingf
inal
ly 6
2
c)
creat
ionofJav
aBui
l
t-i
n-Ex
cept
ions 7
2
d)
creat
ionofUserDef
inedEx
cept
ion 8
3
10 Exer
cise–10(
Thr
eads) 1
32-
38
a)
Ext
endi
ngThr
eadcl
ass 3
(
b)I
mpl
ement
ingi
sAl
i
ve(
)andj
oin(
) 2
3
6
c)I
mpl
ement
ati
onofDaemonThr
eads 3
8
i
11 Exer
cise-11(
Thr
eadscont
inui
ty) 39-
41
a)
Producer
-Cons
umerpr
obl
em 3
b)
Casest
udyont
hreadsy
nchr
oni
zat
ion 9
4
12 Exer
cise–12(
Pack
ages) 1
42-
45
a)I
l
lust
rat
ionofc
lasspat
h 4
b)Acasest
udyoni
ncl
udi
ngi
ncl
asspat
hinosenv
ironment 2
4
c)Cr
eat
ingandi
mpor
ti
ngapackage 3
4
13 Exer
cise-13(
Appl
et) 5
46-
49
a)Pai
ntl
i
kePai
ntBr
ushi
nAppl
et 4
b)Di
spl
ayAnal
ogCl
ockus
ingAppl
et 6
4
c)Di
spl
ayAnal
ogCl
ockus
ingAppl
et 7
4
14 Exer
cise-14(
EventHandl
i
ng) 9
50-
52
a)Cur
sormov
ementusi
ngmouse 5
b)Key
-upandKey
-downev
ent 0
5
15 Exer
cise-15(
Swi
ngs) 2
53-
55
a)Bui
l
dingacal
cul
atori
nswi
ngs 5
b)Di
spl
ayi
ngdi
git
alwat
ch 3
5
16 Exer
cise–16(
Swi
ngs-Cont
inued) 5
56-
58
a)
Bal
lbounc
ingi
nsi
deaJPanel 5
b)
Dis
play
ingar
eal
tree 6
5
8
i
i
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

Ex
erci
se-1(
Basi
cs)
a)Di
spl
ayi
ngdef
aul
tval
ueofal
lpr
imi
ti
vedat
a
t
ypes

Ai
m:Towr
it
eaJAVApr
ogr
am t
odi
spl
aydef
aul
tval
ueofal
lpr
imi
ti
vedat
aty
peofJAVA

Progr am:
classdef aul
tdemo
{
staticby teb;
staticshor ts;
staticinti;
staticlongl ;
staticfloatf;
staticdoubl ed;
staticcharc;
staticbool eanbl;
publ i
cst ati
cvoidmain(Str
ing[]args)
{
Sy stem.out
.pri
ntl
n("
Thedef aultval
uesofpr
imi
ti
vedat
aty
pesar
e:"
);
Sy stem.out
.pri
ntl
n("
By t
e: "
+b) ;
Sy stem.out
.pri
ntl
n("
Shor t:"+s);
Sy stem.out
.pri
ntl
n("
Int:"+i
);
Sy stem.out
.pri
ntl
n("
Long: "+l);
Sy stem.out
.pri
ntl
n("
Float:"+f);
Sy stem.out
.pri
ntl
n("
Doubl e: "
+d);
Sy stem.out
.pri
ntl
n("
Char: "+c);
Sy stem.out
.pri
ntl
n("
Bool ean: "
+bl);
}
}
Out put :
Thedef aultvaluesofpr i
miti
vedatat ypesar e:
By t
e: 0
Shor t:0
Int:0
Long: 0
Float: 0.0
Doubl e: 0.0
Char:
Bool ean: fal
se
Page1
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
b)Root
sofaquadr
ati
cequat
ion

Ai
m:Towri
teaj
avapr
ogram t
hatdi
spl
aytherootsofaquadrat
icequat
ionax
2+bx
=0.Cal
cul
atet
he
di
scr
imi
nat
eDandbasi
ngonv al
ueofD,desc
ribethenat
ureofroot
.

Pr
ogram:
i
mportjav
a.ut i
l.
*;
cl
assquadraticdemo
{
publ
icst ati
cv oidmai n(String[ ]ar gs)
{
i
nta, b,c;
doubler1, r2, D;
Scanners=newScanner (System. i
n);
System.out .printl
n("Gi venquadr aticequation:ax
^2+bx+c")
;
System.out .print(
"Ent era: ");
a=s. nextI
nt ();
System.out .print(
"Ent erb: ");
b=s. nextI
nt ( )
;
System.out .print(
"Ent erc: ");
c=s. nextI
nt ();
D=b*b-4*a*c;
i
f(D>0)
{
Sy st em.out .println("Rootsar erealandunequal
")
;
r1=(-b+Mat h.sqr t(
D))/(2*a)
;r2=( -
b-
Mat h.sqrt(D) )
/( 2*a) ;
Sy st em.out .println("Fir
strootis:"
+r1);
Sy st em.out .println("Secondr ootis:"
+r2);
}
elseif(D==0)
{
Syst em. out.println("Root sarerealandequal"
);
r1=( -b+Mat h.sqr t(D) )
/(2*a);
Syst em. out.println("Root :
"+r1);
}
el
se
{
Sy
stem.
out
.pr
int
ln(
"Root
sar
eimagi
nar
y")
;
}
}
}

Output:
Givenquadraticequati
on:
ax^2+bx+c
Entera:
2
Enterb:
3
Enterc:
1
Rootsarereal andunequal
Fi
rstrooti
s:-0.
5
Secondrooti s
:-1.
0
Page2
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

c)Bi
keRace

Aim: Fi
veBi
ker
sCompet ei naracesuchthatt
heydriveatacons t
antspeedwhichmayormaynot
bet hesameastheother.Toquali
fyther
ace,thespeedofar acermustbemoret hant
heaverage
speedofall5r
acers.Takeasinputthespeedofeachr acerandpri
ntbackthespeedofqual
if
ying
racers.

Pr
ogram:
i
mportjava.
util
.*;
cl
assracedemo
{
publi
cstat i
cv oi
dmai n(Stri
ng[]ar gs)
{
fl
oats1, s2,s3,s4,s5,
av erage;
Scanners=newScanner (Sy stem.i
n);
Sy stem.out.print
ln("Enterspeedoff ir
strac er :
")
;
s1=s. nextFloat();
Sy stem.out.print
ln("Enterspeedofsecondr acer:"
);
s2=s. nextFloat();
Sy stem.out.print
ln("Enterspeedoft hir
dr acer :
");
s3=s. nextFloat();
Sy stem.out.print
ln("Enterspeedoff ourthr acer:"
);
s4=s. nextFloat();
Sy stem.out.print
ln("Enterspeedoff if
thrac er :
")
;
s5=s. nextFloat();
aver age=(s1+s2+s3+s4+s5) / 5;
if
(s 1>average)
Sy stem.out.print
ln("Fi
rstraceri squal
ifyracer :"
);
elsei f
(s2>av erage)
Sy stem.out.print
ln("Secondr acerisqualifyr acer:
")
;
elsei f
(s3>av erage)
Sy stem.out.print
ln("Thirdrac erisquali
fyr acer :
")
;
elsei f
(s4>av erage)
Sy stem.out.print
ln("Fourthr acerisqualif
yr acer:
")
;
elsei f
(s5>av erage)
Sy stem.out.print
ln("Fi
fthraceri squal
ifyracer :"
);
}
}

Output:
Enterspeedoffir
stracer :
4.
5
Enterspeedofsecondr ac er:
6.
7
Enterspeedofthir
dr ac er:
3.
8
Enterspeedoffourthr acer :
5.
3
Enterspeedoffif
thracer :
4.
9
Secondr aceri
squalifyr acer:
Page3
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
d)Acase
st
udy

Ai
m:Acasest
udyonpubl
i
cst
ati
cvoi
dmai
n(250wor
ds)

Casestudy:
Thepr ogram st r
uctureofasi mpl ej avapr ogram i
sgi v enbelowwithdif
ferentsteps
St
ep-1:Cli
ckst art+runandt hent y penot epadinr undi alogboxandcli
ckOK.I tdi splaysNotepad.
St
ep-2:I
nr undi al
ogboxt y
pecmdandcl i
ckOK.I tdisplay scommandprompt .
St
ep-3:Typet hefollowingpr ogr am i nt heNotepadandsav etheprogr
am as“ ex ampl e.
jav
a”ina
currentwor kingdirect ory.
classex ampl e
{
publicstaticv oidmai n(Str
ingargs[])
{
System. out.pri
nt l
n(“Welcome” );
}
}
St
ep-4(Compi lati
on) :Tocompi l
et hepr ogram typet hef oll
owi
ngincurrentwor kingdi r
ector
y
andt hencl ickent er
.
c:\
xxxx>j avacex ampl e.
j
ava
St
ep-5(Execut i
on):Tor unt hepr ogr am t ypethefollowi ngincur
rentworkingdirect oryand
t
hencl i
ckent er.
c:\
xxxx>j avaex ampl e

Ex
planati
on:
 Generallythefil
enameandcl assnameshoul dbesame.I fitisnotsamet henthejavafil
ecan
becompi ledbutitcannotbeex ecuted.Thati swhenex ecut i
oni tgivest hefol
l
owi ngerror
Ex cepti
oni nthread" mai n"java.l
ang.NoCl ass DefFoundEr ror:ex
I n“publicstat
icvoidmai n(Stringar gs[]
) ”st
atement
 publ icisanaccessspec ifi
er.Ifaclassi svisibletoal lclassest henpubl i
cisused
 mai n()mustbedec laredaspubl i
csi nceitmustbecal ledbyout sideofitsclass.
 Thekey wordstati
cal lowsmai n()tobecal ledwi thoutcr eati
ngobj ectoftheclass.
 Thekey wordvoidrepr esent sthatmai n()doesnotr eturnav alue.
 Themai nmet hodcont ainsonepar amet erSt ringargs[].
 Wecansendsomei nputv alues( argument s)atr unt i
met otheSt ringargs[
]oft hemain
met hod.Thesear gument sarecal l
edcommandl i
near gument s.Thesecommandl i
ne
argument sar epassedatt hecommandpr ompt .
I nSystem. out.
pri
ntln("
Wel come" )
;statement
 Sy stem isapr edefinedcl asst hatpr ovi
desac cesstot hesy stem.
 outi stheoutputstream.
 pr i
nt l
n()methoddi spl ayt heout puti ndif
ferentl i
nes.Ifweusepr int()methoditdispl
aythe
outputi nthesamel ine
Page4
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

Ex
erci
se-2(
Oper
ati
ons,
Expr
essi
ons,
Cont
rol
-f
low,
Str
ings)
a)I
mpl
ement
ati
onofBi
nar
ysear
ch
mechani
sm
Aim:Towr
it
eaJAVApr
ogr
am t
osear
chf
oranel
ementi
nagi
venl
istofel
ement
susi
ngbi
nar
y
sear
chmechani
sm

Progr
am:
i
mpor tj
ava.uti
l.Scanner ;
cl
assbinarysear chdemo
{
publi
cstati
cv oidmai n(Stringar gs[])
{
i
ntn, i
, num, fi
rst ,
last,
mi ddle;
i
nta[] =newi nt[20];
Scanners=newScanner (Syst
em. in)
;
Sy stem. out.println(
"Entertotalnumberofelements:"
);
n=s. nex tI
nt (
);
Sy stem. out.println(
"Enterelement sinsor
tedorder:
")
;
for(i =0; i<n; i
++)
a[i]=s. nex tI
nt();
Sy stem. out.println(
"Enterthesear chval
ue:"
);
num =s. nextInt();
fi
rst=0;
l
ast=n-1;
mi ddle=( fi
rst+l ast)/2;
whi l
e(f irst<=l ast)
{
if(a[mi ddle]<num )
fir
st=mi ddle+1;
elsei f(a[ middle]==num )
{
Sy stem.out.pri
ntl
n("numberfound")
;
br eak;
}
el
se
{
l
ast=mi
ddl
e-1;
}

mi
ddl
e=(
fi
rst+l
ast
)/2;
}
i
f(fi
rst>last)
Syst
em.out.
pri
ntl
n("Numberi
snotf
ound"
);
}
}

Out
put:
Ent
ertotal
numberofel
ement
s:
5
Ent
erelement
s:
24689
Ent
erthesear
chv
alue:
8
numberfound

Page5
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

b)Bubbl
esor
t
Ai
m:Towr
it
eaJAVApr
ogr
am t
osor
tforanel
ementi
nagi
venl
i
stofel
ement
susi
ngbubbl
esor
t

Pr
ogram:
i
mportjava.ut
il.Scanner ;
cl
assbubbledemo
{
publi
cst aticv oidmai n( Str
ingar gs[]
)
{
intn, i
,j,temp;
inta[] =newi nt[20];
Scanners=newScanner (System.in);
Sy stem. out.print l
n("Entert otalnumberofelement
s:"
);
n=s. nex tI
nt();
Sy stem. out.print l
n("Enterel ement s:"
);
for( i=0; i
<n; i
++)
a[ i]=s. nex t
Int();
for (i=0;i<n;
i++)
{
f or
(j
=0; j<n-1;j++)
{
if(a[j
]>a[j+1] )
{
temp=a[ j
];
a[j]
=a[j+1];
a[j+1]=temp;
}
}
}
Sy stem. out .
pr i
nt l
n("Thesor t
edel ementsar
e:"
);
for( i
=0;i<n;i
++)
Sy stem. out .
pr i
nt ("
\t"+a[i]);
}
}

Output
:
Ent
ertotalnumberofel
ement
s:
10
Ent
erelement s:
3257689140
Thesortedelement
sare:
0 1 2 3 4 5 6 7 8 9
Page6
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
c)Mer
gesor
t:
Ai
m:Towr
it
eaJAVApr
ogr
am t
osor
tforanel
ementi
nagi
venl
i
stofel
ement
susi
ngmer
gesor
t
Program:
i
mpor tjava.ut
il
.*;
cl
assmer gedemo
{
publi
cstat i
cv oidmai n( Str
ingar gs[]
)
{
intn1,n2, i
,j
,k;
inta[]=newi nt[20];
intb[]=newi nt[20];
intc[]=newi nt[20];
Scanners=newScanner (
Sy stem.i
n);
Sy stem. out.println("
Ent ernumberofel ementsinfi
rstar
ray:
");
n1=s. nex tInt();
Sy stem. out.print l
n("Entersortedelementsoffi
rstarr
ay:
");
for( i=0; i<n1; i
++)
a[i]=s. nex tI
nt();
Sy stem. out.print l
n("Enternumberofel ementsinsecondarray:
")
;
n2=s. nex tInt();
Sy stem. out.print l
n("Entersortedelementsofsecondarray:
");
for( j=0; j<n2; j
++)
b[j]=s. nex tI
nt();
i=0;
j=0;
k=0;
whi l
e((i<n1)&&( j<n2) )
{
if(
a[i]>b[ j
])
c[k++]=b[ j
++];
else
c[k++]=a[ i
++];
}
whi l
e(i<n1)
c[k++]=a[ i++];
whi l
e(j<n2)
c[k++]=b[ j++];
Sy stem. out.println("
Af t
ermer gingt
heelementsare:\
n")
;
for(i=0; i<( n1+n2) ;
i++)
Sy stem. out.print("\t
"+c[i]
);
}
}
Output:
Enternumberofel ement si nf i
rstarray:
6
Enterelementsoff i
rstar ray:
8912131518
Enternumberofel ement si nsec ondar r
ay:
5
Enterelementsofsecondar ray:
67101120
Aftermer gi
ngt heelement sar e:
6 7 8 9 10 11 12 13 15 18 20
Page7
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

d)I
mpl
ement
ingSt
ri
ngBuf
fer
Ai
m:Towr
it
eaJAVApr
ogr
am usi
ngSt
ri
ngBuf
fert
odel
ete,
remov
echar
act
er

Pr
ogram:
cl
assstri
ngbuffer
demo
{
publ
icstati
cv oidmai n(Str
ing[]ar
gs)
{
Stri
ngBuf fersb1=newSt ri
ngBuf
fer
("Hel
loWorl
d");
sb1.delete(0,6);
System. out.printl
n(sb1);
Stri
ngBuf fersb2=newSt ri
ngBuf
fer
("SomeContent
");
System. out.printl
n(sb2);
sb2.delete(0,sb2. l
ength()
);
System. out.printl
n(sb2);
Stri
ngBuf fersb3=newSt ri
ngBuf
fer
("Hel
loWorl
d");
sb3.deleteChar At(0);
System. out.printl
n(sb3);
}
}

Out
put:
Worl
d
SomeCont
ent

el
l
oWor
ld
Page8
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

Exer
cise-3(Cl
ass,Obj
ect
s)
a)Impl
ementingClass&Obj
ect
s
Aim:Towrit
eaJAVAprogr
am t
oimpl
ementcl
assmechani
sm.–Cr
eat
eacl
ass,
met
hodsandi
nvoke
them i
nsi
demai
nmethod
Pr
ograms:
1.
noret
ur ntypeandwi thoutparameter
-l
ist
:
cl
assA
{
intl=10, b=20;
v oiddispl ay()
{
Sy stem.out.
pri
ntln(
l)
;
Sy stem.out.
pri
ntln(
b);
}
}
cl
assmet hoddemo
{
publi
cst aticvoidmain(Stri
ngargs[
])
{
Aa1=newA( );
a1. di
splay()
;
}
}
Output
:
10
20

2.noreturntypeandwi thparamet er
-l
ist
:
cl
assA
{
voiddisplay(intl
,i
ntb)
{
System. out.
print
ln(l
);
System. out.
print
ln(b)
;
}
}
cl
assmet hoddemo
{
publicstati
cv oidmai n(Str
ingargs[
])
{
Aa1=newA( )
;
a1.display(
10,20);
}
}
Output:
10
20

3.r
etur
nty
peandwi
thoutpar
amet
er-
li
st
cl
assA
{
i
ntl
=10,
b=20;

Page9
IIB.TechIISem Jav
aLabManual (R19) Preparedby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
intar
ea()
{
retur
nl*
b;
}
}
classmet hoddemo
{
publ
icstat
icv
oidmain(Stri
ngargs[]
)
{
Aa1=newA( )
;intr=a1.ar
ea()
;
System.
out.
pri
ntln(
"Theareais:"
+r)
;
}
}
Out put:
Thear eais:
200

4.
returnty
peandwi thparameter-l
i
st:
cl
assA
{
i
ntarea(intl,
intb)
{
returnl*b;
}
}
cl
assmet hoddemo
{
publ
icst at
icv oi
dmai n(Str
ingargs[]
)
{
Aa1=newA( )
;
i
ntr =a1.area(10,
20);
Sy st
em. out.pr
intl
n(“
Thear eais:
”+r
);
}
}
Output:
Thear eai
s:200
Page10
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
b)I
mpl
ement
ingConst
ruct
or
Aim:TowriteaJAVAprogr
am t
oimpl
ementconst
ruct
or
Progr
ams:
(i
)Aconstr
uctorwi
thnopar
ameter
s:
cl
assA
{
intl
,
b;
A()
{
l
=10;
b=20;
}

i
ntar
ea()
{
ret
urnl
*b;
}
}
cl
assconst
ruct
ordemo
{
publ
i
cstaticv
oidmain(Str
ingargs[
])
{
Aa1=newA( );
intr=a1.
area()
;
System.
out.
pri
ntl
n("Theareais:"
+r)
;

}
}
Output
:
Theareais:
200
(i
i
)Aconstructorwi t
hparameters
cl
assA
{
i
ntl,
b;
A(i
ntu,intv)
{
l
=u;
b=v;
}
intarea()
{
returnl*b;
}
}
cl
assconstructordemo
{
publi
cst ati
cv oi
dmain(St
ringargs[]
)
{
Aa1=newA( 10,
20);
intr=a1.area()
;
Sy stem.out.
pri
ntl
n("
Thear eais:"+r)
;
}
}
Output
: Thear
eai
s:200
Page11
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
Ex
erci
se-4(Methods)
a)Const
ruct
orOverl
oadi
ng
Ai
m:Towr
it
eaJAVApr
ogr
am t
oimpl
ementconst
ruct
orov
erl
oadi
ng

Pr
ogr
am:

cl
assA
{
intl
,
b;
A()
{
l=10;
b=20;
}
A(
intu,i
ntv)
{
l=u;
b=v ;
}
i
ntarea()
{
returnl
*b;
}
}
cl
assover
constructdemo
{
publi
cstaticvoidmai n(Stri
ngargs[]
)
{
Aa1=newA( );i
ntr 1=a1.
area();
System. out
.pri
nt l
n("Theareais:"+r
1);
Aa2=newA( 30,40);
intr2=a2.ar
ea( )
;
System. out
.pri
nt l
n("Theareais:"+r
2);
}
}

Output
:
Theareai
s:200
Theareai
s:1200
Page12
I
IB.
TechI
ISem CSEJav
aLabManual
(R16) Pr
epar
edby
:Dr
.Md.Umark
han,
KHI
T,Gunt
ur

b)Met
hodOv
erl
oadi
ng

Ai
m:Towr
it
eaJAVApr
ogr
am i
mpl
ementmet
hodov
erl
oadi
ng

Pr
ogr
am:

cl
assA
{
i
ntl=10,
b=20;
i
ntarea(
)
{
r
etur
nl *
b;
}
i
ntarea(
intl
,
intb)
{
r
etur
nl*b;
}
}
cl
assov
ermethoddemo
{
publ
icstati
cvoidmai n(Str
ingar
gs[])
{
Aa1=newA( )
;intr1=a1.
area(
);
Syst
em.out.pri
ntln(
"Theareais:"
+r1)
;
i
ntr2=a1.ar
ea(5,20);
Syst
em.out.pri
ntln(
"Theareais:
"+r2)
;
}
}

Output
:
Theareai
s:200
Theareai
s:100
Page13
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
Exer
cise-5(I
nheri
tance)
a)
Impl
ementingSi
ngleInheri
tance

Ai
m:Towr
it
eaJAVApr
ogr
am t
oimpl
ementSi
ngl
eInher
it
ance

Pr
ogr
am:

cl
assA
{
A(
)
{
Sy
stem.
out
.pr
int
ln(
"I
nsi
deA'
sConst
ruct
or"
);
}
}

cl
assBext
endsA
{
B(
)
{
Syst
em.
out
.pr
int
ln(
"I
nsi
deB'
sConst
ruct
or"
);
}
}

cl
asssingl
edemo
{
publi
cstat
icv
oidmai
n(St
ri
ngar
gs[
])
{
Bb1=newB()
;
}
}

Out
put
:
I
nsi
deA'sConst
ruct
or
I
nsi
deB'sConst
ruct
or
Page14
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

b)
Mul
til
evel
Inher
it
ance

Ai
m:Towr
it
eaJAVApr
ogr
am t
oimpl
ementmul
til
evel
Inher
it
anc
e

Pr
ogr
am:

cl
assA
{
A(
)
{
Sy
stem.
out
.pr
int
ln(
"I
nsi
deA'
sCons
truct
or"
);
}
}

cl
assBext
endsA
{
B(
)
{
Syst
em.
out
.pr
int
ln(
"I
nsi
deB'
sConst
ruct
or"
);
}
}

cl
assCext
endsB
{
C(
)
{
Syst
em.
out
.pr
int
ln(
"I
nsi
deC'
sConst
ruct
or"
);
}
}

cl
assmult
idemo
{
publ
i
cst at
icv
oidmain(
Str
ingar
gs[
])
{
Cc1=newC();

}
}

Out
put
:
I
nsi
deA'sConst
ruct
or
I
nsi
deB'sConst
ruct
or
I
nsi
deC'sConst
ruct
or
Page15
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

c)
Abstr
act
Cl
ass

Ai
m:Towr
it
eaj
avapr
ogr
am f
orabst
ractc
las
stof
indar
easofdi
ff
erentshapes

Pr
ogr
am:

abst
ractclassshape
{
abstractdoubl ear ea()
;
}
cl
assrectangl eex tendsshape
{
doublel =12. 5, b=2.5;
doublear ea( )
{
r
et ur nl *b;
}
}
cl
asstri
angl eex tendsshape
{
doubl eb=4. 2,h=6. 5;
doubl ear ea( )
{
retur n0. 5*
b* h;
}
}
cl
asssquar eex tendsshape
{
doubl es=6. 5;
doubl ear ea( )
{
retur n4* s;
}
}
cl
assshapedemo
{
publicst aticv oidmai n(String[]args)
{
rect angl er1=newr ectangle()
;
tri
angl et 1=newt riangle();
squar es1=newsquar e( )
;
Sy stem. out.pri
ntln("Thear eaofr
ectangl
eis:"+r
1.area()
);
Sy stem. out.pri
ntln("Thear eaoft
ri
angleis:
"+t1.
area())
;
Sy stem. out.pri
ntln("Thear eaofs
quareis:"+s1.
area())
;
}
}

Out
put
:
Thear
eaofr
ectangl
eis:31.
25
Thear
eaoft
ri
angleis:
13.65
Thear
eaofs
quar
eis:
26.
0

Page16
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

Ex
erci
se-6(
Inher
it
ance-Cont
inued)
a)superk
eyword
implementat
ion
Ai
m:Wr
it
eaJAVApr
ogr
am gi
veex
ampl
efor“
super
”key
wor
d

Pr
ogr
ams:
(
i)
Usi
ngsupert
ocal
lsupercl
assconst
ruct
or(
Wit
houtpar
amet
ers)

cl
assA
{
intl,
b;
A()
{
l=10;
b=20;
}
}
cl
assBex tendsA
{
inth;
B()
{
super (
);
h=30;
}
intvolume( )
{
returnl*b*h;
}
}
cl
asssuper demo
{
publi
cst ati
cv oidmai n(
Str
ingar
gs[]
)
{
Bb1=newB( )
;
i
ntr=b1. v
olume( )
;
System.out.pri
ntl
n("
Thevol.i
s:"
+r)
;
}
}

Output
:
Thevol.i
s:6000

(i
i
)Usi
ngsupertocal
lsupercl
assconst
ruct
or(
Wit
hpar
amet
ers)
cl
assA
{
i
ntl,
b;
A(i
ntu,
intv)
{
l
=u;
b=v
;
}
}

Page17
IIB.TechIISem Jav aLabManual (R19) Pr eparedby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
classBex tendsA
{
i
nth;
B(i
ntu, intv ,
i
ntw)
{
super (u,v);
h=w;
}
i
ntvol ume( )
{
returnl *b*h;
}
}
classsuper demo
{
publi
cst ati
cv oi dmai n(
Stri
ngar gs[
])
{
Bb1=newB( 30,
20,30);i
nt
r=b1. volume( );
Sy stem. out.pri
ntl
n("Thevol.i
s:"+r)
;
}
}

Output
:
Thevol.i
s:18000
Page18
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
b)I
mpl
ement
ingi
nter
face
Ai
m:Towr
it
eaJAVApr
ogr
am t
oimpl
ementI
nter
face.
Pr
ogr
ams:
(
i)Fi
rstf
orm ofi
nter
facei
mpl
ement
ati
on
i
nter
faceA
{
voiddisplay()
;
}
cl
assBimpl ement sA
{
publi
cv oiddisplay()
{
System.out.pr
intl
n("
B'smethod"
);
}
}
cl
assCex tendsB
{
publi
cv oidcallme()
{
System.out.pr
intl
n("
C'smethod"
);
}
}
cl
assint
erfacedemo
{
publi
cst ati
cv oi
dmai n(Str
ingar
gs[]
)
{
Cc1=newC( );
c1.displ
ay();
c1.call
me( )
;
}
}

Out
put
:
B'
smethod
C'
smethod

(i
i
)Secondfor m ofinter
faceimplement
ati
on
i
nter
faceD
{
voiddisplay(
);
}
i
nter
faceEex tendsD
{
voidshow( );
}
cl
assA
{
voidcall
me( )
{
Sy st
em. out
.pri
ntl
n("
Thisi
sincal
l
memet
hod"
);
}
}

Page19
IIB.TechI ISem Jav aLabManual (R19) Preparedby :Mr.P.
PULLAI
AH,
KITS,
MARKAPUR
classBex tendsAi mpl ement sE
{
publicv oiddi spl ay()
{
Sy stem. out .pri
ntln("Thisisindi
splaymet hod")
;
}
publicv oidshow( )
{
Sy stem. out .pri
ntln("Thi sisi
nshowmet hod")
;
}
}
classCex tendsB
{
voidcal l(
)
{
Sy stem. out .
println("Thisi
sincallmethod");
}
}
classi nt
erfacedemo
{
publicst ati
cv oidmai n(Stringargs[
])
{
Cc1=newC( );
c1. display ()
;
c1. show( );
c1. call
me( );
c1. call
();
}
}
Out put:
Thi sisindi splaymet hod
Thi sisinshowmet hod
Thi sisincal lmemet hod
Thi sisincal lmet hod
(ii
i)Thirdfor m ofi nt erfaceimpl ementati
on
i
nt erf
aceA
{
voiddi splay (
);
}
classBi mpl ement sA
{
publicv oiddi spl ay()
{
Sy stem. out .
println("Thisi
sinB'smet hod");
}
}
classCi mpl ement sA
{
publicv oiddi spl ay()
{
Sy stem. out .
println("Thisi
sC'smet hod");
}
}
classi nt
erfacedemo {
Page20
IIB.TechIISem Jav aLabManual (
R19) Pr epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
publi
cst ati
cv oidmai n(Str
ingargs[]
)
{
Bb1=newB( )
;
Cc1=newC( )
;
b1.display (
);
c1.di
spl ay (
);
}
}
Out put:
Thi sisinB'smet hod
Thi sisC'smet hod
(iv)Fourthform ofi nt erf
acei mplement at
ion
i
nt erf
aceA
{
voi
ddi splay (
);
}
i
nt erf
aceB
{
voi
dcal lme( )
;
}
i
nt erf
aceCex t
endsA, B
{
voi
dcal l(
);
}
classDi mpl ement sC
{
publi
cv oiddi splay()
{
System. out .
pri
nt l
n("
interf
aceA");
}
publi
cv oidcal lme( )
{
System. out .
pri
nt l
n("
interf
aceB");
}
publi
cv oidcal l()
{
System. out .
pri
nt l
n("
interf
aceC");
}
}
classi nt
erfacedemo
{
publicst at
icv oidmai n(St
ringargs[
])
{
Dd1=newD( );
d1.display (
);
d1.call
me( );
d1.call
();
}
}
Out put:
i
nt erf
aceA
i
nt erf
aceB
i
nt erf
aceC
Page21
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
Ex
erci
se-7(
Except
ion)
a)Ex
cept
ionhandl
i
ng
mechani
sm
Ai
m:Towr
it
eaJAVApr
ogr
am t
hatdescr
ibesex
cept
ionhandl
i
ngmechani
sm

Pr
ogr
am:
UsageofEx
cept
ionHandl
i
ng:

cl
asstr
ydemo
{
publ
icstat
icvoidmain(Str
ingargs[
])
{
t
ry
{
i
nta=10,b=0;int
c=a/b;
System.
out.pr
intl
n(c)
;
}

catch(
Arithmet i
cExceptione)
{
Sy stem.out.
print
ln(e);
}
System.out .
pri
ntl
n("Aft
ert hecat
chst
atement
");
}
}

Output
:
j
ava.l
ang.
Ari
thmeti
cEx
cept
ion:
/byzer
o
Aft
erthecat
chstat
ement
Page22
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
b)I
ll
ust
rat
ingmul
ti
plecat
chcl
asses

Pr
ogr
am:

Ai
m:Towr
it
eaJAVApr
ogr
am I
ll
ust
rat
ingMul
ti
plecat
chcl
aus
es

cl
assmult
it
rydemo
{
publ
icstati
cvoi
dmai n(St r
ingargs[
])
{
t
ry
{
i
nta=10, b=5;
i
ntc=a/ b;
intd[]
={0,1};
System.out.pri
ntl
n(d[
10]
);
System.out.pri
ntl
n(c)
;
}

catch(
Arithmet i
cExcept i
one)
{
Sy stem.out.printl
n(e)
;
}
catch(
Arr ayIndexOut OfBoundsExcept
ione)
{
Sy stem. out.
printl
n(e);
}
System.out .pr
intl
n("Afterthecat
chstatement
");
}
}

Output
:
j
ava.l
ang.
Arr
ayI
ndexOut
OfBoundsEx
cept
ion:
10
Aft
erthecat
chstat
ement
Page23
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

Ex
erci
se–8(
Runt
imePol
ymor
phi
sm)
a)
Runt
imePol
ymor
phi
sm

Pr
ogr
am:

Ai
m:Towr
it
eaJAVApr
ogr
am t
hati
mpl
ement
sRunt
imepol
ymor
phi
sm

cl
assA
{
voi
ddi spl ay()
{
Sy stem.out .
println("Insi
deAcl ass")
;
}
}
cl
assBextendsA
{
voi
ddi spl ay()
{
Sy stem. out.
println("InsideBclass");
}
}
cl
assCext endsA
{
voi
ddi spl ay()
{
Sy stem. out.pri
nt l
n( "
InsideCclas s")
;
}
}
cl
assrunti
medemo
{
publi
cst aticv oidmai n(St r
ingar gs
[])
{
A a1=new A( )
;
B b1=new B( )
;
Cc 1=new C( )
;
Ar ef ;
ref=c1;
ref.di spl
ay (
);
ref=b1;
ref.di spl
ay (
);
ref=a1;
ref.di spl
ay (
);
}
}

Out
put
:

I
nsi
deCclass
I
nsi
deBclass
I
nsi
deAcl
ass
Page24
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
b)
CasestudyonRunt
ime
Pol
ymorphi
sm
Ai
m:Towr
it
eaCasest
udyonr
unt
imepol
ymor
phi
sm,
inher
it
ancet
hati
mpl
ement
sinabov
epr
obl
em
Dynamicmethoddi
spat
chi
sthemechani
sm bywhi
chacal
ltoanov
err
iddenmet
hodi
sresol
vedat
runti
me,r
athert
hancompi
l
etime.

 Wh
 enanov
err
iddenmet
hodi
scal
l
edt
hroughasuper
classr
efer
ence,Jav
adet
ermi
neswhi
ch
ver
sion(supercl
ass/ subcl
asses)oft hatmethodi st obeex ecut
edbasedupont het
ypeoft he
obj
ectbeingr eferr
edt oatthetimet hecalloccurs.Thus, t
hisdeterminat
ionismadeatruntime.
 Atr
 un-t
ime,itdependsont het ypeoft heobjectbei ngrefer
redto( notthetypeoftheref
erence
var
iabl
e)t hatdetermineswhi chversionofanov erri
ddenmet hodwillbeexecuted
 As uperclassreferencevari
ablec anr ef
ertoasubc lassobject.Thi
si sal
sok nownasupcasting.
Javausest hisfacttoresolvecallst
oov er
ri
ddenmet hodsatr unti
me.
Upcasting
Super
Classobj
=newSubCl
ass

Super
Class

ex
tends

SubCl
ass

Theref
ore,
ifasuperc
lasscont
ainsamethodt hatisov err
iddenbyasubclass, t
henwhendifferent
ty
pesofobject
sarerefer
redtothr
oughasuper classreferencevar
iabl
e,di
fferentver
sionsofthe
methodareexecut
ed.Hereisanexampl
et hatil
lustr
atesdy namicmethoddi spatch:

Theex
ampl
eisgi
venby

Consi
derascenario,Bankisacl
assthatprov
idesmethodtogett
herateofi
nter
est.But
,rateof
i
nter
estmaydifferaccordi
ngtobanks.Forexampl
e,SBI,
ICI
CIandAXISbanksareprovi
ding8.4%,
7.
3%and9.7%r ateofinter
est
Bank

get
Rat
eOf
Int
erest
():
fl
oat

ext
ends

SBI I
CICI

get
Rat
eOf
Int
erest
():
fl
oat get
Rat
eOf
Int
erest
()
:f
loat
A
X
I
S

getRat
e
OfI
ntere
st
():
fl
oat

Page25
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

Exerci
se–9( Userdefi
ned
Ex
cepti
on)
a)
creati
onofil
l
ustrat
ingthr
ow

Pr
ogr
am:

Ai
m:Towr
it
eaJAVApr
ogr
am f
orcr
eat
ionofI
ll
ust
rat
ing

t
hrowcl
assthr
owdemo
{
publ
i
cstati
cvoi
dmai
n(St
ri
ngar
gs[
])
{
try
{
t
hrownewNul
lPoi
nter
Except
ion(
"demo"
);
}

cat
ch(
Null
Point
erExcept
ione)
{
Sy
stem.out.
pri
ntl
n(e)
;
}
}
}

Out
put
:

j
ava.
lang.
Nul
l
Poi
nter
Except
ion:
demo
Page26
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
b)
creat
ionofi
l
lust
rat
ingf
inal
l
y
Ai
m:Towr
it
eaJAVApr
ogr
am f
orcr
eat
ionofI
ll
ust
rat
ingf
inal
ly
Pr
ogr
am(
i)
:
cl
assf
inal
ly
demo
{
publi
cst
ati
cvoidmain(St
ri
ngargs[]
)
{
t
ry
{
inta=10,
b=0;int
c=a/b;
Sy st
em.out.
pri
ntl
n(c
);
}

catch(
Ari
thmet
icEx
cepti
one)
{
Sy
stem.
out.
pri
ntl
n(e);
}
fi
nall
y
{
Sy
stem.
out.
pri
ntl
n("Thi
sisi
nsi
def
inal
l
ybl
ock"
);
}
}
}

Output:
j
ava.l
ang.Ari
thmet
icEx
cept
ion:
/byzer
o
Thi
si si
nsidefi
nal
lybl
ock
Pr
ogr
am(
ii
):
cl
assf
inal
ly
demo
{
publi
cst
ati
cvoidmain(St
ri
ngargs[]
)
{
t
ry
{
inta=10,
b=5;int
c=a/b;
Sy st
em.out.
pri
ntl
n(c
);
}

catch(
Arit
hmet
icEx
cept
ione)
{
}
}
fi
nall
y
{

}
}
Syst
em.
out
.pr
int
ln(
e)
;
Sy
stem.
out
.pr
int
ln(
"Thi
sisi
nsi
def
inal
l
ybl
ock"
);

Out
put:
2
Thi
sisi
nsi
def
inal
l
ybl
ock

Page27
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

c)
creat
ionofJav
aBui
l
t-i
n-

Ex
cept
ionsAi
m:Towr
it
eaJAVApr
ogr
am f
orcr
eat
ionofJav
aBui
l
t-i
n

Ex
cept
ionsPr
ogr
ams:

(
i)Ar
it
hmet
icex
cept
ion
cl
assari
thmeti
cdemo
{
publ
icstat
icvoi
dmai n(Str
ingar
gs[
])
{
tr
y
{
i
nta=10, b=0; intc=
a/b;
Syst
em.out.pri
ntl
n(c)
;
}

cat
ch(Ari
thmet
icExcepti
one)
{
Syst
em.out.
pri
ntln(e)
;
}
}
}

Output
:
j
ava.l
ang.
Ari
thmet
icEx
cept
ion:
/byzer
o

(i
i
)Null
Poi
nterEx cept
ion
cl
assnullpoint
erdemo
{
publ
i
cst at
icv oi
dmain(
Str
ingar
gs[
])
{
try
{
St
ri
nga=null
;
Sy
stem.
out
.pr
int
ln(
a.char
At(
0))
;
}

cat
ch(Nul
l
Poi
nter
Except
ione)
{
Syst
em.
out.
pri
ntl
n(e)
;
}
}
}
Output
:
j
ava.l
ang.
Nul
l
Poi
nter
Except
ion

(i
i
i)St
ri
ngIndex
OutOfBoundEx
cept
ion
cl
assstri
ngbounddemo
{
publ
i
cstat
icv
oidmai
n(St
ri
ngar
gs[
])
{
tr
y
{
Page28
I
IB.
TechI
ISem JavaLabManual (R19) Pr epar
edby:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
Str
inga=" Thisisli
kechipping"
;
charc=a. char
At(24);
System.out.
pri
ntl
n(c);
}
cat
ch(Str
ingIndexOutOfBoundsExcept
ione)
{
System.out.
pri
ntl
n(e);
}
}
}

Output
:
j
ava.l
ang.
Str
ingI
ndex
Out
OfBoundsEx
cept
ion:
Str
ingi
ndexoutofr
ange:
24

(
iv)
Fil
eNot
FoundEx
cept
ion
i
mpor tj
ava.i
o.*;
cl
assf i
l
enotfounddemo
{
publi
cstati
cv oi
dmai
n(St
ri
ngar
gs[
])
{
t
ry
{
Fi
l
efi
le=newFil
e("
E:/
/fi
l
e.t
xt"
);
Fi
l
eReaderf
r=newFil
eReader
(fi
le)
;
}

cat
ch(Fil
eNotFoundExcept
ione)
{
Sy
stem.out.
pri
ntl
n(e);
}
}
}
Output
:
j
ava.i
o.Fi
l
eNot
FoundEx
cept
ion:
E:\
fi
le.
txt(
Thesy
stem cannotf
indt
hef
il
especi
fi
ed)

(
v)Number
For
matEx
cept
ion

cl
assnumberf
ormatdemo
{
publ
icstat
icv
oidmain(
Str
ingar
gs[
])
{
t
ry
{
i
ntnum =Integer.
parseI
nt(
"akki
");
Syst
em.out.
print
ln(
num);
}

cat
ch(
Number
For
mat Except
ione)
{
Syst
em.
out
.pr
intl
n(e);
}
}
}

Output
:
j
ava.l
ang.
Number
For
mat
Except
ion:
Fori
nputst
ri
ng:
"akk
i"

Page29
I
IB.TechI
ISem JavaLabManual(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
(vi
)Arr
ayI
ndex
Out Of
BoundsExcepti
on

cl
assarr
aybounddemo
{
publ
icstat
icvoi
dmai
n(St
ri
ngar
gs[
])
{
try
{
i
nta[
]=newi
nt[
5];
a[
6]=9;
}

cat
ch(Ar
rayIndex
OutOfBoundsEx
cept
ione)
{
System.out
.pr
int
ln(e)
;
}
}
}

Out
put
:

j
ava.
lang.
Arr
ayI
ndex
Out
OfBoundsEx
cept
ion:
6
Page30
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

d)
creat
ionofUserDef
ined

Ex
cept
ionAi
m:Towr
it
eaJAVApr
ogr
am f
orcr
eat
ionofUserDef
ined

Ex
cept
ionPr
ogr
am:

cl
assAex t
endsEx ception
{
A(St
rings1)
{
super(s1);
}
}
cl
assowndemo
{
publ
icstati
cv oidmain(
Str
ingar
gs[
])
{
try
{
t
hrownewA(
"demo"
);
}

cat
ch(
Except
ione)
{
Sy
stem.out
.pr
int
ln(
e);
}
}
}

Out
put
:

A:
demo
Page31
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

Ex
erci
se–10(
Thr
eads)
a)
Ext
endingThr
ead
cl
ass

Aim:Towrit
eaJAVApr ogr
am thatcr
eatesthr
eadsbyextendingThr
eadclass.
Fir
stt
hreaddisplay
“GoodMorning“ev
ery1sec,
thesecondthreaddi
spl
ays“Hell
o“ ev
ery2secondsandthethi
rddispl
ay
“Welcome”ever
y3seconds,(
RepeatthesamebyimplementingRunnabl
e)

Pr
ogr
ams:
(
i)
Creat
ingmul
ti
plet
hreadsusi
ngThr
eadcl
ass
cl
assAex t
endsThr ead
{
publ
icvoidr un()
{
try
{
for(i
nti=1; i<=10;i
++)
{
sleep( 1000);
Sy stem. out.
pri
ntl
n("
goodmorni
ng"
);
}
}
c atch(Exceptione)
{
System. out.pri
ntl
n(e)
;
}
}
}
cl
assBex t
endsThr ead
{
publ
icvoidr un()
{
try
{
for(
intj=1; j
<=10;j++)
{
sleep( 2000);
Sy stem. out.
pri
ntl
n("
hel
lo"
);
}
}
c atch(Exceptione)
{
Syst
em. out .print
ln(
e);
}
}
}
cl
assCex t
endsThr ead
{
publi
cv oidrun( )
{
t
ry
{

Page32
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

for
(i
ntk=1;
k<=10;k++)
{
sl
eep(3000);
Syst
em.out.pr
int
ln(
"wel
come"
);
}
}
cat
ch(
Excepti
one)
{
System.out
.pr
int
ln(
e);
}
}
}
cl
assthreaddemo
{
publi
cstati
cvoidmai
n(St
ri
ngar
gs[
])
{
Aa1=newA();
Bb1=newB();
Cc1=newC();
a1.
star
t()
;
b1.
star
t()
;
c1.
star
t()
;
}
}
Output: wel
comewel
comewel
come
goodmor ni
ng
hel
lo
goodmor ni
ng
goodmor ni
ng
welcome
hel
lo
goodmor ni
ng
goodmor ni
ng
hel
lo
goodmor ni
ng
welcome
goodmor ni
ng
hel
lo
goodmor ni
ng
goodmor ni
ng
welcome
hel
lo
goodmor ni
ng
hel
lo
welcome
hel
lo
welcome
hel
lo
hel
lo
welcome
hel
lo
welcome
Page33
I
IB.TechIISem JavaLabManual (
R19) Preparedby:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
(i
i)
Creati
ngmultipl
ethreadsusi
ngRunnabl
einterf
ace
cl
assAimplement sRunnabl e
{
publ
icv oidrun( )
{
try
{
for (i
nti =1;i<=10; i++)
{
Thread. sleep(1000);
System. out .
print
ln(
"goodmorni
ng"
);
}
}
catch( Ex cept i
one)
{
Sy stem. out .
pr intln(e)
;
}
}
}
cl
assBimplement sRunnabl e
{
publ
icv oidrun( )
{
try
{
f or(i
ntj =1;j<=10; j
++)
{
Thread. sleep(2000);
System. out .pr
intl
n("
hell
o")
;
}
}
catch(Ex cept ione)
{
Sy stem. out.pr i
nt l
n(e);
}
}
}
cl
assCimplement sRunnabl e
{
publ
icv oi
dr un( )
{
try
{
for (i
ntk=1; k<=10; k++)
{
Thr ead. sleep( 3000);
Sy stem. out .print
ln("
welcome");
}
}
catch(Ex cept i
one)
{
Sy st em. out .
pr intln(e); }
Page34
IIB.TechIISem Jav aLabManual (R19) Prepar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
}
}
classrunnabl edemo
{
publicst ati
cv oidmain(
Str
ingargs[
])
{
A a1=new A( )
;
Bb1=new B( )
;
Cc1=newC( );
Thr eadt 1=new Thr
ead(a1);
Thr eadt 2=new Thr
ead(b1);
Thr eadt 3=new Thr
ead(c1);
t1.start
();
t 2.star
t();
t 3.star
t();
}
}

Out
put
:
goodmorni
ng
goodmorni
ng
hel
lo
goodmorni
ng
welcome
goodmorni
ng
hel
lo
goodmorni
ng
goodmorni
ng
welcome
hel
lo
goodmorni
ng
goodmorni
ng
hel
lo
goodmorni
ng
welcome
goodmorni
ng
hel
lo
welcome
hel
lo
hel
lo
welcome
hel
lo
welcome
hel
lo
hel
lo
welcome
welcome
welcome
welcome
Page35
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

(
b)I
mpl
ement
ingi
sAl
i
ve(
)andj
oin(
)

Ai
m:Towr
it
eapr
ogr
am i
ll
ust
rat
ingi
sAl
i
veandj
oin(
)

Pr
ogr
am:

cl
assAex t
endsThr ead
{
publ
icvoidrun()
{
tr
y
{
for(i
nti =1; i
<=10; i
++)
{
s leep( 1000);
Sy stem. out.
pr i
ntl
n("
goodmor
ning"
);
}
}
catch(Except ione)
{
System. out .print
ln(e);
}
}
}
cl
assBex t
endsThr ead
{
publ
icvoidrun()
{
try
{
for(i
ntj =1; j<=10; j
++)
{
sleep( 2000) ;
Sy st em.out .
printl
n("
hell
o")
;
}
}
catch(Except ione)
{
System. out .
printl
n(e);
}
}
}
cl
assCex t
endsThr ead
{
publ
icvoidrun()
{
try
{
f
or(i
ntk=1; k<=10; k++)
{
sleep( 3000) ;
Sy
stem.
out
.pr
int
ln(
"wel
come"
);
}

Page36
IIB.TechIISem Jav aLabManual (
R19) Pr eparedby:Mr.
P.PULLAI
AH,
KITS,
MARKAPUR
}
catch(Ex ceptione)
{
Sy stem. out.
printl
n(e)
;
}
}
}
classisal
ivedemo
{
publi
cstaticv oidmai n(St
ringargs[])
{
Aa1=newA( )
;
Bb1=newB( )
;
Cc 1=newC( )
;
a1.start(
) ;
b1.start(
) ;
c1.
star t(
);
System. out .
printl
n(a1.i
sAliv
e());
System. out .
printl
n(b1.i
sAlive(
));
System. out .
printl
n(c1.i
sAliv
e());
tr
y
{
a1. j
oin();
b1. j
oin();
c1.join();
}
catch(InterruptedEx cepti
one)
{
Sy stem. out.
printl
n(e)
;
}
System. out .
printl
n(a1.i
sAliv
e());
System. out .
printl
n(b1.i
sAlive(
));
System. out .
printl
n(c1.i
sAliv
e());
}
}
Out put
: goodmor ningwel
come
true
true
true
goodmor ni
ng
goodmor ni
ng
hello
goodmor ni
ng
welcome
goodmor ni
ng
hello
goodmor ni
ng
goodmor ni
ng
welcome
hello
goodmor ni
ng
goodmor ni
ng
hello
l
o
g welcome
o welcome
o welcome
d welcome
m f
alse
o f
alse
r f
alse
n
i
n Page37
g
h
e
l
l
o
wel
come
h
e
l
l
o
h
e
l
l
o
w
e
l
c
o
m
e
h
e
l
l
o
w
e
l
c
o
m
e
h
e
l
l
o
h
e
l
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

c)I
mpl
ement
ati
onofDaemonThr
eads

Ai
m:Towr
it
eaPr
ogr
am i
l
lust
rat
ingDaemonThr
eads

Pr
ogr
am:

cl
assAextendsThr ead
{
publ
icvoidr un()
{
i
f(Thread. curr
entThread().
isDaemon()
)
System. out.pri
ntl
n("
daemont hreadwork"
);
el
se
System. out.pri
ntl
n("
usert hreadwork"
);
}
}
cl
assdaemondemo
{
publ
icstati
cv oidmai n(Str
ing[]args)
{
Aa1=new A( );
Aa2=new A( );
Aa3=newA( )
;
a1.setDaemon( t
rue)
;
a1.start()
;
a2.start()
;
a3.start()
;
}
}

Out
put
:
daemonthreadwor
k
usert
hreadwork
usert
hreadwork
Page38
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
Exercise-11(Thr
eadsconti
nuit
y)
a)Producer
-Consumerprobl
em
Ai
m:Wr
it
eaJAVApr
ogr
am Pr
oducerConsumerPr
obl
em
Pr
ogram:
cl
assA
{
intn;
booleanb=fal
se;
synchroni
zedintget
()
{
i
f(!
b)
tr
y
{
wai
t(
);
}

catch(Excepti
one)
{
System.out.
pri
ntl
n(e);
}
System.out.pr
int
ln(
"Got:
"+n);
b=false;
notif
y();
ret
urnn;
}
sy
nchr
onizedv
oidput
(i
ntn)
{
i
f(
b)
t
ry
{
wai
t(
);
}

catch(Ex cepti
one)
{
Syst em.out.
pri
ntl
n(e)
;
}
thi
s.n=n; b=true;
System. out.pri
ntl
n("
Put:
"+n);
notif
y();
}
}
cl
assproduc erimpl ementsRunnabl
e
{
Aa1; Thr eadt1;
producer (Aa1)
{
this.a1=a1;
t1=newThr ead(t
his)
;
t1.start(
);
}
publi
cv oidr un() {
Page39
I
IB.
TechI
ISem JavaLabManual(
R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
for
(i
nti=1;i
<=10;
i
++)
{
a1.put
(i)
;
}
}
}

cl
assconsumeri mplementsRunnable
{
Aa1; Thr eadt 1;
consumer (Aa1)
{
this.a1=a1;
t1=newThr ead(t
his);
t1.start(
);
}
publi
cv oidr un()
{
for (i
ntj=1;j
<=10;
j++)
{
a1.
get()
;
}
}
}
cl
assi nt
erdemo
{
publi
cst ati
cv oidmain(Str
ingargs[
])
{
Aa1=newA( )
;
pr oducerp1=newpr oducer(
a1);
consumerc1=newconsumer (a1)
;
}
}
Output: Got
:10
Put
:1
Got:
1
Put
:2
Got:
2
Put
:3
Got:
3
Put
:4
Got:
4
Put
:5
Got:
5
Put
:6
Got:
6
Put
:7
Got:
7
Put
:8
Got:
8
Put
:9
Got:
9
Put
:10
Page40
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

b)
Casestudyonthread
sy
nchroni
zat
ion

Ai
m:Towr
it
eacasest
udyont
hreadSy
nchr
oni
zat
ionaf
tersol
vi
ngt
heabov
epr
oducercons
umer
pr
obl
em

Acasest
udyont
hreadsy
nchr
oni
zat
ionaf
tersol
vi
ngpr
oducerconsumerpr
obl
em:

 Wecanusewai t,not i
fyandnot if
yAllmet hodst ocommuni cat
ebet weent hreadsinJav a.
 Forex ample, i
fwehav et wot hreadsr unninginy ourpr ogram e.g.Pr
oducerandCons umerthen
producerthreadcancommuni catetot heconsumert hatitcanst ar
tconsumi ngnowbecauset here
arei t
emst oconsumei nt hequeue.
 Simi l
arl
y,aconsumert hr eadcant ellthepr oducert hatitcanals ostartputti
ngi t
emsnowbecause
thereissomespacei nt hequeue, whichi screatedasar esultofcons umpt i
on.
 At hreadcanusewai t
()met hodtopaus eanddonot hingdependi nguponsomecondi ti
on.
 Forex ample, i
nt hepr oducer -
consumerpr oblem, producert hr
eads houldwai tifthequeuei sfull
andconsumert hreadshoul dwaitifthequeuei sempt y.
Ifsomet hreadi swai t
ingf orsomecondi tiontobecomet rue,wecanusenot i
fyandnot if
yAll
met hodstoi nformt hem t hatcondi t
ionisnowchangedandt heycanwakeup.
 Bot hnoti
fy()andnot ifyAll()methodsendsanot i
ficati
onbutnot ifysendst henotifi
cati
ont oonly
oneoft hewai tingt hread, noguar anteewhi cht hreadwi ll
receivenotif
icati
onandnot if
yAll
()sends
the
notifi
cati
ont oal lthreads.

Thi
ngst
oremember
:

1.Wecanusewai t(
)andnotify
()met hodt oimpl ementinter-
threadcommuni cat
ioninJav a.Not
j
ustoneort wothreadsbutmul t
iplet hreadscancommuni cat etoeachotherbyus ingthese
met hods.
2.Alway scallwai
t()
,noti
fy(
)andnot ify
Al l
()met hodsfrom synchr oni
zedmet hodorsy nchronized
blockot her
wiseJVM wi l
lthr
owI l
legal MonitorStat
eExcepti
on.
3.Alway scallwai
tandnot i
fymethodf rom al oopandnev erfrom if(
)bl
ock,becaus eloopt est
waitingconditi
onbeforeandaf t
ersl eepingandhandl esnot if
icati
onevenifwai t
ingforthe
condi t
ionisnot
changed.
4.Alway scallwai
tinsharedobjecte.g.shar edqueuei nthisex ample.
5.Prefernotif
yAll
()overnoti
fy(
)met hodduet or easonsgivenint hi
sarti
cle
Page41
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
Exer
cise–12
(
Pack ages)
a)I
ll
ust
rat
ionofcl
ass
path
Ai
m:Towr
it
eaJAVApr
ogr
am i
ll
ust
rat
ecl
asspat
h

i
mportjava.net
.URL;
i
mportjava.net
.URLClassLoader;
publ
i
ccl assApp
{
publicstat
icvoidmai n(
Str
ing[]ar
gs)
{
ClassLoadersysClassLoader=ClassLoader.
get
Sy st
emClassLoader
();
URL[]urls=((URLClassLoader)
sysCl
assLoader)
.getURLs(
);
for(
inti=0;i
<urls.
l
engt h;
i++)
{
Sy
stem.out.
print
ln(
url
s[i
].
getFi
l
e())
;
}
}
}

Output:
E:
/j
av a%20wor
k/
Page42
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
b)Acasest
udyonincludi
ngi
ncl
asspat
hinos
envi
ronment

Ai
m:Towr
it
eacasest
udyoni
ncl
udi
ngi
ncl
asspat
hiny
ourosenv
ironmentofy
ourpackage.

Thedi ff
erencesbet weenpat handcl asspat har egivenby .
(1)ThePATHi sanenv i
ronmentv ariableusedt olocat e"java"or"j
avac"command, torunjava
program andcompi lej
av asour cefile.TheCLASSPATHi sanenv ir
onmentv ari
ableusedt oset
pathforj avaclasses.
(2)Inor dertosetPATHi nJav a,weneedt oincludebi ndi rect
oryinPATHenv i
ronmentwhi lei
n
ordertosetCLASSPATHweneedt oi nc l
udeal ldirectori
eswher ewehav eputeitherour.cl
assfi
l
e
orJARf il
e,whichi srequiredbyourJav aappl icati
on.
(3)PATHenv i
ronmentv ariablei susedbyoper atingsy stem whileCLASSPATHi susedbyJav a
ClassLoader st oloadclassf i
les.
(4)Pat hreferstot hesystem whi l
ec lasspathr eferstot heDev el
opingEnv i
ronment .
Bydef aultthejavar unti
mesy stem usest hecur r
entwor kingdir
ectory.
Normal lytoex ecuteajav apr ogr am inanydi rectorywehav etosetthepathbyasf ol
lows
setpath=c: \
Pr ogram Fi les\ j
ava\jdk1.5.0_10\ bin;

Setti
ngenv i
ronmentalvar
iableinwindowsx p:
Step-1:
Sel ectMycomput eront hedeskt
opandr ightcl
ickthemouseandt
hensel
ectpr
oper
ti
es.
I tdispl
aysthefol
l
owi ng“ Sy
stem Proper
ti
es”dialog.

Sy
stem Pr
oper
ti
es

Adv
a nced

Env
ironmentVar
iabl
es

OK Cancel

St
ep-2:
InSystem Proper
tiescl
ickAdvancedandthencl
ickEnvi
ronmentVar
iabl
es.
Itdis
play
st hefol
lowing“Env
ironmentVar
iabl
es”dial
og.

Env
ironmentVar
iabl
es

Sy
stem Var
iabl
es

New

OK Cancel
St
ep-3:
InEnvironmentVari
abl
escl
ickNewinSyst
em var
iabl
es.
Itdis
playsthefol
lowi
ng“NewSyst
em Vari
abl
e”di
alogbox.

Page43
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

NewSy
stem Var
iabl
e

v
ari
abl
ename:

v
ari
abl
eval
ue:

OK Cancel

St
ep-
4:
Nowtypevari
abl
enameasapathandthenvari
abl
eval
ueas
c:\
Progr
am Fi
l
es\
jav
a\j
dk1.
5.0_10\
bin;
New Sy
stem Var
iabl
e

v
a r
iabl
ename: pat
h

v
a r
iabl
eval
ue: c:
\Pr
ogr
amFi
les\
java\
jdk1.
5.0_
10\
bin;

OK Cancel

St
ep-
5:
Cli
ckOK
Page44
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

c)Cr
eat
ingandi
mpor
ti
ngapack
age

Ai
m:Towr
it
eaJAVApr
ogr
am t
hati
mpor
tanduset
hedef
inedy
ourpackagei
nthepr
evi
ous
Pr
obl
em

(i
)Creati
ngapack age:
Steps:
1.Firstdec laret henameoft hepackageus ingpackagekey word
Exampl e:pack agemy pack;
2.Ty pet hef ollowi ngpr ogr am undert hispackagest atement.Inpackage: cl
ass,data,methods
al
l arepubl ic
packagemy pack;
publiccl assbox
{
publ i
ci ntl =10, b=20;
publ i
cv oi ddi spl ay()
{
Sy stem. out.print l
n(l)
;
Sy stem. out.print l
n(b);
}
}
3.Creat esubdi rectorywi thanamesamet hatofpackagenameundert hecur r
entwor ki
ng
di
r ectorybyasf ollows. d: \ >mdmy pack
4.Undert hissubdi rect oryst or et heabov epr ogr am wi thafi
lename“ box.
java”.
(i
i
)impor tingapack age:
Steps:
1.packagescanbeacc essedbyusi ngt heimpor tstatement
Gener alform:i mpor tpack1[ .pack2] .(classname/ *
);
Exampl e: i
mpor tjav a.i
o. *;
Her epack1i snameoft oplev elpackageandpack2i snameofsubpackage
2.Ty pet hef ollowi ngpr ogr am undert hecur rentwor kingdir
ectoryandsavet heprogram wit
ha
fi
l
ename“ ex ampl e. j
av a” .
i
mpor tmy pack. box ;
cl
asspackagedemo
{
publ icst aticv oidmai n(Stringar gs[])
{
boxb1=newbox ()
;
b1.di splay ();
}
}
3.Nowcompi let heabov epr ogr am int hecur rentwor kingdir
ectoryd:\
j
av acpackagedemo. j
av a
4.Ex ecutet heabov epr ogr am i ncur rentwor ki ngdi rector
y
j
av apackagedemo

Output
:
10
20
Page45
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
Exer
cise-13(
Appl
et)
a)Pai
ntl
ik
ePaintBr
ushi
nAppl
et
Ai
m:Towr
it
eaJAVApr
ogr
am t
opai
ntl
ikepai
ntbr
ushi
nappl
et.
Pr
ogr
am:
i
mpor tjav a.
appl et.
* ;
i
mpor tjav a.
awt .*;
i
mpor tjav a.
awt .event.*;
//<appletcode=" paintdemo"wi dth="800"height="
500"></
appl
et>
publi
ccl asspai ntdemoex tendsAppl etimplement sMouseMotionLi
stener
{
i
ntw, h;Imagei ;
Gr aphicsg1;
publ i
cv oidi nit
()
{
w=get Size( )
.width;h=get Si
ze()
.hei
ght;
i=c r
eat eI
mage(w, h) ;
g1=i .getGr aphics ()
;
g1. setColor (Color .
whi t
e) ;g1.
fil
l
Rect(0,0,w,h);
g1.set
Color(Col
or.
red);
i=c r
eat eI
mage(w, h) ;
g1=i .getGr aphics ()
;
g1. setColor (Color .
whi t
e) ;g1.
fil
l
Rect(0,0,w,h);
g1.set
Color(Col
or.
blue)
;
addMouseMot i
onLi stener(thi
s) ;
}
publ icv oidmouseMov ed(MouseEv ente){}
publ icv oidmouseDr agged(MouseEv entme)
{
intx=me. get X(); i
nty=me. getY()
;
g1. fil
l
Ov al(x-10,y-10,20,20);
repai nt();
me. consume( );
}
publ icv oidupdat e(Gr aphicsg)
{
g.dr awI mage(i ,
0, 0,this);
}
publ icv oidpai nt(Gr aphicsg)
{
updat e(g);
}
}
Output:
Page46
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

b)Di
spl
ayAnal
ogCl
ockusi
ngAppl
et
Ai
m:Towr
it
eaJAVApr
ogr
am t
odi
spl
ayanal
ogcl
ockus
ingAppl
et.
Pr
ogr
am:
i
mportjav a.util.*
;
i
mportjav a.text .
*;
i
mportjav a.appl et .
*;
i
mportjav a.awt .
*;
//
<appletc ode=" clock demo"wi dt
h="550"hei ght
="250"></
appl
et
publ
i
ccl asscl ock demoex t
endsAppl etimplement sRunnabl
e
{
inth=0, m=0, s=0;
Stringst r="";intwt ,
ht;Threadt hr=nul
l;booleanb;
publ i
cv oidi nit(
)
{
wt =get Siz e(
).wi
dth;ht=getSize(
).
height;
}
publ i
cv oids t
ar t(
)
{
if(thr ==nul l
)
{
thr=newThr ead(t
his);
b=false;
thr.
start(
);
}
el
se
{
i
f(
b)
{
b=fal
se;
synchr
onized(t
his)
{
not
ify()
;
}
}
}
}
publ
i
cv oi
dstop()
{
b=tr
ue;
}
publ
i
cv oi
drun()
{
tr
y
{
whi
l
e(t
rue)
{
Calendar cl ndr=Calendar.
getInstance();
h=clndr.get(Calendar.HOUR_ OF_DAY) ;
i
f(h>12) h-=12;
m=cl ndr.get(Calendar.
MINUTE) ;
s=clndr .
get(
Calendar.
SECOND);
Simpl eDateFor matfrmatter=newSi mpl eDateFormat(
"hh:
mm:ss"
,
Locale.getDef
ault
())
;
Dated=cl ndr.getTime();str
=f r
mat ter
.format(d);
i
f(b)
{
sy nchronized(thi
s) {
Page47
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
whi
l
e(b)
{
wai
t(
);
}
}
}
r
epai
nt(
);
t
hr.
sl
eep(1000)
;
}
}
c
atc
h(Except
ione)
{
Sy
stem.out
.pr
int
ln(
e);
}
}
v
oiddrawHand( doubl eangl e,i
ntr adius,Gr aphicsgr p)
{
angle-=0.5*Mat h.PI ;
i
nta=( int)
(radius* Mat h.
cos( angle));i
ntb=( int)
(radi
us*Mat h.sin(angl
e));
grp.
dr awLine( wt /2,ht/2,
wt/ 2+a,ht/2+b) ;
}
v
oiddrawWedge( doubl eangl e,i
ntr adius,Gr aphicsgr p)
{
angle-=0.5*Mat h.PI ;
i
nta=( int)
(radius* Mat h.
cos( angle));i
ntb=( int)
(radi
us*Mat h.sin(angl
e));
angle+=2* Mat h. PI/3;
i
nta2=( i
nt)(5*Mat h.cos(angle));intb2=( i
nt )(5*Math.si
n(angl e))
;
angle+=2* Mat h. PI/3;
i
nta3=( i
nt)(5*Mat h.cos(angle));intb3=( i
nt )(5*Math.si
n(angl e))
;
grp.
dr awLine( wt /2+a2, ht/2+b2, wt/2+a,ht/ 2+b);
grp.
dr awLine( wt /2+a3, ht/2+b3, wt/2+a,ht/ 2+b);
grp.
dr awLine( wt /2+a2, ht/2+b2, wt/2+a3,ht /2+b3) ;
}
publ
icvoidpai nt(Gr aphi csgrp)
{
grp.
s etColor (
Col or.gray);
drawWedge( 2*Mat h.PI*
h/12, wt/5,grp);dr awWedge( 2*Mat h.PI*m/60,wt/3,
grp)
;
drawHand( 2* Mat h.PI*s/60,wt /
2,grp);
}
}
Out
put
:
Page48
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
c)Di
spl
ayAnal
ogCl
ockusi
ngAppl
et
Ai
m:Towr
it
eaJAVApr
ogr
am t
ocr
eat
edi
ff
erentshapesandf
il
lcol
orsus
ingAppl
et

Pr
ogr
am:

i
mpor tj
ava.awt .
* ;
i
mpor tj
ava.appl et.
* ;
//
<appletcode=" graphicsdemo"wi dth="400"height="400" ></appl et>
publ
icclassgr aphi csdemoex tendsAppl et
{
publicv oidpai nt(Graphicsg)
{
i
ntx []={10,220,220};
i
nty []={400,400,520} ;
i
ntn=3;
g.drawLi ne(10,30,200,30);
g.setCol or(Color.
blue); g.drawRect(10,40,200, 30);
g.setCol or(Color.
red) ; g.fil
lRect
(10,80,200, 30);
g.setCol or(Color.
orange) ; g. drawRoundRect (
10, 120,200,30,20,
20)
;
g.setCol or(Color.
green) ; g. f i
l
lRoundRect (10,160, 200,30,20,
20)
;
g.setCol or(Color.
blue); g.drawOv al
(10,200,200, 30);
g.setCol or(Color.
black )
; g. fi
ll
Oval(10,
240, 40,40) ;
g.setCol or(Color.
yellow); g. drawArc(10,
290, 200, 30,0,180);
g.setCol or(Color.
yellow); g. fi
ll
Arc(
10,330,200, 30,0,180) ;
g.setCol or(Color.
pink )
; g.fi
ll
Polygon(x,
y ,
n);
}
}

Out
put
:
Page49
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

Ex
erci
se-14(
EventHandl
ing)
a)Cur
sormovementusi
ng
mouse
Ai
m: Towr
it
eaJAVApr
ogr
am t
hatdi
spl
ayt
hexandypos
iti
onoft
hecur
sormov
ementusi
ng
Mouse.
Pr
ogr
am:
i
mpor tj
av a.awt.*;
i
mpor tj
av a.awt.event.
*;
i
mpor tj
av a.applet.
*;
//
<appletcode=" mouseev ent "wi dth=450hei ght
=300></
appl
et>
publ
icclassmouseev entex t
endsAppl et
i
mplement sMouseLi stener ,
MouseMot i
onLi st
ener
{
Strings1="" ;
intx ,
y;
publ i
cv oidinit(
)
{
addMouseLi st
ener (this);
addMouseMot i
onLi stener (
this);
}
publ i
cv oidmouseCl icked(MouseEv entme)
{
x=100;
y=100;
s1="Mousecl i
cked" ;
repaint()
;
}
publ i
cv oidmouseEnt ered(MouseEv entme)
{
x=100;
y=200;
s1="Mouseent er ed";
repaint()
;
}
publ i
cv oidmouseEx ited(MouseEv entme)
{
x=100;
y=300;
s1="Mouseex it
ed" ;
repaint()
;
}
publ i
cv oidmousePr essed( MouseEv entme)
{
x=me. getX();
y=me. getY();
s1="MousePr essed" ;
repaint()
;
}
publ i
cv oidmouseRel eased( MouseEv entme)
{
x=me.get
X()
;
y=me.get
Y()
;
s1="
MouseReal
eased"
;
Page50
I
IB.
TechIISem Jav aLabManual (
R19) Pr epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
repaint(
);
}
publ
icv oidmouseDr agged(
MouseEventme)
{
x=me. getX()
;
y=me. getY(
);
s1="MouseDr agged";
repaint(
);
}
publi
cv oi
dmouseMov ed(MouseEv
entme)
{
x=me. getX();
y=me. getY();
s1=" MouseMov ed";
repaint();
}
publi
cv oi
dpai nt
(Graphicsg)
{
g.drawSt r
ing(s1,
x ,
y);
}
}

Out
put
:
Page51
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
b)Key
-upandKey
-downev
ent
Ai
m:Towri
teaJAVApr
ogr
am t
hati
dent
if
ieskey
-upkey
-downev
entuserent
eri
ngt
exti
na
Appl
et.
Program:
i
mpor tjava. awt .
*;
i
mpor tjava. awt .
ev ent .
*;
i
mpor tjava. applet.*;
//
<appletcode=" key event "width=450height=300></
appl
et>
publi
ccl asskey ev entex tendsAppl etimplementsKeyLi
stener
{
Strings1="" ;
intx ,
y ;
publ i
cv oidinit()
{
addKey Listener (t
his);
request Focus( )
;
}
publ i
cv oidkey Pressed( KeyEventke)
{
x=100;
y=200;
s1=" keypr ess ed" ;
repai nt(
);
}
publ i
cv oidkey Releas ed(KeyEventke)
{
x=100;
y=400;
s1=" keyRel eased" ;
repai nt();
}
publ i
cv oidkey Typed( KeyEventke)
{
s1=s1+ke. getKey Char (
);
repai nt();
}
publ i
cv oidpai nt(Graphi csg)
{
g.dr awSt ring(s1,x ,
y);
}
}
Output:
Page52
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

Exerci
se-15(Swings)
a)Buil
dingacalcul
atori
n
swi
ngsAi
m:Towr
it
eaJAVApr
ogr
am t
obui
l
daCal
cul
atori
n
Swi
ngsPr
ogr
am:
i
mportjav
a.awt .*;
i
mportjav
a.awt .event .
*;
i
mportjav
ax.swi ng.*;
cl
asscalc
ulatorex tendsJPaneli mpl ement sAct i
onList
ener
{
JTextFieldjt=newJTex t
Field();
doubled=0; St ri
ng
op=" =";bool ean
b1=t rue;
cal
culator ()
{
setLay out(newBor derLay out());
j
t.setEditabl e(false);
add(jt,"Nort h");
JPanel j
p=newJPanel ()
;
j
p.set Layout (newGr idLay out(4,4));
Stri
ngs1=" 789/ 456* 123-0.=+" ;
for(i
nti =0; i<s 1.l
engt h();
i++)
{
JBut tonb=newJBut t
on(s1.subst
ri
ng(i
,i+1))
;
j
p.add( b);
b.addAct ionListener(this)
;
}
add(jp, "
Cent er");
}
publi
cv oidact i
onPer formed( Act i
onEv entae)
{
Stri
ngs1=ae. getActionCommand( );
i
f( '
0'<=s1. char At(0)&&s1. charAt(0)<='9'
||s1.
equal
s("
."
))
{
i
f( b1)
j
t.set Text(s1) ;
el
s e
j
t.set Text(j
t.getTex t
()+s1) ;
b1=f al
se;

}
el
se
{
i
f(b1)
{
i
f(s1.
equal
s("
-"
))
{
el
se
op=s1;
}
j
t.
set
Tex
t(s1)
; b1=f
alse;

Page53
I
IB.
TechI
ISem Jav aLabManual (R19) Pr epar
edby:Mr.
P.PULLAIAH,
KITS,MARKAPUR
}
else
{
doubl ex=Doubl e.
pars
eDouble(
jt
.get
Tex
t()
);
calculate(x)
;
op=s1;
b1=t rue;
}
}
}
priv
atev oidcal culate( doubl en)
{
if(op.equal s("+" ))
d+=n;
elseif( op.equal s("-"
))
d- =n;
elseif( op.equal s("*"
))
d* =n;
elseif( op.equal s("/"
))
d/ =n;
elseif( op.equal s("="))
d=n;
jt.
setTex t(""+d) ;
}
publi
cst ati
cv oidmai n( Stri
ng[]args)
{
JFr amej f=newJFr ame();
jf.
setTitle("calcul ator")
;
jf.
setSize( 300, 300) ;
Cont ainerc=j f .getContentPane();
c.add(newcal cul ator()
);
jf.
show( ) ;

}
}

Out
put
:
Page54
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR
b)Di
spl
ayi
ngdi
git
alwat
ch
Ai
m:Towr
it
eaJAVApr
ogr
am t
odi
spl
ayt
hedi
git
alwat
chi
nswi
ngt
utor
ial
Pr
ogr
am:
i
mportjava.awt .
*;
i
mportjava.applet.*;
i
mportjava.util
.*;
//
<appletcode=" di
gi tal
wat ch"wi dth=450hei ght=300></ appl
et>
publ
i
ccl assdi gi
talwat chext endsAppl etimplement sRunnable
{
Threadt ,t
1;
publi
cv oidst art(
)
{
t=newThr ead(thi s);
t.star
t();
}
publi
cv oidrun( )
{
t1=Thr ead.current Thr ead();
while(t
1==t )
{
repaint();
try
{
t1.sleep( 1000);
}
catch(Exc ept ione)
{
Syst em. out.pri
ntl
n(e);
}
}
}
publi
cv oidpai nt(Graphi csg)
{
Calendarcal =newGr egor i
anCalendar (
);
Stri
ngh=St ri
ng. valueOf (cal.
get(Calendar.HOUR));
Stri
ngm =St ri
ng. valueOf (cal
.get(Calendar.MINUTE)
);
Stri
ngs=St ri
ng. valueOf (cal.
get(Calendar.SECOND));
g.drawSt ri
ng(h+" :"+m +" :
"+s, 20,30) ;
}
}
Out
put
:
Page55
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
MARKAPUR

Ex
erci
se–16(
Swi
ngs-Cont
inued)
a)
Bal
lbouncingi
nsi
dea
JPanel
Ai
m:Towr
it
eaJAVApr
ogr
am t
hatt
ocr
eat
easi
ngl
ebal
lbounc
ingi
nsi
deaJPanel
.

Pr
ogr
am:

i
mportjava.awt.
*;
i
mportjavax.swi
ng.*;
publ
i
ccl assbounc i
ngbal
lextendsJPanel
{
i
ntw,h;
fl
oatr=40, d=r*2,X=r+50, Y=r+20, dx=3,dy=3;
publi
cbounc i
ngball
()
{
Threadthr
ead=newThr ead()
{
publi
cvoidrun( )
{
whi
le(true)
{
w =get Width()
;
h=get Height()
;
X=X+dx;
Y=Y+dy ;
i
f( X-r<0)
{
dx=- dx;
X=r ;
}
elseif(X+r>w)
{
dx=-dx ;
X=w-r ;
}
i
f( Y-r<0)
{
dy=- dy;
Y=r ;
}
elseif(Y+r>h)
{
dy=-dy ;
Y=h-r ;
}
repai
nt();
try
{
Thread.sl
eep(50)
;
}
cat
ch(
Except
ione)
{

Page56
I
IB.
TechI
ISem Jav
aLabManual
(R19) Preparedby:Mr.P.
PULLAI
AH,
KITS,
MARKAPUR
Sy
stem.out.
pri
ntl
n(e);
}

}
}
}
;
t
hread.
star
t()
;
}
publ
i
cv oidpai ntComponent (Graphicsg)
{
super.paint Component (
g);
g.setColor(Color .
BLUE) ;
g.fi
ll
Ov al((
int)(
X- r
),(i
nt)(
Y-r),(
int
)d,(
int
)d);
}
publ
i
cst ati
cv oidmai n(Str
ing[]args)
{
JFramej f=newJFr ame( "
bouncingball
")
;
jf
.setSize(300, 200);
jf
.setCont entPane( newbounci ngbal
l()
);
jf
.setVisible(t
rue);
}
}

Out
put
:
Page57
I
IB.
TechI
ISem Jav
aLabManual
(R19) Pr
epar
edby
:Mr
.P.
PULLAI
AH,
KITS,
9MARKAPUR

b)
Displ
ayi
ngar
eal
tree

Ai
m:Towr
it
eaJAVApr
ogr
am JTr
eeasdi
spl
ayi
ngar
eal
treeups
idedown

Pr
ogr
am:

i
mportjavax.
swi ng. *
;
i
mportjavax.
swi ng. t
ree. *;
cl
assrealt
ree
{
publi
cstat icv oidmai n(Stri
ng[]ar
gs)
{
JFr amej f=newJFr ame( )
;
Def aultMut ableTreeNoded1=newDefaul
tMutableTreeNode(
"Color
",true);
Def aultMut ableTreeNoded2=newDefault
MutableTreeNode("
Black"
);
Def aultMut ableTreeNoded3=newDefault
MutableTreeNode("
Blue")
;
Def aultMut ableTreeNoded4=newDefault
MutableTreeNode("
Nav yBlue");
Def aultMut ableTreeNoded5=newDefault
MutableTreeNode("
DarkBlue" )
;
Def aultMut ableTreeNoded6=newDefault
MutableTreeNode("
Green")
;
Def aultMut ableTreeNoded7=newDefault
MutableTreeNode("
White")
;
d1.add( d2);
d1.add( d3);
d3.add( d4);
d3.add( d5);
d1.add( d6);
d1.add( d7);
JTr eej t=newJTr ee(d1);
jf
.add( jt);
jf
.set Size(200, 200) ;
jf
.set Visible(true);
}
}

Out
put
:
Page58

You might also like