Core Java Progrmmers
Core Java Progrmmers
ntr
oduct
iont
oJAVA(
CH-
1)
Program:-
Program isacol l
ectionofsetofi nst r
uctionst obeexecut edtopr oduce
theoutputusingaspeci alt
y peofcompi lerorsof t
war e.
Compi ler
:-
Acompi l
erisaspeci alprogr am orsof twarewhi chi susedt oconv ert
sourcecodet omachi necode.i tisalsousedt odet ecterrorsatthet i
me
ofcompi l
ati
onoft hepr ogram.
Algorit
hm:-
Thepr ogrammerbegi nst hepr ogr ammi ng processbyanal yzing the
problem,breakingiti ntomanageabl epi eces,anddev elopingagener al
soluti
onforeachpi ececal l
edanal gorit
hm.
Flowchart:
-
Flow chartisav isuallypr esenti
ng t he f l
ow ofcont rolthrough an
i
nf or
mat i
onpr ocessingsy st ems,t heoper ati
onsper f
ormedwi t
hi nthe
system andthesequencei nwhi cht heyar eper f
ormed.
Al
gor
it
hm:
Programmi ngLanguage: -
Thelanguagewhi chisusedtorepresenttheinst
ruct
ionsofaprogr
am to
executeitiscall
edapr ogrammi nglanguage.
Types:-
[Link]
/procedural l
anguage:-i
ti s based on struct
ure or
procedures/functi
ons.
ex-c
[Link]
alobjector i
entedlanguage:-whi
chmayormaynotuset he
conceptsofoopst owri
teapr ogram.
ex-c++,php
3.f ull
yobj ector ientedlanguage: -withoutt hehel pofoopswecannot
wr i
teapr ogram.
ex-j
av a,.net
[Link] ectbasedl anguage: -basedonobj ects.
ex-j
av ascr i
pt,vbscript
Hist ori
calDev el opmentofPr ogr ammi ngLanguages: -
[Link]-1954
[Link]-1957
[Link]-1960
[Link]-1963
[Link]-1967
6.B-1970
7.C-1972
8.C++-1980
[Link]–1980- 1990
10. JAVA–1990/ 1991
11. .NET-1991
12. PHP–1993
13. R–1993
14. SCALA-2003
Feat uresofOOPs: -
Object -Ori
ent edPr ogrammi ngi samet hodol ogyorpar adigm t odesigna
progr am usi ng cl asses and obj [Link] si mpl i
fies t he sof t
war e
dev elopmentandmai ntenancebypr ovidi
ngsomeconcept s:
[Link] ass:-cl assi sanuserdef i
neddat aty pewhi chdescr i
beabouta
parti
cul ari tem orper sonorpl [Link] anguagesi tismust
to cr eat e a cl ass f or r epr esent ing dat a. Cl ass
cont ainsvar i
ablesf orst oringdat aandf unct ionst ospeci f
y
variousoper ationst hatcanbeper for medondat [Link] asswi ll
notoccupyanymemor yspaceandhencei ti sonl ylogical
represent ationofdat a.
[Link] ect :-obj ecti sthei nst ance/ copyoft hecl asswhi chdescr ibes
thechar acteristi
cs/behav iouroft hecl [Link] eatemor e
thanoneobj ectforasi ngleclass.
3.I nheritance: -whenonecl asinher it
st hef eaturesofanot herclass
then i ti s cal l
ed i nher i
[Link] mai n adv antage ofusi ng
inheri
tancei scoder eusuabi l
i
tyandsecur it
[Link] avat herearet wo
typesofi nher i
tance; onei ssingleandanot heri sinterf ace.
[Link] ymor phi sm: -gr eek wor d pol ymeans manyand mor phism
meansf [Link] ngl emet hodwi t
hsamenamepr ocesst o
form di fferentdi ffer entoper ati
onst heni tiscal ledpol ymor phism.
Ther e ar e t wo t ypes of pol ymor phism l ike compi le t ime
pol ymor phi sm andr unt i
mepol ymor phism.
[Link] aencapsul ation: -wr appi ngupofdat ai ntoasi ngl
euni ti s
cal l
edencapsul [Link] at i
oni shi dingt hef unct ionaldat a
from t he obj ect cal li
ng i t. I ntegr ation of dat a and
oper at i
ons/ funct ionsi n acl assi sEncapsul [Link] i ti sal so
cal l
eddat ahi ding.
[Link] aabst r
act i
on: -Itisusedt odi splayonl ynecessar yandessent ial
featur esofanobj ectt ot heout si dewor l
[Link] ngofnecessar y
dat a by di scar ding/ hiding unnecessar y dat ai s cal led dat a
abst raction.
[Link] ng:-whenoneobj ectcopy /passt hemessagesofi t
toanot herobj ectt heni tiscal ledasmessagepassi [Link] ng
canbedoneei theri mpl icitl
yorexpl icitl
y.
HistoryofJAVA: -
JamesGosl i
ng, Mi keSher i
dan,andPat rickNaught oni nit
iat edt heJav a
l
anguagepr ojecti nJune1991atSunMi crosy [Link] rstofal lthey
namedj avaasoakbecausei twasdev elopedunderoakt r
eebutl ateron
i
twas r enamed t oj av a( coffee)because t hey dev eloped i ton a
restaurantwhi letaki ngcof f
ee.
Editi
onsofJAVA: -
1.J2SE( standar dedi tion) -
cor ejav a
2.J2EE( enter pr i
seedi ti
on) -[Link] a
3.J2ME( micr oedi ti
on) -mobi l
eapp
VersionsofJAVA: -
[Link] a(1995)
2.JDK1.0(23rdJan,1996)
3.JDK1.1(19thFeb,1997)
4.J2SE1.2(8thDec,1998)
5.J2SE1.3(8thMay,2000)
6.J2SE1.4(6thFeb,2002)
7.J2SE5.0(30thSep,2004)
[Link] aSE6( 11thDec, 2006)
[Link] aSE7( 28thJul y,
2011)
10. Jav aSE8( 18thMar ch, 2014)
11. Jav aSE9( 21stSep, 2017)
JDK: -
TheJav aDev elopmentKi t(JDK)i sasof twaredev el opmentenv i
ronment
usedf ordev elopi ngJav aappl i
cationsandappl ets.I tincludestheJav a
Runt imeEnv i
ronment( JRE) ,an i nterpreter/
loader( Java),a compi l
er
(j
av ac),anar chi ver(jar),adocument ationgener ator( Javadoc)andot her
toolsneededi nJav adev elopment .
JRE: -
JREst andsf or“ JavaRunt i
meEnv i
ronment ”andmayal so bewr i
tten
as“ Jav aRTE. ”TheJav aRunt i
meEnv ir
onmentpr ov i
dest hemi ni
mum
requirement sf orexecut ingaJav aappl icat
ion;i tconsi st soft heJav a
Virt
ual Machi ne( JVM) ,corecl asses, andsuppor tingf ies.
l
JVM: -
Jav aVi rtualmachi ne(JVM)i sav eryimpor t
antpar tofbot hJDKandJRE
becausei tiscont ainedori nbuiltinbot [Link] ev erJav apr ogram y ou
run usi ng JRE orJDK goes i nto JVM and JVM i sr esponsible
forex ecut i
ngt hej av apr ogr am linebyl i
nehencei tisal soknownas
i
nter [Link] per formsf ol
lowi ngoper ation:
[Link]
[Link] if
iescode
[Link] ecut escode
[Link] ov idesr untimeenv ironment
Feat
uresofJAVA: -
[Link] e-
Jav ai seasyt ol earnandi tssy ntaxi squitesimpl e,cleanandeasy
tounder [Link] usingandambi guousconcept sofC++ar e
eitherl eftouti nJav aort heyhav ebeenr e-impl ement ed i na
cleanerway .
[Link] ect -Ori
ent ed-
Inj av aev erythingi sObj ectwhi chhassomedat aandbehav iour.
Jav acanbeeasi lyex tendedasi tisbasedonObj ectModel .
[Link] tabl e-
Jav aBy tecodecanbecar r i
edt oanypl [Link] mpl ement ati
on
dependentf [Link] erythingr el
at edt ostoragei spr edef ined,
ex ampl e:sizeofpr i
mi tivedat atypes
[Link] formi ndependent -
Unl i
keot herpr ogrammi ngl anguagessuchasC, C++et cwhi chare
compi l
edi ntopl atform speci fi
cmachi [Link] ai sguar ant eedt o
bewr ite-once, r
un- any wher elanguage.
[Link] ed-
Wheni tcomest osecur it
y ,Javai sal wayst hef irstchoi [Link] t
h
javasecur efeatur esi tenabl eust odev elopv i
rusf ree,temperf r
ee
syst [Link] apr ogr am al way srunsi nJav arunt imeenv ironment
wit hal mostnul li nteractionwi thsy stem OS,hencei ti smor e
secur e.
[Link] -
Jav a makes an ef fortt o el i
mi nate error pr one codes by
emphasi zingmai nlyoncompi l
et imeer r
orchecki ngandr untime
checki [Link] hemai nar easwhi chJav aimprov edwer eMemor y
Management and mi shandl ed Except i
ons by i ntroduci ng
automat i
cGar bageCol l
ect orandExcept i
onHandl ing.
[Link] chi tect ureneut ral-
Compi l
ergener at esby te-codes,whi chhav enot hingt odowi t
ha
par ti
cul arcomput erar chitect ure,henceaJav apr ogr am iseasyt o
i
nt repr etonanymachi ne.
[Link] nami c-
Jav ai s a dy nami cl anguage.I tsuppor ts dy nami cl oading of
classes.I tmeanscl assesar el oadedondemand.I talsosuppor ts
funct ionsf rom i tsnat iv elanguagesi .
[Link]++.
9.I nter pret ed-
Jav ai sai nterpr etedl anguagebecauseby tecodeandsour cecode
aredi f
f erent l
yt reat ed.
10. Hi ghPer for mance-
Jav ai sani nterpr etedl anguage,soi twillnev erbeasf astasa
compi led l anguage l ike C or C++.But ,Jav a enables hi gh
perf ormancewi tht heuseofj ust-i
n-ti
mecompi l
er .
11. Mul tithreaded-
Jav amul tithreadi ngf eat ur emakesi tpossiblet owr it
epr ogr am
thatcandomanyt askssi mul taneousl y
.Benef itofmul tit
hreadi ng
i
st hati tut ili
zessamememor yandot herr esour cest oexecut e
mul tiplet hr eadsatt hesamet i
me,l ikeWhi let yping,grammat ical
error sar echeckedal ong.
12. Di stribut ed-
Jav ai sdi stribut edbecausei tfacili
tatesuser stocr eatedistr
ibut ed
appl icat ionsi nj av [Link] eusedf orcr eati
ngdi str
ibut ed
appl icat [Link] sf eatur eofJav amakesusabl et oaccessf ilesby
callingt hemet hodsf rom anymachi neont heinter net.
Appl
icat i
onsofJAVA: -
usedf orsof twar edev elopment
usedf orgr aphi csandani mat ion
usedf orf ifthgener ationcomput erli
ker obots
usedf ordev el
opi nggames
usedf orpr ojectdesi gn/ dev el
opment
u sedf orr eal t
imedev elopment .
El
ement
sofJAVA(
CH-
2)
Char
act
er-set
:-
I
t combines smal
l al
phabet
s,capi
tal al
phabet
s,di
git
s and speci
al
symbol st owr iteapr ogr am.
a- z(asci icode- >97- 122)
A- Z(asci i code- >65- 90)
0- 9(asci i code- >48-57)
Speci al sy mbol s(asci icode- >0-47, 58- 64,91- 96,123-127)
Const ants: -
Const antsar et hef i
xed quant itywhosev aluecannev erbechange
thr
oughoutt hepr ogr am execut ion.
Types: -
1.I
nt egerconst ant-
-maybe+v eor–v e.
-sizei s4by tes
-ex ampl esar e9,-346
[Link]/ r
eal const ant -
-maybe+v eor_ v e
-sizei s4by tes
-ex ampl esar e1/ 3,-4.89
[Link] act er/st ringconst ant-
-ifiti sachar acterconst antt heni tmustbeencl osedwi thina
pai rofsi ngl equot eandsi zei st woby [Link]-‘
s’
-ifi ti sast ringconst antt heni tmustbeencl osedwi thina
pai rofdoubl equot eandsi zei snotf [Link]- “anil
”
Variables:-
Thesear et het empor arynamedmemor yl ocationswher etheconst ant
val
uesar est or [Link] eryconst antv aluemustbeassoci ated wi tha
vari
abl einsidet hememor y.
Rulesf orconst ruct i
ngav ari
abl e:-
1.v ari
abl enamemustst ar tswi thanal phabetoranunder score(
_ ).
2.i tcannotst artswi thadi gi t.
[Link] gitscanbepl acedaf terfirstpl ace.
[Link] ankspacei sal lowedwhi l
edecl ar ingav ari
able.
5.v ari
abl enamel engt hmustnotbemor et hen38char acters.
[Link] alsy mbol sex ceptunder scor ei sal lowedwhi ledeclaringa
vari
abl e.
Types: -
1. L ocal Var iabl esar edecl aredandusedi nsidemet hods.
2. Inst anceVar iablesar edecl aredi nsi deacl assbutout si
deany
met [Link] ecthasi tsowncopyofi nstancev ar i
[Link],
thesev ar iablesar ecr eat edwhenobj ect sar einstant i
at ed.
3. Stat ic/ Cl assVar iabl esar egl obaltot hecl assanddoesn’ tbelong
toanypar t
icularobj ect .Inot herwor ds, thereisonecopyofeach
stat i
cv ar iableiscr eatedpercl asswhent hecl assi sl oaded.
CommentLi nes: -
Thesear eusedt odeact ivat el i
neofcode( s)whi char epr esentbutnot
usedi nsi det hepr ogr am.
Types:
[Link] ngl el inecomment :
-usedt odeact i
v ateasi ngl el ineusi ngt he
symbol (/ /)
.
ex-/ /Sy st em. out .
pr i
nt (“hello”);
[Link] t
ilinecomment :-usedt odeact i
vat emor et hanonel i
neata
ti
me. (/ ** /)
ex-/ *i nta;
a=5;
Sy stem. out .
pr i
nt (a);* /
Identifi
er s:-
These ar et he user -def i
ned wor ds speci ally used f orconst ructi
ng
variable,met hodorar r
ay .Thel engthofi dent ifi
ersmustnotbemor e
than31char act ers.
Key wor ds: -
Thesear eal socal l
edasr eser vewor [Link] ethepr e-
def inedwor ds
whi chcar ryaspeci almeani ngf orthecompi lerandwecannotchange
thenameoft hesekey wor ds.
1)int10)br eak 19)aut o 28)cat ch37) i
nterface 46)cont inue
2)f l
oat 11)def ault20)st atic 29)t hrow38)abst ract 47)const
3)char 12)i f 21)got o 30)pr ivate39)t hrows48)package
4)shor t 13)el se 22)do 31)publ i
c40)f inall
y49)i mpor t
5)long14)swi tch 23)whi le32)pr otect ed41)ext ends50)nat ive
6)doubl e15) case 24)f or33)t r
y 42)i mpl ement s51)by te
7)true16)f alse25)nul l34)t ransient43)f i
nal 52)new
8)strictf p17)enum 26)cl ass35)asser t
44)Bool ean 53)t his
9)r etur n 18)v oid 27)v olati
le36)del ete 45)super 35) 54)
instanceof
55)sy nchr oni zed
Dat atypes: -
Datat ypedeci deswhi cht ypeofdadaav ar iablecant [Link] sused
asa suf fi
xf ort hev ariabl [Link] ear edi fferentt y
pesdat atypesusedi n
j
av apr ogr ammi ngl anguage.
[Link] imar ydat aty pe: -I ti sal so cal led pr edef i
ned/buil
t-i
n/ pri
mitive
dat atype.
ex:-
dat atype si ze( by tes) range
1.i nt 4 -2,147,483, 648t o2,147,483, 647
[Link] 2 0t o65535
[Link] ean 1 true/false( 0/ 1)
[Link] e 8 1.7e-308t o1. 7e+308
5.f loat 4 3.4e-038t o3. 4e+038
6.l ong 8 -2^63t o2^ 63- 1
[Link] t 2 -32768t o+32767
[Link] t
e 1 -128t o+127
[Link] ydat aty pe: -itiscat egor i
zedi ntot wot ypes.
i. der iveddat at ype: -
ex:-
ar r
ay ,met hod
ii
. user -def i
neddat atype:-
ex-class
Howt owr iteaj av apr ogr am: -
Forwr iti
ngj av apr ogr am wecanchooseanyoft heappl i
cations/ wlike
j
dkornet beansorecl ipse.I fwear eusi ngj dk t henwemusthav et o
i
nst allitinourcomput [Link] terthatwr it
et hecodei nnotepadandsav eit
i
nside anydr ive( like D: \ )wi th an ext ensi on . java and filename as
[Link] omptandgot od: \andwr it
et hef oll
owi ng
code:
D:\>setpat h=”compl et epat h” ;
Not e:-compl etepat hisgener atedas:
(1)tempor arypat hset ting:-
Got oc: \progr am f il
es\ j
av a\ j
dk1. 8.0\bin,copyt hi
scompl etepat hfrom
addr essbarandpast ei ti nsidecommandpr omptandpr essent er,t
hen
thepat hwi l
l beaut omat icallysetandnowwecanwr i
teourpr ogr am.
(2)per manentpat hset ti
ng: -
Got oc: \
pr ogram f iles\ jav a\jdk1. 8.0\ bi
n,copyt hiscompl etepat hfrom
addr ess bar .Ri ghtcl ick on my comput er ,go t o proper ti
es,open
admi nistrativet ools, clickonenv i
ronmentv [Link] i
ckonnew.A
dialogboxwi l
lappearandt her ewehav etoprovideav ariablename( any
name)andv ar
iabl ev alueas“ past ethecopiedpat h”andcl i
ckonok
but ton.
(1)Wr it
easi mpl epr ogram t opr intyourname?
cl assHel lo
{
publicst aticv oidmai n(Stri
ngargs[]
)
{
Sy stem. [Link] i
nt (
“hell
ostudents!”);
}
}
Howt ocompi l
e:-
D:\>j avacf i
lename. j
av a
Ex-j av acHel lo.
java
Howt or un:-
D:\>j avaf i
l
ename
Ex:-Jav aHel l
o
Not e: -j av a programsar ecase- sensiti
ve(meanswehav et ol ookup
capi tal andsmal lletterscar ef ull
y) .
Progr am descr iption: -
class: -i ti s an user -defined dat aty
pe whi ch consi sts of some
dat amember s and met hods t
o store and access
het erogeneous/ dissi mi l
art y
peofdat a.
Hel lo:-iti sanuser -definedcl assname.
publ ic:-Her e publ ici san access speci fi
erwhi ch all
ows t hhe mai n
met hodt obeaccessbl eev er ywher e.
stat i
c: -st ati
chel psmai nmet hodt ogetl oadedwi t
houtget ti
ngcal ledby
anyi nst ance/ object .
void: -iti sakey wor d/return-t ypewhi chretur
nsnot hingtot hepr ogram,
onl ypr ints.
mai n( ):-i tisanuser -definedmet hodf r
om whi chtheact ualpr ogram
execut ionst ar t
s.
Stringar gs[]:
-Herewear edef iningaSt ri
ngarrayt opassar gument sat
commandl i
[Link] gsi st hev ariablenameoft heStringar r
ay .Itcanbe
changedt oany thingsuchasSt r
ing[ ]a.
Sy stem: -i
tisapr e-def i
nedcl asss
out :-
iti sapar amet er.
print()
:-itisapr e-def i
nedmet hodt opr inttheout putont hescreen.
Oper ator s:
-
Thesear et hespeci alsy mbol swhi char eusedt ooper at
eorper form
taskov ert heoper andorv ariable.
Ty pes:-
[Link] gnmentoper at or :
-usedt oassi gnav aluet othev ari
[Link]
s
oft wot ypes.
i
. si mpl eassi gnment (=)
ex: inta=5;
i
i. compoundassi gnment (+=,-=,
*=,/=)
ex: sum+=i ;
[Link] aloper ator:-
i
. commaoper at or:-usedt osepar ateconst ants,variabl
eand
ex pr essions.
Ex :-
const antsepar ati
oni nta[ ]=newi nt {
1,2,3,4,
5};
v ariablesepar at i
on i nta,b,c;
expr essionsepar at i
oni nta=5,b=4;
i
i. semi colon:-usedt oter minat eal i
neofcode.
ex: inta=9;
i
ii. concat enat i
on oper at or:-used t o concat enate string wit
h
v ariablebyt hehel poft hesy mbol (+).
Ex :-Sy stem. out .print(“addi t
ionv alue=”+c) ;
[Link] i
thmet ic oper at or:-used t o per form mat hemat i
caloper ati
on
ov eroper andsusi ngdi fferentt ypesofsy mbol sli
ke+,-,
*,/
,%.
(2)Wr i
teapr ogr am t oaddt woi nt egernumber?
classAddi ti
on
{
publ i
cst aticv oidmai n(St ringar gs[ ]
)
{
i
nta=5, b=4,c;
c=a+b;
Sy stem. [Link](“additionv alue=” +c) ;
}
}
Howt ot akeuseri nputf rom key boar d:-
Process1: -usi ngScannercl ass
(3)Wr iteapr ogram t oinputanumberanddi splayi
t?
i
mpor tj
av a.
ut i
l.*;
classx
{
publ icstaticv oidmai n( Stri
ngar gs[
])
{
i
nta;
Scannersc=newScanner (System.i
n);
Sy stem. [Link](“enteranumber ”);
a=sc. nex tI
nt();
Sy stem. [Link](“valueofa=” +a);
}
}
Descr i
ption:-
Scanneri sapr edef i
nedcl asswhi chisusedt otakeuser-
inputfrom
key boar dbutf ort hi
swehav et oaddapre-defi
nedpackagecalledi
mpor t
j
av [Link] i
l
.*;I
tisj ustl i
keheaderf i
lesi
ncandc++.
Process2: -usi ngBuf fer edclass
(4)Wr iteapr ogram t oinputanumberanddi splayi
t?
i
mpor tj
av a.
io.* ;
classx
{
publ ic static void main(
Stri
ng ar
gs[
]) t
hrows
IOEx cept i
on,Ar it
hmet icEx cepti
on
{
Buf feredReaderbr =newBuf feredReader
(new
Input StreamReader (Sy [Link]));
Sy stem. [Link](“enteranumber ”);
Strings=br .
readLi ne();
i
ntn=I nteger .
par seInt(s) ;
Sy stem. [Link](“valueofn=” +n);
}
}
Descr i
ption:-
Buf feredReaderi sapr edefinedclasswhichi susedt ot
akeuser -
input
from key boar dbutf ort hiswehav etoaddapr e-def
inedpackagecalled
i
mpor tj
av a.
io.* ;
Itisjustl ikeheaderf i
lesi ncandc++.
Pr ocess3: -usingcommandl i
near gument
(5) Writ
eapr ogr am toinputt wov aluesanddi splayit?
classx
{
publ i
cst at i
cv oidmai n( Str
ingargs[])
{
Sy stem. out .
println(
args[ 0]
);
Sy stem. out .
println(
args[ 1]
);
}
}
Not e:-pr int()isusedt opr i
ntmessagesi nacont i
nuouslineont he
scr eenwher easpr intl
n( )isusedt oprintmessagesi ndif
fer
entdif
fer
ent
l
inesont hescr een.
(6) Writ
eapr ogr am tof indtheareaandci rcumf erenceofacircl
e?
classCi rcl e
{
publ i
cst at i
cv oidmai n( Str
ingargs[])
{
floatr=7, a,c;
a=3. 141* r*r;
c=2* 3.141* r
;
Sy stem. out .
println(
“areaofci rcl
e=”+a);
Sy stem. out .
println(
“ci
rcumf er
enceofci rcl
e=”+c);
}
}
(7) Writ
eapr ogr am toswapt woi ntegernumberusi ngthi
rdvari
abl
e?
classSwap
{
publ i
cst at i
cv oidmai n( Str
ingargs[]))
{
i
nta=8, b=7, c;
c=a;
a=b;
b=c;
Sy stem. out .
println(
“afterswappi ngv al
ueofa=” +a);
Sy stem. out .
println(
“afterswappi ngv al
ueofb=” +b);
}
}
(8)Wr i
teapr ogram t oswapt woi ntegernumberwi thoutusingthird
var i
able?
classSwap
{
publ i
cst at
icv oidmai n(St
ri
ngar gs[]
) )
{
i
nta=8, b=7;
a=a+b;
b=a- b;
a=a- b;
Sy [Link]
n(“aft
erswappi ngv alueofa=” +a);
Sy [Link]
n(“aft
erswappi ngv alueofb=” +b);
}
}
(8)Wr i
teapr ogram t oswapt woi ntegernumberusi ngbi t
wiseoperator?
classSwap
{
publ i
cst at
icv oidmai n(St
ri
ngar gs[]
) )
{
i
nta=8, b=7;
a=a^ b;
b=a^ b;
a=a^ b;
Sy [Link]
n(“aft
erswappi ngv alueofa=” +a);
Sy [Link]
n(“aft
erswappi ngv alueofb=” +b);
}
}
[Link] ati
onal /compar i
sionoper at or:
-usedt ocompar ebetweent wo
ormor eoper andsusingdifferentsy mbolsl i
ke>,<,
>=,<=,
==,!
=.
[Link] cal/ booleanoper ator
:-usedt operforml ogicaloperati
onlike
producingt rue/fal
sev al
ueusi ngand, or
,not,xorgate.
AND( &&) OR(||
) NOT( !) XOR(^)
T T- >T T T->T T->F T T->F
T F- >F T F->T F->T T F->T
F T- >F F T->T F T->T
F F-
>F F F-
>F F F-
>F
{ * * * * *
for(j
=i;
j<=4;j++) * * * * * * *
Sy st
em. [Link](““)
; * * * * * * * * *
for(j
=1;j<=k;j
++)
Sy st
em. [Link](“*
”);
Sy st
em. [Link]
n(“”)
;
}
}
}
(43)Wr iteapr ogr am toprintf
loydtr
iangl
euptofi
ver ows?
classSer i
es4 1
{
2 3
Publicst ati
cv oidmai n(Str
ingargs[
])
{ 4 5 6
i
nti ,
j
,k=1; 7 8 9 10
11 12 13 14
15
for(i
=1; i
<=5; i++)
{
for(j
=1; j
<=i ;
j++)
{
Sy stem. out .
print(k);
k++;
}
Sy stem. out .
println(“”);
}
}
}
(44)Wr i
teapr ogr am togener at
epascalt r
iangleupt ofiv
erows?
classSer i
es5
{
publ i
cst aticv oidmai n(Stri
ngargs[ ]
)
{
i
nti ,
j,space, coef =1;
for(i
=1; i
<=5; i++)
{
for(space=1; space<=5- i
;space++)
Sy stem. out .
print(““);
1
for(j
=0; j
<=i ;
j++)
1 1
{
i
f(j==0| |
i
==0) 1 2 1
coef =1; 1 3 3 1
else 1 4 6 4 1
coef =coef *(i-j
+1) /j;
Sy stem. out .
print(coef )
;
}
Sy stem. out .
println(“”);
}
}
}
[Link] eachl oop: -
St
ar tedwi thakey wor [Link] ar i
ngandi nit
ial
i
zinga
l
oopcount ervariablewedecl ar
eav ari
ablet hatisthesamet y
pe
ast hebaset ypeoft hear rayfollowedbyacol ontoaccesst he
el
ement sofsamet ype.
Syn:-for(typevar i
able:
array)
{
St
atement (s);
}
(45)Wr i
teapr ogr am forforeachl oop?
classSer i
es6
{
publicstaticv oidmai n(Str
ingar gs[]
)
{
i
nta[ ]
={1,2,3,4,
5};
for(i
nti:
a)
{
Sy st
em. [Link]
ln(i
);
}
}
}
Ar
ray
(CH-
4)
Arrayi sader iv
eddat atypei nj avapr ogrammi ngl [Link] he
coll
ectionofhomogeneousdat aorsi milartypeofdat [Link]
arr
aysay st hatwecanst or emor et hanoneel ement /val
ueofsi milar
ty
pei nsideasi nglevar iabl
ebydef iningasubscr i
ptorsi [Link]
lthear ray
el
ement sar eaccessedbyt hehelpofanuni quei ndexnumberwhi chi s
bydef aultstartsfrom z erobutwecanst artitfrom anyot hernumber .
Types:-
[Link] ngleDi mensional Ar r
ay/OneDi mensi onal Array(
1d)
[Link] eDimensi onal Array/TwoDi mensi onal Array(2d)
[Link] tidimensional Arr
ay (
3d)
1.1d: -
Whenev erthear rayelement sar est oredi nsideasi nglevar
iableby
def i
ning a si ngle subscr i
ptorsi ze t hen iti s call
ed as single
dimensi onalarray .
sy n:-
<dat a-type><variable-name>[ size];
or
sy n:-
dat atypev ari
able=newdat atype[ si
ze];
[Link] let i
mear ray :
-
(46) Wr iteapr ogr am t odi splayacompi l
et i
mear r
ay?
classAr ray1
{
publ icst at
icv oidmai n(Stringar gs[])
{
i
nta[ 5]={23,6,
90, 1,56} ;
Sy stem. [Link]
n( “firstelement =”+a[0]
);
Sy stem. [Link]
n( “secondel ement =”+a[1])
;
Sy stem. [Link]
n( “thirdel ement =”+a[2]);
Sy stem. [Link]
n( “four t
hel ement =”+a[3])
;
Sy stem. [Link]
n( “fifthelement =”+a[4]
) ;
}
[Link] ray :-
(47) Wr iteapr ogr am t odi splaya1dar r
ayatr unt
ime?
i
mpor [Link]
l.*;
classAr ray1
{
publ icst at
icv oidmai n(Stringar gs[])
{
i
nta[ ]
=newi nt[100] ,
i,n;
Scannersc=newScanner (Sy stem. in);
Sy stem. [Link]
n( “ent ert herange” );
n=sc. next I
nt();
Sy stem. [Link]
n( “ent erel ement s”)
;
for( i
=0;i<n;
i++)
{
a[i]=[Link]();
}
Sy stem. [Link]
n( element sar e”);
for( i
=0;i<n;
i++)
{
Sy stem. [Link]
n( a[i]);
}
}
}
(48) Wr iteapr ogram t osor tal lthear rayelementsinascendi
ngor
der
usi ngbubbl esor t?
i
mpor tj
av a. uti
l.*
;
classAr ray 2
{
publ icstat icv oidmai n(St
ringargs[])
{
i
nta[ ]
=newi nt[100],
i,n,j
,
temp;
Scannersc=newScanner (Sy st
[Link]);
Sy stem. out .printl
n(“enterther ange”);
n=sc. next Int();
Sy stem. out .printl
n(“enterel ements”)
;
for( i
=0;i
<n; i++)
{
a[i]=[Link] Int();
}
for( i
=0;i
<num- 1;i
++)
for( j
=i+1;j<num; j
++)
{
i
f(a[ i
]>a[j
])
{
temp=a[ i]
;
a[i]=a[j]
;
a[j]=temp;
}
}
Sy stem. out .printl
n(“element si
nascendingor
derusi
ngbubbl
esor
tare”);
for( i
=0;i
<n; i++)
{
Sy stem. out .printl
n(a[i])
;
}
}
}
(49) Wr i
teapr ogram t of i
ndt hel ar
gestandsmall
estel
ementpresent
i
nsi det hear r
ay?
i
mpor tj
av a. uti
l.*
;
classAr ray 2
{
publ icst ati
cv oi dmai n(Stringar gs[])
{
i
nta[ 100] ,
i
,n,l
ar ge,small;
Scannersc=newScanner (Sy stem. in);
Sy stem. [Link](“
ent erther ange” );
n=sc. next I
nt( )
;
Sy stem. [Link](“
ent erel ement s”)
;
for( i
=0;i<n;i
++)
{
a[i]=[Link] I
nt() ;
}
l
ar ge=a[ 0];
for( i
=1;i<n;i
++)
{
i
f(a[ i
]>large)
l
ar ge=a[ i];
}
smal l
=a[ 0];
for( i
=0;i<num; i++)
{
i
f(a[ i
]<smal l)
smal l
=a[ i
];
}
Sy stem. [Link](“
largestel ementi s=”
+large)
;
Sy stem. [Link](“
smal lestel ementi s=”+small
);
}
}
(50) Wr iteapr ogr am t osear chf oranel ementusingl
inearsear
ch?
i
mpor [Link]
.*;
classAr ray4
{
publ icst ati
cv oi dmai n(Stringar gs[])
{
i
nta[ 100] ,
i
,n,s,
count er;
Scannersc=newScanner (Sy stem. in);
Sy stem. [Link](“
ent erther ange” );
n=sc. next I
nt( )
;
Sy stem. out .pr
intl
n(“enterelement s”);
for( i
=0;i
<n; i++)
{
a[i]=[Link] Int
();
}
Sy stem. out .pr
intl
n(“entertheelementt osearch\n”
);
s=sc. nex tInt()
;
for( i
=0;i
<n; i++)
{
i
f(a[ i
]==s)
count er
=1;
}
i
f(count er==1)
Sy stem. out .pr
intl
n(“el
ement sf
ound” )
;
else
Sy stem. out .pr
intl
n(“el
ementnotf ound” );
}
}
(51) Wr i
teapr ogram t odisplayallt hearrayelementsi
nrev
erseor
der?
i
mpor tj
av a. ut
il
.*
;
classAr ray 5
{
publ icst aticvoidmai n(Str
ingar gs[])
{
i
nta[ 100] ,
i,
n;
Scannersc=newScanner (
Sy st
em. in);
Sy stem. out .pr
intl
n(“entertherange” );
n=sc. next Int()
;
Sy stem. out .pr
intl
n(“enterelement s”);
for( i
=0;i
<n; i++)
{
a[i]=[Link] Int
();
}
for( i
=n-1;i>=0;i-
-)
{
Sy stem. out .pr
intl
n(a[i
])
;
}
}
}
(52) Wr iteapr ogram t oinsertanel ementintoanar r
ay?
i
mpor tjava. util
.*
;
classAr ray 6
{
publ icst aticv oidmai n(Str
ingar gs[])
{
i
nta[ 100] ,
i,
n, k,
p;
Scannersc=newScanner (
Sy st
em. in);
Sy stem. out .printl
n(“entertherange” );
n=sc. next Int( )
;
Sy stem. out .printl
n(“enterelement s”);
for( i
=0;i<n;i++)
{
a[i]=[Link] Int();
}
Sy stem. out .printl
n(“enterthelocat i
ontoenter\”)
;
p=sc. next Int( )
;
Sy stem. out .printl
n(“entertheelementt oi
nsert
\n”)
;
k=sc. next Int();
for( i
=n-1;i>=p; i-
-)
{
a[i+1]=a[ i]
;
a[p- 1]=k;
}
Sy stem. out .printl
n(arrayelement sar e\
n”)
;
for( i
=0;i<n;i++)
{
Sy stem. out .printl
n(a[i
]);
}
}
}
(53) wr i
teapr ogram todel eteanel ementfr
om anarray?
i
mpor tjava. util
.*
;
classAr ray 6
{
publ icst aticv oi dmai n(Stringar gs[])
{
i
nta[ 100] ,
i,
n, k;
Scannersc=newScanner (Sy [Link]);
Sy stem. out .pr i
nt l
n(“entert herange” );
n=sc. next Int( );
Sy stem. out .pr i
nt l
n(“enterel ement s”)
;
for( i
=0;i<n;i++)
{
a[i]=[Link] Int ();
}
Sy stem. out .pr i
nt l
n(“entert helocat i
ont odel ete”);
k=sc. next Int();
i
f(k>=n+1)
Sy stem. out .pr i
nt l
n(“del
et i
onnotpossi bl
e”) ;
else
for( i
=k-1;i<n- 1;i++)
{
a[i]=a[i+1];
}
Sy stem. out .pr i
nt l
n(“arr
ayel ement sare”);
for( i
=0;i<n;i++)
{
Sy stem. out .pr i
nt l
n(a[i
])
;
}
}
}
2.2d: -
Whenev ert hear rayel ement sar est oredi nsi
deasi nglevar
iabl
eby
defining t wo subscr i
ptorsi ze t hen i tis called as doubl
e
dimensi onal arr
ay .
syn:-sy n:-<data-t
y pe><v ari
able-name>[ size1]
[si
ze2]
;
or
syn:-dat at ypev ar
iabl e=newdat atype[row] [
column];
(54) Wr iteapr ogr am todi splayamxnmat ri
x?
i
mpor tjava. util.*;
classAr ray 10
{
publ icst at i
cv oidmain(Stringar gs[])
{
i
nta[ ]
[]=newi nt [
100][
100],
i,j
,row,col;
Scannersc=newScanner (Sy [Link]);
Sy stem. [Link]
n(“
enterther owsi ze”
);
row=sc. nex t
Int();
Sy stem. [Link]
n(“
enterthecol umnsi ze”
);
col =[Link] tI
nt();
Sy stem. [Link]
n(“
enterel ement s”);
for(i=0;i<r ow;i++)
{
for(j=0;j<col ;
j++)
{
a[i][
j]
=sc. nex t
Int()
;
}
Sy stem. [Link]
n(“
”);
}
Sy stem. [Link]
n(“
element sare”);
for(i=0;i<r ow;i++)
{
for(j=0;j<col ;
j++)
{
Sy stem. [Link](
a[i
][
j]
);
}
Sy stem. [Link]
n(“
”);
}
}
}
(55) Wr iteapr ogram tofindt hetransposeof3x3mat
ri
x?
i
mpor tjav [Link]
.*;
classAr ray10
{
publ icst at i
cv oidmain(Stringar gs[])
{
i
nta[ 3][3],i,
j
;
Scannersc=newScanner (Sy [Link]);
Sy stem. [Link]
ln(“
enterel ement s”)
;
for(i=0;i
<3;i++)
{
for(j=0;j
<3;j++)
{
a[i][
j]
=sc. nex t
Int()
;
}
Sy stem. [Link]
ln(“
”);
}
Sy stem. [Link]
ln(“
mat r
ixt ransposei s”
);
for(j=0;j
<3;j++)
{
for(i=0;i
<3;i++)
{
Sy stem. [Link]
(a[j
][
i]
);
}
Sy stem. [Link]
ln(“
”);
}
}
}
(56) Wr i
teapr ogram todispl ayt hediagonalel
ement
sofa3x3mat
ri
x?
i
mpor tj
av [Link]
l.*
;
classAr ray11
{
publ icstaticv oidmain(Stringar gs[])
{
i
nta[ 3][
3],i
,j
;
Scannersc=newScanner (Sy [Link]);
Sy stem. [Link]
ln(“
enterel ement s”)
;
for(i=0;i
<3;i++)
{
for(j=0;j
<3;j++)
{
a[i][
j]
=sc. nex t
Int()
;
}
Sy stem. [Link]
ln(“
”);
}
Syst
[Link].
pri
ntl
n(“
diagonal
element
sar
e”)
;
for
(i
=0;
i<3;
i
++)
{
for
(j
=0;
j<3;
j
++)
{
i
f(i
==j
)
Syst
[Link].
pri
nt(
a[j
][
i]
);
}
Syst
[Link].
pri
ntl
n(“
”);
}
}
}
[Link]: -
Whenev erthear rayel ementsar estor
edinsideasingl
ev ar
iabl
eby
definingmor ethant wosubscr iptorsi
zethenitiscall
edasmul t
i
di
mensi onal arr
ay .
syn:-<dat a-t
y pe><variable-
name>[ si
ze1]
..
.[
sizen]
;
(57) Wr i
t eapr ogram t odispl aya3x3x3mat r
ix?
i
mpor tjava. uti
l.*;
classAr ray 12
{
publ icst ati
cv oidmai n(Stringargs[])
{
i
nta[ ]
[][
]=newi nt[3][
3][
3],i
,j
,k;
Scannersc=newScanner (Sy st
[Link]);
Sy stem. out .printl
n(“enterel ements”)
;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0; k<3; k++)
{
a[i][
j]
[k]=sc. next I
nt();
}
Sy stem. out .printl
n(“”)
;
}
System.
[Link]
ntl
n(“”)
;
}
System.
[Link]
ntl
n(“el
ement sar
e”)
;
for
(i
=0;i
<3;
i++)
{
for
(j
=0;j
<3;
j++)
{
for
(k=0;
k<3;k++)
{
System.
[Link]
ntl
n(a[i
][
j]
[k]
);
}
System.
[Link]
ntl
n(“”)
;
}
System.
[Link]
ntl
n(“”)
;
}
}
}
St
ri
ngHandl
ing(
CH-
5)
Stri
ngi sasequenceofchar acter
[Link]
ngi sapre-definedclassi
njav
a
whichcomesundert hepackage“ i
mportjava.
lang.*
” .A str
ingcanbe
createdint wodi f
ferentway s.
[Link] r
inglit
eral:
-
Syn:-St ri
ng<st r
ingv ariablename>;
Ex:-Stri
ngname=” ani l
”;
[Link] wor d:-
Syn:-String<stri
ngv ariablename>=newSt r
ing(“
stri
ngv alue”
);
Ex:-Stri
ngname=newSt ring(“
anil
”);
(58)Wr i
teasi mpl epr ogr am forStri
ngclass?
publicclassSt ri
ngExampl e
{
publicstaticvoidmai n(Stringargs[]
)
{
Stri
ngs1=" java";
charch[] ={'
s',
'
t'
,'
r'
,'
i'
,
'n',
'g',
'
s'};
Stri
ngs2=newSt ri
ng( ch);
Stri
ngs3=newSt ri
ng( "exampl e");
System. [Link]
intl
n(s1) ;
Syst
[Link]
.pr
intl
n(s2)
;
Syst
[Link]
.pr
intl
n(s3)
;
}
}
Pr
edefi
nedStringMethods:
-
No. Met
hod Descr
ipt
ion
1 charchar
At(
inti
ndex) r
etur
ns charvalue f
or
t
hepart
icul
ari
ndex
2 i
ntl
engt
h() r
etur
nsst
ri
ngl
engt
h
3 st
ati
c St r
ing for
mat
(St
ri
ng f
ormat
, r
etur
nsf
ormat
tedst
ri
ng
Obj
ect.
..args)
4 stati
c Str
ing for
mat (
Local
el,St
ri
ng r
etur
nsfor
matt
edst
ri
ng
format,Object
..
.args) wi
thgiv
enl
ocal
e
5 St
ri
ngsubst
ri
ng(
intbegi
nIndex) ret
urns subst
ri
ng f
or
giv
enbegi
nindex
6 Str
ing subst
ri
ng(
int begi
nIndex,i
nt ret
urns substr
ing for
endIndex
) giv
en beginindex and
endindex
7 bool
eancont
ains(
Char
Sequences) ret
urns tr
ue or f al
se
aft
er mat chi
ng t he
sequenceofcharv
alue
8 stat
ic St r
ing j oin(
CharSequence r
etur
nsaj
oinedst
ri
ng
deli
mit
er,
CharSequence..
.el
ements)
9 stat
ic St ri
ng j oi
n(CharSequence r
etur
nsaj
oinedst
ri
ng
deli
miter
, I
ter
able<? extends
CharSequence>el
ement s)
10 bool
eanequal
s(Obj
ectanot
her
) checks t
he equal
it
y of
str
ingwit
hobject
11 bool
eani
sEmpt
y() checksi
fst
ri
ngi
sempt
y
12 St
ri
ngconcat
(St
ri
ngst
r) concati
nat
es speci
fi
ed
str
ing
13 St
ri
ngr
epl
ace(
charol
d,charnew) repl
acesalloccur
rences
ofspeci
fi
edcharv al
ue
14 St
ring r epl
ace(
CharSequence ol
d, repl
acesalloccurrences
CharSequencenew) of specif
ied
CharSequence
15 stat
icStri
ngequal
sIgnor
eCase(
Str
ing compares anot
her
another
) str
ing.I
tdoesn'
tcheck
case.
16 St
ri
ng[
]spl
i
t(St
ri
ngr
egex) r
eturns spl
it
ted st
ri
ng
matchi
ngregex
17 St
ri
ng[
]spl
i
t(St
ri
ngr
egex,
intl
i
mit
) r
eturns spl
i
tted st
ri
ng
matchi
ng r egex and
l
imit
18 St
ri
ngi
nter
n() r
etur
nsi
nter
nedst
ri
ng
19 i
nti
ndexOf
(i
ntch) r
etur
ns speci
fi
ed char
v
alueindex
20 i
nti
ndexOf
(i
ntch,
intf
romI
ndex) ret
urns speci
fi
ed char
val
ueindexstar
ti
ngwith
giv
enindex
21 i
nti
ndexOf
(St
ri
ngsubst
ri
ng) r
etur
ns speci
fi
ed
subst
ri
ngi
ndex
22 i
nt i
ndexOf(
Str
ing subst
ri
ng, i
nt ret
urns speci
fi
ed
f
romI
ndex) substr
ingindexstar
ti
ng
wit
hgiv eni
ndex
23 St
ri
ngt
oLower
Case(
) r
etur
ns st
ri
ng i
n
l
owercase.
24 St
ri
ngt
oLower
Case(
Local
el) ret
urns st
ring i
n
l
ower case usi
ng
specifi
edlocale.
25 St
ri
ngt
oUpper
Case(
) ret
urns st
ri
ng i
n
uppercase.
26 St
ri
ngt
oUpper
Case(
Local
el) ret
urns st
ring i
n
uppercase usi
ng
specif
iedl
ocale.
27 St
ri
ngt
ri
m() removesbegi nni
ng and
ending spaces oft hi
s
str
ing.
28 st
ati
cSt
ri
ngv
alueOf
(i
ntv
alue) convert
sgiventypeinto
str
ing.I
tisover
loaded.
[Link]
ass: -
Stri
ngBuf feris a peer cl ass ofStri
ngt hat prov
ides much of t he
funct i
onali
ty of st ri
[Link] ri
ng representsf i
xed-l
engt h,i mmutable
char acter sequences whi le Str
ingBuffer r
epresents gr owabl
e and
writablechar [Link] ri
ngBuf f
ermayhav e char act
ersand
subst ri
ngs inserted int he middle orappended t ot he end.I twil
l
automat i
call
ygrowt omaker oom f
orsuchaddi t
ionsandof tenhasmor e
char acterspreallocat
edt hanar eactuallyneeded,to al low room for
growt h.
Met hods: -
1.i nsert
(posi
tion,”
str
ing”)
2.r ever se( )
[Link] et e()
[Link] et eChar At()
5.r eplace( startpos,endpos, ”str
ing”)
6.i ndex Of ()
7.l ast Index Of()
[Link] r
ing( startpos,endpos)
9.t oSt ri
ng( )
(59) Wr iteasi mpl epr ogram f orStr i
ngBufferclass?
i
mpor tjav a.i
o. *;
classAni l
{
publ i
cst aticv oidmai n(String[]args)
{
St ri
ngBuf fers=newSt ringBuf fer("
hell
oanil")
;
[Link]( "wel come" );
Sy stem. out .
pr i
ntln(s);
[Link]( 1);
Sy stem. out .
pr i
ntln(s);
}
}
[Link] ri
ngBui ldercl ass: -
Jav aSt ri
ngBui l
dercl assi susedt ocr eatemut able(modifi
able)stri
ng.
TheJav aSt ringBui lderclassi ssameasSt ri
ngBuf fercl
assexceptthatit
i
snon- sy nchr oni zed.I tisav ail
ablesi nceJDK1. [Link]
idesanAPI
compat i
bl ewi thSt ri
ngBuf fer,butwi thnoguar anteeofsynchronizat
ion.
(60) Wr iteapr ogram f orSt ri
ngBui lderclass?
i
mpor tjav a.i
o. *;
classSt ringBui l
der Exampl e
{
publ icst aticv oidmai n( Str
ingar gs[])
{
StringBui ldersb=newSt ri
ngBui lder("Hell
o");
sb. append( "cor e");
Sy stem. out .pr i
ntln(sb) ;
sb. i
nser t(1,"Jav a");
Sy stem. out .pr i
ntln(sb) ;
}
}
Met hods: -
1.i nser t(
)
[Link] erse( )
[Link] Of ()
[Link] I
ndex Of (
)
[Link] ri
ng()
[Link] ri
ng( )
[Link]( )
Wapf orf indi ngacronym.
Wapt ot akeuseri nputstri
ngusi ngiopackage.
i
mpor tjav [Link].*;cl
assDemo
{
publicst aticvoidmai n(
St r
ingargs[
])
{
Stri
ngname=" pr
abhatkumarsi ngh";
Stri
ngwor ds[]=name. spli
t(
"");
for(Stringwor d: words)
{
Syst em. [Link]
nt(
[Link](0)
+"."
);
}
}
}
classDemo{
publicstaticv oi
dmai n(St
ri
ngargs[
])throwsIOException{
Str
ings;
BufferedReader ob = new Buff
eredReader
(new
InputStreamReader (System. i
n));
System. out.
printl
n("
Enterast
r i
ng");
s=ob. readLine( )
;
System. out.
printl
n("
YouenteredSt r
ing"+s);
}
}
Wapt ot akeuseri nputst ringusinguti
lpackage.
i
mpor [Link]
l.
Scanner ;
classDemo{
publicstaticv oi
dmai n(St
ri
ngargs[
]){
Str
ings;
Scannersc=newScanner ([Link])
;
System. out.
printl
n("
Enterast
r i
ng");
s=sc. nex t
Line();
System. out.
printl
n("
YouenteredSt r
ing"+s);
}
}
Waptot akeuseri nputacharacterusi
ngutilpackage.
i
[Link]
l.
Scanner;
cl
assDemo{
publicstaticvoi
dmai n(
Stri
ngargs[
]){
chars;
Scannersc=newScanner (Syst
em. i
n);
[Link].
pri
ntl
n("
Enterachar"
);
s=sc. next
().
char
At(0);
[Link].
pri
ntl
n("
Youenteredcharacter"
+s)
;
}
}
St
ri
ng StringBuf f
er StringBui lder
Sl
ower
. Lessef fici
ent/Faster
. Mor eef f
icient/
Faster
.
I
mmutabl
emeans Mut ablest r
ingclass. Mut abl e/modi f
iabl
e
str
ingcl ass.
whenev er we do St ringBuf f
er StringBui l
der isnon-
Str
ing mani pulat
ion i
ssy nchronizedi.
e. synchr oni zedi.
e. not
l
ike concat enati
on,t hread saf [Link] t hread saf e. I
t means
substri
ng et c, i tt wo t hreadscan' tcallt wot hreadscancal lthe
generates a new t he met hods of met hodsofSt ri
ngBuil
der
Str
ing and di scards StringBuf f
er simul taneousl y.
the older St
ring for simul t
aneousl y.
garbagecoll
ection.
Cl
assandObj
ect
(CH-
6)
Class:-
Acl assi sanuser -
defi
neddatatypeinjav awhi chcanbecr eatedbyt he
helpofcl asskey [Link] hecol lectionofdi ssimilartypeof
relat
eddat a.I
tdescri
besaboutapar t
icularpl aceorper [Link] assi s
alsocal l
edasanent it
ywhi chcontai
nsdi ff
er entdat
[Link] assconsistsof
twocomponent s.
[Link] amember :-t hese are just l i
ke v ari
ables t o hol d dat a.
Datamember sar edeclaredatt het opoft hecl assdecl arati
on
preceededbydat atypemeanswhi cht ypeofdat ai tcanhol [Link]:-
rol
l,
address,aetc.
[Link] hods:
-thesear enot
hingbutt hememberf unct i
onsj ustli
kein
cwhi char eusedt ooper atet hedat amember si nsidetheclass
pr ogr [Link] hodsmustpr eceededbyar eturntypet osaywhet her
itret ur nsav al ueorpr intsomet [Link]:-voidshow( ),
intget(
)etc.
Sy n:-
class<cl assname>
{
<Accessspeci f
ier>Ty pedat amember 1;
.
.
<Accessspeci f
ier>Ty pedat amember n;
Access- speci f
ierret urntypemet hod1( )
{
//body
}
.
.
Access- speci f
ierret urntypemet hodn( )
{
//body
}
}
Obj ect:-
Itisani nst ance/ copyofacl asswhi chi susedt oaccessal lthemethods
byt hehel pofdotoper [Link] ngobj ectwecanaccessal lthedat a
member st hr ought heobj ectinsidemai n().Therear ethreet echni
quest o
i
ni ti
ali
zeanobj ect.
[Link] efer encev ari
able
[Link] hod
[Link] r
uct or
Sy n:-classnameobj ectname=newcl assname( )
;
Accessspeci fi
er:-
Thesear eal socal ledasmodi f
ierswhi char eusedt opr ov i
desecurit
yt o
thecl asspr ogram.I tprov i
desaccessr estri
ctionst othemember sso
thatt hey can r est ri
ctly used i nsi
de t he progr am accor ding tot he
progr ammer ’
schoi [Link] eare4t y
pesofaccessspeci fiersavail
abl
ei n
j
av a.
[Link] ivat e:-ifanymemberi sdecl ared aspr i
vatet hen itcan be
accessedi nt hatcl assonl ywher ei tisdecar ed.
[Link] ic:-
ifany memberi s decl ared as publ ict hen itcan be
accessedany wher einsidet hepr ogram insideanycl ass.
[Link] ot ected:-itisusedi ncaseofi nheritancepr ogrammi ngwherewe
usemor et hanonecl [Link] susedwhenwewantt oshareone
cl
assdat awi thsomesel ect edclassesi ndisethepr ogram andnot
al
lcl assesandt hecl assi smusti nherit
edi not hercl asseswhere
wewantt oshar et hedat a.
[Link] aul t/noaccess: -
itisusedwhennoaccessmodi fi
erispresent.
Any cl ass, f ield, met hod or const ructor t hat has no
declar edaccessmodi f
ierisaccessi bleonl ybycl assesi nthesame
[Link] aultmodi fierisnotusedf orf i
eldsandmet hods
withinani nter f
ace.
(61) Wr i
teapr ogr amusi ngcl asst oconv ertCel si
ust of ahrenhiet?
classConv ert
{
doubl ef ,
c;
voidshow( )
{
c=39;
f=c* 9/5+32;
Sy stem. out .print(
“ Fahrenhei tv al
ue=” +f);
}
publ icstat icv oidmai n( Str
ingar gs[ ]
)
{
Conv ertx 1=newConv er t()
;
x1. show( );
}
}
(62)Wr i
teapr ogr am usi ngcl asst oconv ertfahr enhieti nt
oCel si
us
scal e?
classConv ert
{
doubl ef ,
c;
voidshow( )
{
f=98. 7;
c=( f-32) *5/9;
Sy st em. [Link]
(“Celsiusv alue=”+c);
}
}
publ i
ccl assConv er t
1
{
publ i
cst ati
cv oidmai n( Stri
ngar gs[
])
{
Conv ertx 1=newConv ert();
x1. show( )
;
}
}
(63) Wr i
t eapr ogram t of indther ever
seofanumberusi
ngcl
ass?
i
mpor [Link]
.*
;
classRev erse1
{
i
ntnum, rem, r
ev ;
voidcal ( )
{
Scannersc=newScanner (System.i
n);
Sy st em. [Link]
ln(“enteranumber ”);
num=sc. nex t
Int(
);
whi le( num! =0)
{
rem=num%10;
rev =r ev*10+r em;
num=num/ 10;
}
Sy st em. [Link]
(“reversev alue=”+rev)
;
}
publ i
cst ati
cv oidmai n( Stri
ngar gs[
])
{
Rev erse1obj =newRev erse1();
obj .cal (
);
}
}
Innercl ass: -
Inj avai nnercl assi sal socal ledasnest [Link] assi s
wr i
tteni nsi deanot herclasst heni tiscalledasinnerclass.
Ty pes: -
[Link] at i
ci nnercl ass:-
Ast at i
ccl assi .
[Link]
edinsideacl assi scalled
static nest ed cl ass inj av a.I tcannotaccess non- static data
member sandmet hods.I tcanbeaccessedbyout erclassname.I t
can access st atic dat a member s of outer class i ncluding
privat [Link] ed cl asscannotaccessnon- stat
ic( instance)
dat amemberormet hod.
(64) Wr iteapr ogram f orst ati
ci nnercl ass?
classOut er
{
statici nta=30;
staticcl assI nner
{
voidmsg( )
{
Sy stem. out .
println("
valueofa" +a) ;
}
}
publ icst at i
cv oidmai n(Stri
ngar gs[ ])
{
Out er .
Innerobj =newOut er.
Inner ( );
obj .
msg( );
}
}
[Link] -statici nnerclass:-i tispopul arlycal
l
edasi [Link] a
i
nnercl asshasaccesst oal loft hemethodsandv ariablesev en
theyar epr ivate oft heencl osingcl assasi fthesemet hodsand
variabl es hav e been decl ared wi t
hinthe innercl [Link] he
opposi tei snott rue;encl osi ngcl asscannotaccessdi rectl
yt he
member sofi nnercl ass.
(65) Wr iteapr ogram f ornon- stat ici nnerclass?
publ icclassOut er
{
privatei nta=10;
publ icv oidabc( )
{
Inneri =newI nner ();
i
.get ()
;
}
classI nner
{
publ i
cv oi dget ()
{
Sy stem. out .print(
a);
}
}
publ i
cst aticv oidmai n(St
ringargs[]
)
{
Out ero=newOut er(
);
[Link]( );
}
}
3.L ocali nnercl ass:-
Acl assi .
[Link]
edi nsideamethodiscall
ed
locali nnercl assi njava.I
fy ouwanttoi nvokethemet
hodsoflocal
innercl ass, y
oumusti nstanti
atethi
sclassinsidet
hemethod.
(66) Wr i
teapr ogram f orl
ocalinnerclass?
publ i
ccl assLocal
{
privatei nta=30;
voiddi spl ay( )
{
classLocal 1
{
voidmsg( )
{
Sy stem. out .printl
n(a);
}
}
Local 1l 1=newLocal 1();
l
1. msg( );
}
publ i
cst aticv oidmai n(St
ringargs[]
)
{
Local obj =newLocal ();
obj .
displ ay();
}
}
[Link]
mousi
nnercl
ass:
-Acl
asst
hathav
enonamei
sknownas
anony mousi nnercl assi nj [Link] dbeusedi fy ouhavet o
overridemet hodofcl assori nterf
ace.
(67)Wr i
t eapr ogr am f oranony mousi nnercl ass?
abst r
actcl assHel l
o
{
abst r
actv oidhi (
);
}
classMy class{
publicst ati
cv oidmai n( Str
ingar gs[]
)
{
Hel l
oh=newHel l
o( )
{
voidhi (
)
{
Sy st
em. out .
pr intl
n( "hav eani ceday! ")
;
}
};
[Link](
);
}
}
fi
nal l
y:-
Jav af inallybl ocki sabl ockt hati susedt o executei mpor
tant
codesuchascl osi ngconnect ion,stream etc.
Jav afinal l
ybl ocki salway sexecut edwhet herexceptionishandled
ornot .
Jav afinal l
ybl ockf oll
owst ryorcat chblock.
Final l
ybl ocki nj av acanbeusedt oput" cl
eanup"codesuchas
cl
osi ngaf il
e, closi ngconnect i
onet c.
Sy n:
-
fi
nally
{
//statement ;
}
Final:
-
fi
nal key wordi susedi ndifferentcont [Link] l
,finali
sanon-
accessmodi fierappl icableonl ytoav ari
abl e,amethodoracl ass.
[Link] nal variabl e:-
Whenav ariablei sdecl aredwi thf i
nalkeyword,itsv aluecan’
tbe
modi fied,essent i
ally,aconst [Link] sal someanst haty oumust
i
niti
aliz eaf i
nal variable.
ex:-
fi
nal i
nta=5;
[Link] hod: -
Whenamet hodi sdecl aredwi thf i
nal key wor d,itiscal l
edaf inal
met hod.A f inalmet hodcannotbeov er r
[Link] ectclass
doest his—anumberofi tsmet hodsar ef [Link] are
met hodswi thf i
nalkey wordf orwhi chwer equiredt of oll
ow the
samei mpl ement ationt hroughoutal l t
heder ivedcl asses.
Ex:-
fi
nal voi dabc( )
{
//code
}
[Link] ass: -
Whenacl assi sdecl ar
edwi t
hf inal keywor d,i ti scalledaf inal
cl
[Link] i
nal classcannotbeext ended( inher it
ed).
Ex:-
fi
nal classA
{
}
Finali
ze: -
Thej [Link] ect.f
inal
ize()i s cal l
ed by t he gar bage
col l
ectoronanobj ectwhengar bagecol lectiondet ermines
thatt her ear enomor ereferencest otheobj ect.
A subcl ass ov err
ides the f inalizemet hod t o dispose of
sy stem r esour cesort oper form ot hercl eanup.
Ex:-
protect edv oidf i
nalize()
{
//code
}
Const
ruct
or(
CH-
7)
Aconstructorisaspecialtypeofmet hod/
functi
[Link]
ruct
or
namei ssameascl [Link] nadvantageofusingconst
ruct
or
i
swedonothav etocal laconstruct
orinsi
det hemain()asweknow a
constr
uctorisautomatical
lycal
ledwhenanobj ecti
scr eat
ed.
Aconstructordoesn’tr
eturnanyvaluenorhaveanyreturntype.
Types:
-
[Link] aultconst ructor:
-itisthetypeofmethodwhi
chdon’
thaveany
paramet er/argumenti nsidei t
smet hodcal
litonl
yini
ti
ali
zethe
val
uesi nsidei t
sbodypar t.
Syn:-classname( )
{
//i
niti
alizati
on;
}
(68) Wr it
eapr ogram f ordefaultconstr
uct
or?
classFact o
{
i
ntnum, f;
Fact o()
{
num=5;
f=1;
}
voidshow( )
{
whi le(num! =0)
{
f=f* num;
num- -;
Sy stem. [Link]
(“f
act ori
alval
ue=” +f
);
}
}
publ icstaticv oidmai n(Str
ingargs[])
{
Fact ox1=newFact o()
;
x1. show( );
}
}
[Link]
ructor:
-iti
st het ypeofconstr
uct
orwhichi
s
usedt otakeparameter
/argumentasi nputinsi
dei
tsmethodcal
l.
Thev al
uesmustbepassedf r
om themai n(
).
Syn:-cl
assname(ty
peparamet er
1,.
..,
typeparameter
)
{
i
nst ancev ariable=par amet er
name;
}
(69) Wr it
ea pr ogr am t of ind thesum ofdi git
sofa numberusi ng
par amet erizedconst ructor?
classDi git
{
i
ntnum, rem;
Digi t(
intn)
{
num=n;
}
voidshow( )
{
sum=0;
whi le(num! =0)
{
rem=num%10;
sum=sum+r em;
num=num/ 10;
}
Sy stem. out .print(“sum ofdi sgits=”
+sum) ;
}
publ icst aticv oidmai n(Stri
ngar gs[]
)
{
Digi tx1=newDi git(123);
x1. show( )
;
}
}
Thi skey wor d:-
Ifwear eusi ngpar amet erizedconst ruct
orinsi
deapr ogram andinthat
casei ft hei nst ancev ari
abl enamei ssameaspar ameternameoft he
const ruct ort heni tisv erydi f
ficul
tt odiff
erent
iat
ebothoft hem forthe
compi [Link] nt hatcaset hiskeywor disusedtoseparatethem.
Sy n:-[Link] ari
able=par amet ername;
(70) Wr it
eapr ogr am t oswapt woi ntegernumberusingthiskeyword?
classSwap
{
i
nta,b;
Swap( i
nta,i
ntb)
{
thi
s.a=a;
thi
s.b=b;
}
voi
dshow( )
{
i
ntc;
c=a;
a=b;
b=c;
[Link]
int
ln(
“af
terswappi
ngv al
ueofa=”
+a)
;
[Link]
int
ln(
“af
terswappi
ngv al
ueofb=”
+b)
;
}
publi
cstaticvoidmain(St
ri
ngargs[
])
{
Swapobj =newSwap( 4,
5);
obj.
show( )
;
}
}
I
nher
it
ance(
CH-
8)
Inher i
tance:-
i
ti st heconceptwher eonecl assder i
vesthef eaturesofanot [Link]
mai nadv ant
ageofusi nginheritanceiscoder eusuabi l
i
ty.I ninherit
ance
we must r equi re at l
est t wo cl asses; f i
rst cl ass i s cal led
par ent/base/exi sti
ng/ super cl ass wher e anot her cl ass i s cal led
sub/ derived/childcl [Link] assder ivesthef eaturesofanot hercl ass
i
scal ledsubcl asswher easf rom whi chcl assi tisder ivediscal led
super [Link] nheritanceweneedakey wor dcal l
edext [Link]
hav et oonlycr eat eobj ectforchi l
dclassonl ybecausepar entcalssdat a
areal readyav ailableinchi l
dandpar entclassdat ashoul dbepr otected.
Ty pes:-
Likec++j avaal sosuppor tsdifferentt
y pesofi nheritancel ike:
[Link] nglei nher i
tance: -whenonechi ldclassder ivest hef eaturesof
onepar entcl assandt herei snotmor et hant wocl assav ai
lable
insidet hepr ogram i scal l
edsi ngleinher it
[Link] eweal way s
createobj ectforchi l
dcl assonl yandi tcanbeachi evedbyext
ends
key word.
Syn:-class<chi l
dclassname>ext ends<parent
classname>
(71)Wr it
eapr ogr am forsinglei nher i
tance?
classX
{
voidone( )
{
Sy stem. [Link]
n(“hell
o”);
}
}
classYext endsX
{
voidt wo( )
{
Sy stem. [Link]
n(“hi
” )
;
}
publ i
cst ati
cv oidmai n(Stri
ngar gs[]
)
{
Yobj =newY( );
obj .
two( );
obj .
one( );
}
}
(72)Wr it
eapr ogr am t ofinddi v i
sionandmodul odi
v i
sionv al
ueoftwo
numberusi ngsinglei nherit
ance?
classDi visi
on
{
protect edi nta,b,c;
voidf irst()
{
a=5;
b=4;
c=a/ b;
Sy stem. [Link]
n(“di
v i
sionv alue=” +c);
}
}
cl
assModul oextendsDi vi
sion
{
voi
dsecond( )
{
i
ntd;
d=a%b;
[Link]
n(“
modul odi visi
onv al
ue”+d);
}
publi
cst ati
cv oidmai n(Str
ingar gs[]
)
{
Modul oobj=newModul o()
;
obj.
fir
st();
obj.
second( );
}
}
[Link] ti
levelinher i
tance:-whenonecl assderivest hefeaturesof
anotherand agai nt hatder ive cl
ass deri
ves the featuresf
rom
anothercl assandsoont heni ti
scall
edmul t
il
evelinheri
tance.
Ex :
-
classFat her
{
doublef ;
voiddi sp1()
{
f=20000;
Sy st
em. [Link]
intl
n("fatherincome="+f);
}
}
classMot herextendsFat her
{
doublem;
voiddi sp2()
{
m=0. 9* f
;
Sy st
em. [Link]
intl
n("mot herincome="+m) ;
}
}
classSonex t
endsMot her
{
doubl es;
voiddi sp3( )
{
s=0. 8* m;
Sy stem. out .
printl
n("soni ncome=" +s);
}
publ i
cst aticv oidmai n(St ri
ngar gs[ ]
)
{
Sonobj =newSon( );
obj .
disp1( ) ;
obj .
disp2( ) ;
obj .
disp3( ) ;
}
}
[Link]: -Tor educet hecompl exityandsi mplif
yt hel anguage,
mul tiplei nher i
tance i s notsuppor t
ed inj [Link] i fwe
consi derA,BandCast hreeclassest henCcl assinher i
tsAandB
classes.I fAandBcl asseshav esamemet hodandy oucal litf
rom
childcl assobj ect,therewi l
lbeambi guitytocallmet hodofAorB
[Link] nordert oov er comet hispr obl
em javaintroduceanew
conceptcal led int erf
ace i nstead ofmul t
ipleinher i
tance using
interfaceandi mpl ement skey wor d.
Sy n:
- i nterface<i nterfacename>
{
Memberdecl aration;
}
class <childclasname> i
mplement s
<interf ace1>, .
..,
<interfacen>
or
class <chi l
dclassname> ext ends <par entclassname>
impl ement s<interface1>, ..
.,
<interfacen>
(
73)Wr i
teasi mpl epr ogram f orinterface?
i
nter
facepqr
{
v
oidshow( );
}
i
nt erfacexy z
{
voiddi sp();
}
classabci mplement spqr,xyz
{
publ i
cv oidshow( )
{
Sy stem. out
.print
ln(“
welcome” )
;
}
publ i
cv oiddisp()
{
Sy stem. out
.print
ln(“
hell
o”);
}
voiddi splay()
{
Sy stem. out
.print
ln(“
hi”
);
}
publ i
cst ati
cv oidmain(Stri
ngargs[
])
{
abcobj =newabc( )
;
obj .
show( );
obj .
disp();
obj .
display(
);
}
}
(74)Wr iteapr ogram forinter
face?
classX
{
voiddi splay()
{
Sy stem. out
.print
ln(“
hell
o”);
}
}
i
nt erfacecircl
e
{
voi
dar ea1(floatr);
}
i
nterfacesquar e
{
voi
dar ea2(ints) ;
}
publi
ccl assYext endsXi mplement scir
cle,
square
{
publi
cv oidar ea1(floatr)
{
fl
oatca;
ca=3.141* r
*r;
System. [Link] i
ntl
n( “areaofcircl
e=”+ca);
}
publi
cv oidar ea2(ints)
{
i
ntsa;
sa=s* s;
System. [Link] i
ntl
n( sa);
}
voi
dshow( )
{
System. [Link] i
ntl
n( “bye”);
}
publi
cst ati
cv oidmai n(Stri
ngar gs[
])
{
Yobj =newY( );
obj.
displ ay()
;
obj.
ar ea1(5.5) ;
obj.
ar ea2(5);
obj.
show( );
}
}
[Link] erarchicali nher i
tance:-Whenmor ethanonecl assder
ivest
he
featuresf rom asi nglebasecl assthenitiscall
edashier
archi
cal
inheri
tance.I tf oll
owsahi erarchyortr
eelikest
ruct
ure.
Ex:
-
cl
assa
{
voi
done( )
{
System. [Link]
ln(
"hell
o");
}
}
cl
assbex t
endsa
{
voi
dt wo( )
{
System. [Link]
ln(
"hi
i")
;
}
}
cl
asscex tendsa
{
voi
dt hree()
{
System. [Link]
ln(
"bye");
}
}
cl
assd
{
publicstati
cv oidmain(Stri
ngargs[
])
{
bo1=newb( );
co2=newc( );
[Link]();
[Link]()
;
[Link]();
}
}
[Link] bridInherit
ance:-
Whenmor et hanonet ypeofinher
it
ancemergedt
ofor
m anewt
ypeof
i
nher i
tancet heni ti
scalledhybri
dinher
it
ance.
Ex:
-
cl
assa
{
voi
done( )
{
System. out .
printl
n("
hell
o");
}
}
cl
assbex tendsa
{
voi
dt wo( )
{
System. out .
printl
n("
hii
");
}
}
cl
asscex tendsa
{
voi
dt hr ee()
{
System. out .
printl
n("
bye");
}
}
cl
assdex tendsb
{
voi
df our ()
{
System. out .
printl
n(“
welcome” )
;
}
publi
cst ati
cv oidmain(Stri
ngargs[]
)
{
dobj =newd( );
obj.
four ();
}
}
Useofsuper :
-
Thesuperkey wor dinjavaisar ef
erencevari
ablewhichisusedtoref
er
i
mmedi atepar entcl
assobj ect
.Iti
susedinthreecases.
[Link] be used t or ef
eri mmediate par
entclass i
nst
ance
variabl
e.
(75) Ex:-
classHel l
o
{
Stringname=" hell
o";
}
classHi extendsHel l
o
{
Stringname=" wor l
d";
voidpr int()
{
Sy stem. out.
print
ln(name) ;
Sy stem. out.
print
ln([Link]) ;
}
publ icstati
cv oidmai n(Stri
ngar gs[
])
{
Hi h=newHi ();
[Link](
) ;
}
}
[Link] oinvokei mmedi
atepar
entcl
assmet
hod.
(76) Ex:-
classHel l
o
{
voidi n()
{
Sy stem. out.
print
ln("hell
of r
iends");
}
}
classHi extendsHel l
o
{
voidi n()
{
Sy stem. out.
print
ln("hifr
iends");
}
voidout ()
{
Sy stem. out.
print
ln("hell
of r
iends");
}
voidshow( )
{
super .i
n();
out ();
}
publ icstaticv oidmai n(St ri
ngargs[])
{
Hi h=newHi ()
;
[Link]( );
}
}
[Link] ()canbeusedt oinvokei mmediateparentcl
assconstr
uct
or .
(77) Ex:-
classHel l
o
{
Hel l
o( )
{
Sy [Link] .printl
n("iam t hebest "
);
}
}
classHi ex t
endsHel l
o
{
Hi()
{
super ();
Sy [Link] .printl
n("higuy s");
}
publ icstaticv oidmai n(St ri
ngargs[])
{
Hi h=newHi ()
;
}
}
Abst ractcl ass: -
A cl asst hati sdecl aredwi t
habst ractkeyword,isknownasabst ract
classi nj av [Link] eabst ractandnon- abst
ractmethods(method
wit hbody ).Abst ractioni sapr ocessofhidingtheimplementat
iondet
ails
andshowi ngonl yf unctionalit
ytot heuser.
Sy n:-abstractcl ass<cl assname>
{
}
Abst ractmet hod: -
Amet hodthati sdeclaredasabst r
actanddoesnothav
ei mpl
ementat
ion
i
sknownasabst ractmet hod.
Sy n:-abstractr eturntypemet hodname( )
;
(78) Wr i
teapr ogr am forabstractclassandmethod?
abst ractclassHel l
o
{
abst ractvoidmsg( );
voidget (
)
{
Sy stem. out.
pr intl
n("hell
o");
}
}
classHi extendsHel l
o
{
voidmsg( )
{
Sy stem. out.
pr intl
n("iam cool");
}
}
classBy eex tendsHel l
o
{
voidmsg( )
{
Sy stem. out.
pr intl
n("iam smar t"
);
}
}
classWel come
{
publ icstati
cv oidmai n(Stri
ngar gs[
])
{
Hel loh1=newHi (
);
Hel loh2=newBy e();
h1. get();
h1. msg( );
h2. msg( );
}
}
Met hodov erriding:-
Ifsubcl ass( chi l
dcl ass)hast hesamemet hodasdecl
aredinthepar
ent
class, i
tisknownasmet hodov [Link]
nameasi nt hepar [Link] hodmusthav esamepar ameterasin
the par ent cl [Link] hod ov erriding is used to pr
ovide speci
fic
i
mpl ementat i
onofamet hodt hati sal r
eadyprovi
dedbyitssuperclass.
Met hodover r
idingisusedf orruntimepol ymorphi
sm.
(79) Writ
eapr ogr am formet hodov er ri
ding?
classDemo
{
voidr un()
{
Sy [Link]
n("t
hisispar entcl ass");
}
}
classDemo1ex tendsDemo
{
voidr un()
{
Sy [Link]
n("t
hisischi l
dcl ass" );
}
publ icst
aticv oidmai n(Str
ingar gs[ ]
)
{
Demoobj 1=newDemo( );
Demoobj 2=newDemo1( );
obj 1.r
un()
;
obj 2.r
un()
;
}
}
Pol
ymor
phi
sm(
CH-
9)
Greek wor d pol
y means many and mor phi
sm means f orm.
Polymorphism i
stheabi l
it
yofanobj ecttotakeonmanyf [Link]
mostcommonuseofpol ymorphism inOOPoccur swhenaparentclass
refer
enceisusedtor efertoachi [Link]
etwot y
pesof
polymorphi
sm i n java: compi l
et ime pol y
mor phi
sm and r unti
me
polymorphi
[Link] can per form pol ymorphism inj av
a by met hod
overl
oadingandmet hodov err
idi
ng.
Types:-
[Link]
ymor phi
sm: -
Thepol y
mpr phi
sm whichi soccur redatt heti
meofcompi l
ati
onoft he
progr am i scal l
edcompi let i
mepol y [Link] eof
compi let imepol y
mor phi
sm i nj avaist o ov erl
oad astati
cmethod.
Ov erloadi nghappensi nsingleclass.
Ex:-
Met hodov erloading:-whenasi ngleclasscallsamef unct
ionformul
tipl
e
ti
mes wi th di f
ferent-
dif
fernetoper ations then itis call
ed method
ov erl
oadi [Link] emet hodnamemustbesamebutt ypeargumentmust
bedi ff erent .
(80)Wr iteapr ogr am formet hodov er
loadinginj ava?
classone
{
i
nta;
doubl eb;
voidshow( intx )
{
a=x;
Sy stem. out .
printl
n(a);
}
voidshow( doubl ey )
{
b=y ;
Sy stem. out .
printl
n(b);
}
publ i
cst aticv oidmai n(Str
ingargs[])
{
oneobj =newone( );
obj .
show( 8);
obj .
show( 5.5);
}
}
(81)Wr iteapr ogr am tooverloadamet hodinj ava?
classOv erl
oad
{
i
ntadd( i
nta, i
ntb)
{
retur n(a+b);
}
intadd( inta,intb, intc)
{
return(a+b+c) ;
}
publ i
cst ati
cv oidmai n(Stri
ng[]args)
{
Ov erloado1=newOv er l
oad( )
;
Sy stem. [Link](o1. add( 11,
11));
Sy stem. [Link](o1. add( 11,
11,11)) ;
}
}
[Link] imepol ymor phi sm: -
Runt i
me pol ymor phi sm orDy nami c Met hod Di spatchis a process in
whi chacal lt oanov erriddenmet hodi sr esolvedatr unti
mer atherthan
compi l
e-ti
me. I
nt hispr ocess, anov er
ri
ddenmet hodi scall
edthrought he
referencev ariableofasuper [Link] erminat i
onoft hemet hodto
becal ledi sbasedont heobj ectbei ngr efer
r edt obyt her efer
ence
[Link] hodov er r
idingi st heexampl eofr unt i
mepol ymorphi sm.
Ex:-
Met hodov erri
ding: -whent hesamef unct i
oni swor kf ormultipletimes
fordi fferentpur posesi n di f f
erent-
differentcl assest hen i
ti scal l
ed
met hodov erridi
ng.
(82) Wr i
teapr ogram f orr unt i
mepol ymor phi sm ?
classBank
{
i
nti nterest()
{
return(0);
}
}
classSBIex tendsBank
{
i
nta, b;
i
nti nterest(intx,i
nty )
{
a=x;
b=y ;
return(a+b) ;
}
}
classI CI CIex tendsSBI
{
doubl ec;
doubl einterest (doubl ez )
{
c=z ;
retur n(c);
}
publ icstat icv oidmai n(Stringargs[ ]
)
{
ICICIa=newI CI CI()
;
Sy stem. out .printl
n( "
SBIRat eofI nterest
: "+a.i
nterest
(5,
4));
Sy stem. out .printl
n( "
ICICIRat eofInterest: "
+a.i
nterest(
5.5)
);
}
}
Const ructorov er l
oadi ng:-
Whenev erwewantt oov erloadaconst ructormor ethanoneti
mei
nsi
de
apr ogram t heni tiscal l
edconst ructorov erl
oading.
(83) Wr it
eapr ogr am f orconst ructorov erloading?
classBox
{
doubl ewi dth, height,dept h;
Box (doublew, doubl eh, doubl ed)
{
widt h=w;
hei ght=h;
dept h=d;
}
Box ()
{
widt h=hei ght=dept h=0;
}
Box (doublel en)
{
widt h=hei ght=dept h=l en;
}
doubl evol ume( )
{
retur nwi dth*hei ght*dept h;
}
}
publ
icclassTest
{
publ
icstati
cvoidmai n(Stri
ngargs[
])
{
Boxmy box1=newBox (10,20,
15);
Boxmy box2=newBox ();
Boxmy cube=newBox (7);
doubl
ev ol;
vol=my box1.
volume( )
;
Syst
em. out
.pr
int
ln("Volumeofmy box1i
s"+vol
);
vol=my box2.
volume( )
;
Syst
em. out
.pr
int
ln("Volumeofmy box2i
s"+vol
);
vol=my cube.
volume( )
;
Syst
em. out
.pr
int
ln("Volumeofmy cubei
s"+v
ol);
}
}
Except
ionHandl
ing(
CH-
10)
Exceptionsar et heer rorswhi char eoccurdur ingpr ogram execut ion
[Link] ear etwot ypesofer r orsoccuri nsidet hepr ogram; thatar e:
[Link] let imeer ror:-theer r
or swhi chareoccur redatt het i
meof
compi lation oft hepr ogram ar ecal ledcompi letimeer [Link]
arealsocal l
edassy ntaxerror .
Ex :
-statementmi ssing,termi nationer r
oret c.
[Link] i
me er ror:
-t he errors whi ch ar e occur red att he t ime of
runningt hepr ogr am ar ecalledr untimeer ror [Link] ear etwot y
pes
ofrunt imeexcept ionsav ail
abl eike:
i. Sy nchr onousexcept i
on: -theexcept ionswhi char eundert he
cont r
oloft hepr ogr ammer /comput erar ecal l
edsy nchronous
except i
[Link] :-loopov erf l
ow,zer odi vide,numberf ormat
error .
ii
. Asy nchronousexcept ion:-t heexcept i
onswhi char ebey ond
the cont rol of t he pr ogrammer /comput er ar e cal led
asy nchr onousexcept [Link]: -sy st
em cr ash, harddiskf ai
lure
etc.
SynchronousExcept ionCat egori
es: -
1)CheckedExcept ion:-
Theclassest hatex tendThr owabl ecl assexceptRunt imeExcept i
onand
Errorar eknownascheckedexcept i
ons
e.g. I
OExcept ion,SQLEx ceptionet [Link] ionsarecheckedat
compi le-t
ime.
2)UncheckedExcept ion:-
Thecl assest hatext endRunt imeExcept i
onar eknownasunchecked
except i
ons
[Link]
thmet icExcept i
on,NullPointerException,Ar
rayI
ndexOutOfBoundsEx
cept i
onet [Link] ceptionsar enotcheckedatcompi l
e-t
ime
rathertheyar echeckedatr untime.
Built-
in/Pre-def i
nedExcept ion:-
Theexcept i
onswhi char eal r
eadyav ailableinsidejavali
brar
yandwe
donothav et ocr eateex ceptionalblock f orthem usingexceptional
key wordsar ecal l
edpr e-definedexcept ions.
[Link] i
thmet i
cExcept i
on:-Ar it
hmet i
cer r
or,suchasdi vi
de-
by-zer
o.
[Link] r
ay I
ndexOut OfBoundsExcept ion:-
Arrayindexisout-
of-
bounds.
[Link]
aySt
oreExcepti
on:
-Assi
gnmentt
o an ar
ray el
ementofan
i
ncompati
bletype.
[Link]
assCast
Except
ion:
-I
nval
i
dcast
.
5.I
ll
egalAr
gument
Except
ion:
-I
ll
egalar
gumentused t
oinv
oke a
method.
6.I
ll
egal
Moni
tor
StateExcept
ion:
-I
ll
egalmoni
toroper
ati
on,suchas
wai
ti
ngonanunlockedthr
ead.
[Link]
legal
Stat
eExcept
ion:
-Env
ironmentorappl
i
cat
ioni
sini
ncor
rect
state.
[Link]
legal
ThreadStat
eException:
-Requested oper
ati
on not
compatibl
ewi t
hthecurrentthreadstate.
9.I
ndexOutOf
BoundsExcept
ion:
-Some t
ype of i
ndex i
s out
-of
-
bounds.
10. Negat
iveAr
ray
SizeExcept
ion:
-Ar
raycr
eat
edwi
thanegat
ive
si
ze.
11. Nul
lPoi
nter
Except
ion:
-I
nval
i
duseofanul
lref
erence.
12. Number Format
Except
ion:
-I
nval
i
dconv
ersi
onofast
ri
ngt
oa
numer
icf
ormat.
13. Secur
it
yExcept
ion:
-At
temptt
ovi
olat
esecur
it
y.
14. St r
ingI
ndexOutOf
Bounds:
-At
tempt t
o i
ndex out
side t
he
boundsofastri
ng.
15. Unsuppor tedOper
ati
onExcept
ion:
-Anunsuppor
tedoper
ati
on
wasencount
ered.
16. Cl
assNot
FoundExcept
ion:
-Cl
assnotf
ound.
17. Cl oneNot
Support
edExcept
ion:
-Att
emptt o cl
onean obj
ect
t
hatdoesnoti
mplementt
heCloneablei
nter
face.
18. I
ll
egal
AccessExcept
ion:
-Accesst
oacl
assi
sdeni
ed.
19. I nst
anti
ati
onException:
-At
temptt
ocr
eat
eanobj
ectofan
abst
ractcl
assorint
erface.
20. I nterr
upt
edExcept
ion:
-Onet
hreadhasbeeni
nter
rupt
edby
anot
herthr
ead.
21. NoSuchFi
eldExcept
ion:
-Ar
equest
edf
iel
ddoesnotexi
st.
22. NoSuchMet
hodExcept
ion:
-Ar
equest
ed met
hod does not
ex
ist
.
23. UnknownHost
Except
ion:
-net
wor
kingexcept
ion.
24. SQLExcept
ion:
-dat
abaseer
ror
.
25. Fi
leNot
FoundExcept
ion:
-fi
l
enotf
ound.
26. I OExcept i
on: -input/outputexception.
User-defi
nedexcept i
on:-
Tohandl eanuser -defi
nedexcept ioninc++wemustuset hreekey wor ds.
1.t ry:
-iti
sabl ockofst atementwher ewecangener ateanexcept i
on.
[Link] ch:-
itisal soabl ockofst at
ementwher ewecandi splayan
exceptionalmessage gener ated by t ry bl
ock by t he hel p of
exceptional typear gument .
3.t hrow:-itisakey wor dwhi chi susedi nsidetryblockt othrow an
exceptionf rom trybl ocktocat chbl ock.
4.t hrows:-t
hrowskey wor di
susedf orhandlingcheckedexcept ions.
Byusi ngt hr owswecandecl aremul t
ipl
eexcept ionsinonego.
Usedwi t
hf unctionbl ockli
kemai n()forbuf f
erinput.
5.f i
nally:
-j
av af i
nallybl ockisusedt oexecut eimpor t
antcodesuchas
closi
ng connect ion,st r
eam et [Link] i
nall
yblock i s al ways
execut edwhetherexcept
ioni
shandl
edornot
.Jav
afi
nal
l
ybl
ock
foll
owst ryorcatchbl
ock.
Sy
n:-t
ry
{
//protectedcode;
}
catch(Excepti
onarg)
{
//throwingexcepti
on
}
fi
nally
{
//
st at
ement
}
(84) Wri
teapr ogram f oruser-def
inedexcepti
onusingzer
odi
vi
de?
publ i
cclassTest
{
publ i
cstat i
cv oidmai n(Str
ingargs[]
)
{
try
{
i
nta=10, b=0, c;
c=a/ b;
Sy [Link]
ln(c);
}
cat ch(
Ex ceptione)
{
Sy [Link]
ln(e);
}
fi
nal l
y
{
Sy [Link]
ln("f
inall
yblockisalwaysexecuted"
);
}
Sy [Link]
ln("r
estoft hecode..
."
);
}
}
Wr iteapr ogram f orAr r
ayIndexOutOfBoundExcepti
on.
classExcept i
onDemo2
{
publi
cst ati
cv oi dmai n(Stri
ngar gs[
])
{
try
{
inta[]=newi nt[10] ;
a[11]=9;
}
catch(Ar r
ay I
ndexOut OfBoundsExcept i
one)
{
System. out .
pr intln("
Ar r
ayIndexOutOfBounds")
;
}
}
}
Wri
teapr ogr am f orNumber For matExcepti
on.
cl
assExcept ionDemo3
{
publi
cst ati
cv oi dmai n(Stri
ngar gs[
])
{
try
{
i
ntnum=I nteger .
parseInt("XYZ");
Syst [Link] .pr i
ntln(
num) ;
}
catch(Number For mat Exceptione)
{
Syst em. out .printl
n("Numberf ormatexcepti
onoccur
red"
);
}
}
}
Wri
teapr ogr am f orSt ri
ngIndexOut OfBoundExcepti
on.
cl
assExcept ionDemo4
{
publi
cst ati
cv oi dmai n(Stri
ngar gs[
])
{
try
{
Str
ingst r=" begi nnersbook" ;
Syst [Link] .pr i
ntln(
str.
length())
;
charc=st [Link] At(
0) ;
c=st r
.char At (40);
Sy
stem.
out
.pr
int
ln(
c);
}
cat
ch(St
ri
ngIndexOut
OfBoundsExcepti
one)
{
Syst
em. out
.pr
int
ln(
"St
ri
ngIndexOut
OfBoundsExcept
ion!
!"
);
}
}
}
Package(
CH-
11)
Aj avapackagei sagr oupofsi milartypesofcl asses, inter facesandsub
-packages. Package i nj av a can becat egor ized i nt wo f orm,bui l
t-i
n
packageanduser -def i
nedpackage. Ther ear emanybui lt-i
npackages
suchasj ava,lang, awt ,jav ax,swi ng, net,io,util
, sql et
c.
Adv antages:-
[Link] avapackagei sagr oupofsi mi lart ypesofcl asses,i nterfaces
andsub- packages.
[Link] nj av acanbecat egorizedi nt wof or
m,bui l
t-i
npackage
anduser -def i
nedpackage.
[Link] ear emanybui l
t-i
npackagessuchasj ava,l ang,awt ,j
av ax,
swing,net ,io,ut i
l,sql etc.
Typesofpackages: -
[Link] stem suppl ied/Pr e-def ined/Bui lt
-inpackages: -
Thepackageswhi char eal readyav ailablei nsidej av alibraryar e
cal
led bui lt-i
n packages and ar e used f orsome pr e-defined
cl
asses.
i. i mpor tj [Link]. *;: -usedf orSy stem,St ri
ng,Obj ect,Thr ead,
Except i
onet [Link].
ii
. i mpor tj [Link] i
l
.*; : -t hese ar e cal l
ed as ut i
lity( serv i
ce)
classesandar eusedv eryf requent lyi ncodi ngf orScanner
class.
ii
i. i mpor tj [Link].*; : - used for FileInputSt r
eam,
FileOut putSt ream,Fi leReader ,Fi leWr iter,RandomAccessFi le,
Buf feredReader , Buffer edWr it
eret ccl asses.
iv. i mpor tj [Link] .
* ; : -used f or URL,Ser verSocket ,Socket ,
Dat agramPacket ,Dat agramSocketet ccl asses.
v. i mpor tj [Link] et.*; :
- used f or Appl etCont ext,
Appl et,Audi oSt ub, Audi oCl i
pet ccl asses.
vi. i mpor tj [Link] .*; : -usedf orBut ton,Choi ce,Text Field,Frame,
List,Checkboxet cclasses.
vi
i. i mpor tjava. awt .event.
*;: -used for MouseLi st
ener,
Act ionList ener , Act i
onEv ent,Wi ndowAdapt eretcclasses.
vi
ii
.i mpor tjava. sql .*; : - used f or Dr iverManager , Statement,
Connect i
on, Resul tSetet ccl asses.
i
x. i mpor tjavax. swi ng.*; :
-usedf orswi ngclasses.
[Link] -def i
nedpackages: -
Thepackageswhi char ecreat edbyt heuseratt het i
meofwr i
ting
thepr ogram accor di
ngt ot heneedofuseri scalleduser -
defi
ned
package.I ti scr eat edbyt hehel poft hekey wordpackage.
Syn:-package<packagename>;
Stepst ocr eat epackage: -
(85)Wr it
eapr ogr am t ocreateanuser -defi
nedpackage?
Creat eaf oldercal led“abc”i nsideanydr iveli
ke“ d:
\ ”becausey our
pathi ssetont hi sdr i
v esopr efert hisdrive.
Wr i
tet hef ol l
owi ngpr ogram andsav eitasHel l
o.j
ava
packageabc;
publiccl assHel lo
{
publici ntadd( inta, i
ntb)
{
return( a+b) ;
}
publicst aticv oidmai n(Str
ingar gs[]
)
{
Hel l
oobj =newHel lo();
System. out .
pr int l
n( obj.
add(10, 20) )
;
}
}
Nowwr i
tet hef ollowi ngprogr am andsav eitasHi .
java
impor tabc. Hel lo;
publiccl assHi
{
publicst aticv oidmai n(Str
ingar gs[]
)
{
Hel l
oobj =newHel lo();
System. out .
pr int l
n( obj.
add(100, 200));
}
}
Now compil
eandr unHi .
jav
aandseet heout putbecausewehav e
cr
eated an user-
def
ined package cal
led import [Link]
l
o; and
i
mplementediti
nsi
deHi.
javatoseet
heeff
ect.
Gener
ics(
CH-
12)
Gener icsi nJav ai ssi mi l
art otempl at
esi nC++.Thei deai
stoal
lowtype
(I
nteger ,St ri
ng,… et canduserdef inedt ypes)t obeapar ameterto
met hods,cl assesandi nterf
[Link] e,classesl
ikeHashSet
,
ArrayList ,HashMap, etcusegener i
csv [Link] hem f
orany
[Link] all
ygener i
csi susedf ortakingdi f
ferenttypesofi
nputfora
singlev ar i
abl ebyspeci fyingt y
peT.
Wecancr eat egener icspr ogrammi ngf orthefollowing:
[Link] icscl ass
[Link] icsmet hod/ const r
uctor
[Link] icsint erface
(86)Wr iteapr ogram f orcl asstypegener ics?
classHel l
o<T>
{
Tobj ;
Hel lo(To)/ /const ructor
{
obj =o;
}
publ icTget ()
{
retur n(obj);
}
publ icst aticv oidmai n(Stri
ngar gs[]
)
{
Hel lo<I nteger >obj 1=newHel lo<>(100);
i
ntx=obj [Link] ();
Sy stem. out .pr i
ntln(x);
Hel lo<St r
ing>obj 2=newHel lo<>(“swarnanil”
);
Strings=obj [Link]();
Sy stem. out .pr i
ntln(s);
}
}
(87)Wr iteapr ogram f ormet hodtypegener ics?
classTest
{
stati
c<T>v oiddispl ay( Ta)
{
Sy st
em. [Link]
intl
n( element .
getClass()
.getName(
)+"="+a)
;
}
publicst ati
cvoidmai n(Stri
ng[]args)
{
display(11);
display("hel
lostudent s")
;
display(1.0);
}
}
(88)Wr i
teapr ogram f orinter
facegener ics?
i
nt er
facea<T>
{
publicvoi dadd(Tt );
}
publicclassBoxi mpl ement sa<Integer>
{
i
ntt ;
publicvoi dadd(Integert )
{
this.
t=t ;
}
publicintget (
)
{
returnt;
}
publicst ati
cvoidmai n(Stri
ng[]args)
{
Boxa=newBox ()
;
[Link](10) ;
Sy st
em. [Link]
int([Link] (
));
}
}
Mul
ti
-t
hreadi
ng(
CH-
13)
Mul t
it
hreading inj avais a process ofexecut i
ng mul ti
plet hreads
si
mul [Link]
call
yali
ghtweightsub- pr
ocess,asmal l
est
[Link] t
ipr
ocessi
ngandmul ti
threading,bot
har eusedt o
achievemul ti
[Link] ti
thr
eadingt hanmul ti
processing
becauset hreadsshar eacommonmemor yar [Link]' tal l
ocate
separate memor y area so sav es memor y,and cont ext-
swi t
ching
betweent het hreadst akesl esst i
met hanpr ocess.
Advant ages: -
1.I tdoesn' tblockt heuserbecauset hreadsar ei ndependentandy ou
canper f
or m mul ti
pleoper ationsatsamet i
me.
[Link] for m manyoper ationst oget hersoi tsavest i
me.
[Link] eads ar ei ndependentso i tdoesn' taf fectot hert hreads if
ex cept i
onoccuri nasi nglet hr ead.
[Link] aMul t
it
hreadi ngismost l
yusedi ngames, animat i
onet c.
Multi
taski ng: -
Multi
taski ngi sapr ocessofexecut i
ngmul ti
pl et askssi [Link]
usemul ti
taski ngtout il
izet [Link] titaskingcanbeachi evedbyt wo
ways:
o P rocess- basedMul t
it
aski ng( Mul tiprocessi ng)
o T hread- basedMul t
it
aski ng( Mul tit
hr eadi ng)
1)Process- basedMul t
itasking( Mul tiprocessi ng):-
o E achpr ocesshav eitsownaddr essi nmemor [Link] ocess
allocat essepar atememor yar ea.
o P rocessi sheav y weight .
o Co stofcommuni cati
onbet weent hepr ocessi shi gh.
o S witchingf rom onepr ocesst o anot herr equi resomet i
mef or
sav ingandl oadi ngr egi sters, memor ymaps, updat i
ngl i
stsetc.
2)Thread- basedMul titasking( Mul tit
hreadi ng) :-
o T hreadsshar et hesameaddr essspace.
o T hreadi sl i
ght wei ght.
o Co stofcommuni cati
onbet weent het hr eadi sl ow.
Thread: -
Athreadi sal ightwei ghtsubpr ocess, asmal l
estuni tofpr [Link]
asepar atepat hofex ecut i
[Link] eadsar ei ndependent ,ifthereoccur s
exceptioni nonet hr ead,i tdoesn' taf fectot hert hreads.I tsharesa
commonmemor yar ea.
Thr
eadLi
fe-
cycl
e:-
The l
if
e cycl
e oft he t
hread i
n
j
avaiscont r
oll
ed [Link]
j
avathreadst
atesareasfoll
ows:
1.
New:-The thread i
si n new
statei fy oucr eateani nstanceofThr eadcl assbutbef oretheinv
ocat i
on
ofst art()met hod.
[Link] e:-Thet hreadi sinr unnabl est ateaf t
eri nvocationofst ar
t()
met hod,butt het hreadschedul erhasnotsel ect
edi ttobet herunning
thread.
[Link] ng:-Thet hreadi si nr unningst ateift het hreadschedulerhas
select edi t
.
[Link]: -Thisi sthest atewhent het hreadisst i
llalive,buti
scur r
entl
y
notel igibletor un.
[Link] mi nated:-At hreadi si ntermi natedordeadst atewheni tsr un()
met hodexi ts.
Thr eadCl ass:-
Itisapr e-definedcl assi njav awhichi susedt ocr eatet hr
eadsinsidethe
progr am.
Const r uctorsusedf orThr eadCl ass:-
[Link] ead( )
[Link] ead( Stri
ngname)
[Link] ead( Runnabl er )
[Link] ead( Runnabl er ,
Stri
ngname)
Met hodsusedf orThr eadCl ass:-
[Link] icvoi drun()
[Link] icvoi dstart()
[Link] icvoi dsleep( )
[Link] icvoi djoin()
[Link] icvoi dstop( )
[Link] icvoi dsuspend( )
[Link] icvoi dresume( )
[Link] icintget Priori
ty()
[Link] icintset Pri
or i
ty()
10. publicBool eani sAli
ve()
11. publicSt r
ingget Name( )
12. publicvoidset Name( )
13. publicThr eadcur r
entThr ead()
14. publicThr [Link] St at
e()
15. publicvoidi nterrupt(
)
(89) Wr iteasi mpl eprogr am t oimpl ementt hread?
classHel loext endsThr ead
{
publ icvoidrun( )
{
Sy stem. out.
printl
n( "
threadi srunning..
."
);
}
publ icstati
cv oidmai n(Str i
ngar gs[]
)
{
Hel lot1=newHel lo();
[Link]();
}
}
Runnabl einterface:-
Thi si sapr e-definedi nterfaceusedi njav
athr
eadpr
ogr
ammi
ngf
or
runni ngmul ti
plet hread.
(90) Ex:-
classHi implement sRunnabl e
{
publ icvoidrun( )
{
Sy stem. out.
printl
n( "
threadi srunning..
."
);
}
publ icstati
cv oidmai n(Str i
ngar gs[]
)
{
Hi m1=newHi ();
Thr eadt 1=newThr ead( m1) ;
[Link]();
}
}
(91) Writeapr ogr am f ort hreadsl eepmode?
classTestex tendsThr ead
{
publ icvoidrun( )
{
for(inti=1;i
<5;i
++)
{
try
{
Thr [Link](500) ;
}
cat ch(I
nt er
ruptedExcept ione)
{
Sy [Link] .
print l
n(e);
}
Sy [Link] .
print l
n(i
);
}
}
publ i
cst ati
cv oidmai n(Stri
ngar gs[])
{
Testt 1=newTest ();
Testt 2=newTest ();
[Link]
();
[Link]
();
}
}
Thr eadPr iori
ty:-
Each t hread hav eapr ior
[Link]
iesarerepr esented byanumber
bet ween 1 and 10.I n mostcases,t hread schedulerschedul esthe
threadsaccor dingt ot heirpri
orit
y( knownaspr eempt i
vescheduling)
.But
i
ti snotguar ant eedbecausei tdependsonJVM speci f
icati
onthatwhich
schedul ingitchooses.
Thr eadPr i
orityConst ants:-
[Link] ntMI N_ PRIORITY(1)
[Link] ntMAX_ PRI ORITY(10)
[Link] ntNORM_ PRIORITY( 5)
(92) Writeapr ogr am f orthreadpr i
or i
ty?
classTest 1ext endsThr ead
{
publ i
cv oidrun( )
{
Sy [Link] .
print l
n("t
hreadnamei s: "
+Thread.
currentThread()
.get
Name( )
);
Syst
[Link]
intl
n("
threadprior
ityi
s:"
+Thread.
curr
entThr
ead()
.get
Pri
ori
t
y(
));}
publ
icstati
cvoidmai n(St
ri
ngargs[])
{
Test1m1=newTest 1( )
;
Test1m2=newTest 1( )
;
[Link]
Pr i
ori
ty(
Thread.MIN_PRIORITY); //[Link]
Pri
ori
ty(
2);
[Link]
Pr i
ori
ty(
Thread.MAX_ PRIORITY);
m1. st
ar t();
m2. st
ar t();
}
}
Thr eadSy nchr oni zation: -
Sy nchr onizat ioni nj av ai sthecapabi l
it
ytocontroltheaccessofmul t
ipl
e
threadst oanyshar edr [Link] aSynchroni
zat i
oni sbett
eropt i
on
wher ewewantt oal lowonl yonet hreadtoaccesst hesharedresour ce.
Why?
[Link] eventt hreadi nter f
erence
[Link] eventconsi st encypr oblem.
Ty pes: -
[Link] ualexcl usion
i
.sy nchr onizedmet hod:-Synchronizedmet hodi susedtol ockan
obj ectf oranyshar edr [Link] hr
eadinv okesasy nchronized
met hod, itaut omat icallyacqui resthelockf ort
hatobj ectandreleasesi t
whent het hr eadcompl etesitstask.
(93) Ex:-
classHel l
o
{
synchr oniz edv oidpr int(intn)
{
for(inti=1; i<=5;i++)
{
Sy stem. out .
println(n* i)
;
try
{
Thr ead. sleep( 400) ; / /mi l
li
seconds
}
cat ch(Ex cept i
one)
{
Sy stem. out .
println(e) ;
}
}
}
}
classHi ex tendsThr ead
{
Hel lot;
Hi(Hel lot )
{
this.t
=t;
}
publ i
cv oidrun( )
{
t.
pr i
nt(5);
}
}
classBy eextendsThr ead
{
Hel l
ot;
By e(Hellot)
{
this.t
=t;
}
publ i
cv oidrun( )
{
t.
pr i
nt(100);
}
}
publ i
ccl assTest 2
{
publ i
cst ati
cv oidmai n(Str
ingar
gs[
])
{
Hel l
oobj =newHel l
o();
Hi t1=newHi (
obj );
By et2=newBy e(obj);
[Link]
t();
[Link]
t();
}
}
i
[Link] zedblock:-
i
ii.
stati
csy nchronizati
on:
-
[Link]-oper ati
on
Gar
bageCol l
ect
ion:-
GarbageCollect
ionisprocessofr eclaimingther
unti
meunused
memor yautomat i
cal
ly.I
notherwor ds,itisawayt odestroyt
he
unusedobjects.
Forgarbagecollecti
onweusef ree()f uncti
oninClanguageand
delet e()inC++.But ,
inj av aiti sper formedaut omat i
call
y.
So, javapr ov idesbet termemor ymanagement .
i nJav a,t hepr ogr ammerneednott ocaref orallthoseobj ects
whi ch ar e no l ongeri n [Link] bage collectordest roysthese
object s.
Gar bage col lect ori s bestexampl e ofDaemon t hreadas iti s
alway srunni ngi nbackgr ound.
Mai nobj ectiveofGar bageCol lect oristof reeheapmemor yby
dest royingunr eachabl eobj ect s.
Advantagesof garbagecol l
ect ion: -
I tmakesj avamemor yefficientbecausegar bagecol l
ectorremov es
theunr eferencedobj ect sf rom heapmemor y
.
I tisaut omat icallydonebyt hegar bagecol l
ect or
(apar tofJVM)so
wedon' tneedt omakeext r
aef forts.
Needofgar bagecol lection:-
Anobj ecti ssai dt obeunr eachabl eifi tdoesn’tcont ainanyr efer
encet o
i
[Link] obj ecti s sai dt o be el igiblef orgar bage col lecti
on ifiti s
unr
eachabl [Link] ear et hreeway sf orgar bagecollecti
on:
o B ynul li
ngt her ef erence
o B yassi gningar eferencet oanot her
o B yanony mousobj ectet c.
Howt or ungar bagecol l
ect i
on: -
[Link] ngSy stem. gc( )met hod
[Link] ngRunt ime. get Runt i
me. gc( )met hod
Note:
-Just bef ore dest roy ing an obj ect, Gar bage Col l
ector
cal
lsfinalize()met hod on t he obj ectt o per f
orm cl eanup act iv
iti
es.
Oncef inalize()met hod compl et es,Gar bage Col l
ector dest royst hat
obj
ect.
Wi
ndowAppl
icat
ions(
CH-
14)
JFC:-
Standf orJav aFoundationCl [Link] oosecol l
ecti
onofst andardJav a
APIsf orcl i
ent-
sidegraphics,graphi
caluseri nter
faces(GUIs),andr el
ated
programmi [Link] ef oundati
oncl assesint hesenset hatmost
cli
ent-sideJav aappli
cat
ionsar ebuil
tupont heseAPI s.
[Link]: -
Standsf orAbstractWi ndow Tool kit
.I tisan APIt o develop GUIor
window- basedapplicat
ionsi njava.
Jav aAWTcomponent sareplatfor
m-
dependenti .[Link] s are displ
ay ed accordi
ng t ot he vi
ew of
operat [Link] sheav [Link]
scomponent sareusingt he
resour cesofOS.
[Link]: -
Swi ngi sanadv ancedGUIt ool ki twr i
tteni npur eJav [Link] he
AWTbutpr ov i
desmanynew GUIcomponent sandusef ulGUI -
r elated
appl icat i
onser v i
[Link] ngof fersapl uggabl el ook- and-feelarchi tect ur e
thatal lowsanappl icationt obet r
iviallyconf igur edei thert odi spl aya
platf orm- i
ndependentJav alook- and-feelort omi mict helook-and- feelof
thenat iveoper at ingsy [Link] ngal soi ncl udesanaccessi bi l
it yAPI
thatenabl est heuseofassi stivet echnol ogi es, suchasscr eenr eader sor
screenmagni fi
er sf ort hev isioni mpai [Link] eaturesofSwi ngar e
basedont hepi oneer ingdesi gnoft heNet scapeI nternetFoundat i
on
Classes.
[Link] a2D: -
Jav a2Di st henamef ort hest ate-of -t
he- ar tt wo- dimensi onalgr aphi cs
APIi ntroducedi nJav a1. [Link] a2Di sbui ltupont heAWT,butgr eatly
expandsont hegr aphi cscapabi l
it
iest hatwer eav ail
ablei nJav a1. 0and
Jav a1. [Link] a2Di ncl udessuppor tforr esol utioni ndependence, rot ation,
scal ing and shear ing ofar bi trarygr aphi cs,ant i
ali
asing oft extand
graphi cs,al phat ranspar ency ,col orcomposi ting,andt heuseoft hef ull
rangeoff ont si nst alledont henat ivesy stem.
[Link] inting:-
Theabi li
tyt opr intt extandgr aphi csonapagei sal mostasi mpor t antas
theabi lit
yt odr awt ex tandgr aphi csont hescr [Link] a1. 1int roduced
simpl epr intingcapabi l
itiesaspar toft heAWT,andJav a1. 2incl udesa
mor epower fulpr int i
ngAPIaspar toft [Link] sbookdescr ibesbot h
print i
ngAPI s.
[Link] aTr ansf er :
-
Ani mpor tantf eat ur eofmanycl ient-si deappl icat i
onsi st heabi li
t yt o
all
ow user -
di rect eddat at ransf erwi t hint heappl icati
onandbet ween
unr elated appl icat [Link] ear et wo commonl yused dat at ransf er
met aphor s:cut -and- past eanddr ag-and- dr [Link] a1. 1def i
nedabasi c
dat at ransf erf ramewor kandpr ovidedanAPIf orcut -[Link] a1. 2
addssuppor tf ordat at ransf erusi ngt hedr ag- and- dr opmet aphor .
[Link] et:-
Theappl etAPIal lowsacl ient -sidepr ogr am t or unasanappl et ,ormi ni-
appl icat i
on,wi t hinawebbr owserorsomeot herf orm ofappl etv iewer .
Techni cally, theappl etAPIi snotpar toft heJFC, buti tisacr uci alpi ece
oft hecl i
ent -sideJav apr ogr ammi ngpi ctur e.
AWTHi erar chy :
-
Object :-
Thesear euserint erfaceswhi char eusedt ocreatedifferentcontrolsli
ke
button,box,[Link] e-defi
nedclasses.
Component :-
Itist hesupercl assofal lJav acomponent sandisdecl aredasabst r
act.
Thati s,we cannotcr eate obj ects ofComponentcl ass di r
ectly
.A
Componentobj ectr epresent sagr aphi cali
nteract
ivear eadisplayableon
thescr eent hatcanbeusedbyt heuser .
Cont ainer:
-
The Cont aineri s a componenti n AWT t hatcan cont ai
n anot her
component sl i
kebut tons,textf
ields, l
[Link] assest hatextends
Cont ainerclassar eknownascont ainersuchasFr ame, DialogandPanel .
Applet :-
Appleti saspeci alt ypeofpr ogram t hatisembeddedi nthewebpaget o
gener atethedy nami ccont ent.I trunsi nsi
det hebr owserandwor ksat
cli
entsi de.
Window: -
Thewi ndow i sthecont ainerthathav enobor dersandmenubar [Link]
mustusef rame, di al
ogoranot herwi ndowf orcreati
ngawi ndow.
Frame: -
TheFr amei st hecont ainerthatcont aintitlebarandcanhav emenubar s.
Itcanhav eot hercomponent sl i
kebut ton, textf i
eldet c.
Panel :
-
ThePaneli st hecont ainerthatdoesn' tcont aint itl
ebarandmenubar [Link]
canhav eot hercomponent slikebut ton, t
ext f
ieldet c.
Dialog:-
TheDi al ogcont rolrepresentsat opl evel wi ndowwi thabor derandat i
tl
e
usedt ot akesomef orm ofi nputf rom t heuser .Iti nher i
t st heWi ndow
class.
Appl etDet ail
s: -
Anappl eti saJav apr ogr am t hatrunsi naWebbr owser .Anappl etcan
beaf ullyf unct ionalJav aappl icati
onbecausei thast heent ireJav aAPI
atitsdi sposal .Appletisapr e-def i
nedcl assi nj av [Link] etpr ogramscan
ber unbyaddi ngapackagecal l
ed“i mpor tj av [Link] et.*;”
Appl i
cat i
on: - Appl et:-
1)consol eappl i
cat i
ons. 1)wi ndowappl ications.
2)basedonCUI 2)bsedonGUI
3)compi le-jav acf il
ename. j
ava; 3) compi le-jav acf il
ename. java
Run-jav af il
ename; run-appl etv i
ewer
fil
ename. java
4)mai n()pr esent 4)mai n( )notpr esent
5)requiresJRE 5)requi resbr owser
6)doesnotr equi resecur it
y 6)requi resecur i
ty
7)stand- aloneappl icati
onbecauser uns 7) requi resomet hi
rdpar t
y
toolslikes
oncommandpr ompt . browser .
8) can access any dat a or sof t
ware
8) cannotaccessanydat aofsy stem.
Av ai
lableoncomput er .
AppletLifecycle:
-
Appletli
fe-cy
cleconsistsoffol
lowi
ng
steps:
[Link]()
:-
met hod iscall
ed atthet i
meof
start
ingt heexecut i
[Link]
si scal
ledonl
y
oncei ntheli
fecy cl
e.
Syn:-publicvoi
dinit(
)
{
//
body
}
[Link] art():
-met hodi scal ledbyt hei nit(
)met [Link] hodi scalleda
numberoft imesi nt hel ifecy cle;whenev ert heappletisdeiconif
ed,t o
maket heappl etact i
v e.
Syn:-publ i
cv oidstar t()
{
/ /
body
}
[Link] nt( )
:-met hodi scal l
edbyt hest art
()met [Link]
ednumber
oftimesi nt heex ecut ion.
Syn:-publ i
cv oidpaint ()
{
//body
}
[Link] op( ):
-met hodi scal ledwhenev ert heappl etwindow isiconi
fiedt o
i
nact ivat et heappl et .Thi smet hodi scal lednumberoft imesi nt he
execut ion.
Syn:-publ i
cv oidstop( )
{
//body
}
[Link] roy ():
-met hodi scal l
edwhent heappl etiscl
[Link] hod
i
scal l
edonl yoncei nt hel ife-
cycl e.
Syn:-publ i
cv oiddest roy ()
{
//body
}
Adv ant agesofAppl et:-
o I twor ksatcl ientsi desol essr esponset ime.
o S ecured
o I tcanbeex ecut edbybr owser srunni ngundermanypl at
efor ms,
includi ngLi nux ,Wi ndows, MacOset c.
Disadv ant agesofAppl et:
-
o P lugini srequi redatcl i
entbr owsert oexecut eapplet
.
(94)Wr i
teanappl etpr ogr am t ocr eateawi ndow?
i
mpor tjav [Link] et.
*;
/*<appl etcode=” My app1”hei ght=200wi dth=250>
</appl et>* /
publiccl assMy app1ex tendsAppl et
{
publ i
cv oidinit()
{
setBackgr ound( [Link]);
setFor eground( Col [Link]) ;
}
publ i
cv oidpai nt(Gr aphicsg)
{
[Link] ring(“hell
ost udent s”,
30,30);
}
}
(95) Wr iteapr ogr am t ocr eat eappletwindow usi
ngpar
am t
agt
otake
values?
i
mpor tjav a.
appl et.*;
/*<appl etcode=” my app1”hei ght=200width=250>
<par am name=" roll"v al
ue=" 101" >
<par am name=" name"v alue=" ani
l">
<par am name=" age"v alue=" 28">
</appl et >*/
publ i
ccl assMy app2ex tendsAppl et
{
Stringname;
i
ntr ol l
;
i
ntage;
publ i
cv oidinit()
{
setBackgr ound( [Link]);
setFor eground( Col [Link]) ;
r=get Par amet er("roll"
);
n=get Par amet er("
name" );
a=get Par amet er("
age" )
;
r=Integer .
parseInt (r
) ;
a=Int eger .parseInt(a);
}
publ i
cv oidpai nt(Gr aphicsg)
{
[Link] ring(r,50, 60) ;
[Link] ring(n,60, 70) ;
[Link] ring(a,70, 80) ;
}
}
i
mpor tjav a.
appl et.*;
i
mpor tjav a.
awt .*;
/
*
<appletcode="Appl
et3"hei
ght
="300"wi
dth="
300"
>
<param name="no1"val
ue="
10">
<param name="no2"val
ue="
20">
</applet
>
*/
publ
i
ccl
assAppl
et3ext
endsAppl
et
{
publ
i
cvoidpaint(
Gr aphi
csg)
{
i
ntn1=Integer.
parseInt
(thi
[Link]
Par
amet
er(
"no1"
));
i
ntn2=Integer.
parseInt
(thi
[Link]
Par
amet
er(
"no2"
));
Stri
ngs=" Jav aAppl etPar amet erEx ampl e: sum ofn1andn2i s:"
+( n1+n2) ;
[Link] ring(s, 20, 20) ;
}
}
Graphi csCl ass: -
graphi csisapr e-def inedcl assi njav at odr aw di f
fer entt ypesof2d
designsl ikel ine,r ect angle,squar e,elipse,pol ygonet [Link] aphicsclass
mustbe wr itten i nsi de pai nt(
)ofappl etand comes underi mpor t
j
av [Link] .
Graphi cs [Link] fferentmet hods av ailablei nj av
af or
Graphi csclassar e:
[Link] ne(intx1, inty 1,i
ntx2, i
nty 2):
-usedt odr awal ine.
[Link] awRect (intx ,
inty ,i
nthei ght,i
ntwi dt h):
-usedt odr aw r ectangleand
squar e.
[Link] al(i
ntx ,
inty ,i
nthei ght,i
ntwi dth) :
-usedt odr awov alandci r
cle.
[Link] awPol ygon( int[]x poi nts,i
nt [
]y poi nts,
intnpoi nts) :-
used t o draw
polygons.
[Link] (intx ,
inty ,
inthei ght,i
ntwi dth,i
ntar cwi dth,intarcheight)
:
-usedt odr awr oundr ect angl e.
[Link] r
ing(St ri
ngname, intx, i
nty ):
-usedt odr awl ineoft ext.
[Link] awAr c(i
ntx, inty ,inthei ght ,
intwi dth,i
ntst artangle,intar cangle):-
used
todr awar c.
[Link] awI mage( Imagei mg,intx, inty ,ImageObser verob) :
-used t o draw
i
mage.
[Link]
ll
Rect (i
ntx ,i
nty ,
inthei ght ,i
ntwi dth):-usedt ofillrectangl eandsquar e.
[Link]
Ov al(
intx, i
nty ,
inthei ght ,i
ntwi dth):-
usedt of il
l oval andci rcle.
11.f ill
Pol ygon( int []xpoi nt s,i
nt[]y points,i
ntnpoi nts):-usedt ofillpolygons.
12.f ill
RoundRect (intx ,
inty ,
i
nthei ght,i
ntwi dth,
intar cwi dth,i
ntar cheight):
-
usedt of i
llroundr ect angl e.
[Link]
Ar c( i
ntx ,i
nty ,inthei ght,i
ntwi dth,
intst artangle,intar cangl e) :
-usedt o
fil
lar c.
Col orcl ass: -
Iti s a pr e-defined cl ass i nj av a ctreat ed by i mpor tj [Link] .Color
[Link] s cl ass i s used t o setcol orsf ort he componentand
cont ainer .
Fieldsusedf ort hiscl assar e:
Col [Link],Col [Link] eenet c.
Const ruct orsusedf ort hi sclassar e:
Col or(intr gb),Col or(intr ,intg,i ntb,i nta) , Col or (intr gba,bool ean
hasal pha) ,Color (floatr ,floatg, f l
oatb)et c.
Met hodsusedf ort hi sclassar e:
bright er( )
,darker (),get Col or (
String nm) ,get Color(St ring nm,Col orv )
,
get RGB( ),
hashCode( )etc.
Fontcl ass: -
Itisal soapr e-def i
nedcl assi nj avawhi chcomesundert hepackage
i
mpor tj av a.
awt .Font .Iti susedt odesi gnat extbyset ti
ngdi f
ferent
proper ti
esofFontcl ass.
Fieldsusedf ort hiscl assar e:
Font .BOLD, Font .ITALI C,Font .
PLAI Net c.
Const ruct orsusedf ort hi sclassar e:
Font (),Font (Stringname, intst yle,intsize)et c.
Met hodsusedf ort hi sclassar e:
creat eFont (i
ntf ont For mat ,Fi lef ontFile),cr eat eFont (intf ontFor mat,
Input St ream f ont St ream) ,decode( Stri
ngst r
),get Fami ly(
) ,
get Font (
String
nm) ,
get Font Name( ),getSi ze(),
get St y
le(),
isBol d(),
isItalic( )
,i
sPl ain(),
isTrans
formed( ).
(96) Wr iteapr ogr am t odr awaci rcleont heappl etwi ndow?
i
mpor tjav [Link] et .
* ;
i
mpor tjav [Link] .*;
/*<appl etcode=” My app3”hei ght =200wi dth=300>
</appl et >* /
publ i
ccl assMy app3ex tendsAppl et
{
publ i
cv oidpai nt( Gr aphi csg)
{
[Link] (40, 50, 90, 90, 200, 200) ;
[Link]
llRoundRect (40, 160, 90, 90,200, 200);
[Link] al(150, 50, 90, 90);
[Link]
ll
Ov al(150, 160, 90, 90);
[Link] c(270,50, 90, 90,0,360);
[Link]
ll
Arc( 270, 160, 90, 90,0,360);
}
}
(97)Ex:-
i
mpor tjav [Link].*;
i
mpor tjav [Link].*;
/*<appletcode=” My app4”height=200wi
dth=300>
</applet >*/
publiccl assMy app4ex t
endsApplet
{
Fontf ;
Stri
ngm;
publicv oidi nit
()
{
setBackgr ound(Col [Link]);
f=newFont ("Ari
al",Font .I
TALIC,20)
;
m=" Wel comet oJav a";
setFont (f);
}
publicv oidpai nt(Gr aphi csg)
{
Colorc=newCol or (0,255,0);
[Link] (c);
[Link] r i
ng(m,4, 20) ;
}
}
No. Appl
et Appl
icat
ion
1) Needspackagei
nit
ial
l
y. Noneedofpackagei
nit
ial
l
y.
2) Smal
lpr
ogr
ams. Lar
gepr
ogr
ams.
3) Usedt orunaprogr
am on Canbeexecut
edonst
andal
one
cl
ientbrowser
. syst
em.
4) Executed i
na r
est
ri
cted Access al
lresour
ces of t
he
envi
ronment. computer
.
5) Cr
eat
ed by ext
endi
ng Cr
eat
edbywr
it
ingpubl
i
cst
ati
c
j
ava.
appl
et.
Appl
et. v
oidmai
n(St
ri
ngar
gs[
])met
hod.
6) Itisportabl
eandcanbe Need JDK, JRE, JVM must
extecut
ed by any jav
a i
nstal
l
edoncl
ientmachi
ne.
support
edbrowser
.
8) Usedf
orGUI Usedf
orCUI
9) Specif
ic cl ass cal
l
ed Nospeci
fi
ccl
assr
equi
red
Appletrequi
red.
AWTCont r
ols: -
Label class: -
ALabelobj ecti sacomponentf orplacingtextinacontainercreatedby
thehel pofpr e-def i
nedcl assLabel .
Fields:
Label .CENTER, Label .
LEFT, [Link]
Const ructors:
Label (),Label(St ringtext),Label (
Stringtext,i
ntali
gnment)etc.
Met hods:
i
nt get Al
ignment ()
,St
ri
ng get Text (
),
void setText(
Str
ing t ext)
,v oi
d
set Ali
gnment (intalignment )etc.
(98) Wr iteapr ogr am tocr eateaLabelcl ass?
i
mpor [Link] et.
*;
i
mpor [Link] .
* ;
/*<appl etcode=” Myapp5”hei ght=200wi dth=300>
</appl et >*/
publ iccl assMy app5ex tendsAppl et
{
publ icv oidinit()
{
Label l1=newLabel (
);
l
1. setText (“hello” );
add( l1);
}
}
Buttoncl ass: -
Thiscl assi susedt ocr eateabut t
onwher eButtonisalsoapre-def
ined
class.
Const ruct ors:
Button( ),But ton(St ri
ngt ext)etc.
Met hods:
Stri
ng getLabel (
),
String getAct
ionCommand( ),
v oi
d
addAct ionLi st ener(Act i
onListenerl )etc.
(99)Wr iteapr ogram t ocr eateaBut tonclass?
i
mpor tjav [Link] et.*;
i
mpor tjav [Link] .*;
/*<appl etcode=” My app6”hei ght=200wi dt
h=300>
</applet >*/
publiccl assMy app6ex t
endsAppl et
{
publicv oidi nit()
{
Buttonb1=newBut ton();
[Link] (“submi t
”);
add(b1) ;
}
}
Checkboxcl ass:-
Acheckboxi sagr aphicalcomponentt hatcanbei nei t
heranon( t
rue)
orof f(false)st ateusi ngCheckboxasapr e-defi
nedclass.
Const ruct ors:
Checkbox (),
Checkbox( Stri
nglabel ),Checkbox(Stri
nglabel,
bool
eanst ate)
Met hods:
Stri
ng get Label ()
,bool ean get State(),
void setLabel
(Str
ing l
abel)
,v oi
d
setState( bool eanst at
e) ,Str
ingpar amSt ri
ng()etc.
(100) Wr i
teapr ogr am t ocreateaCheckboxcl ass?
i
mpor tjav [Link] et.*;
i
mpor tjav [Link] .*;
/*<appl etcode=” My app7”hei ght=200wi dt
h=300>
</applet >*/
publiccl assMy app7ex t
endsAppl et
{
publicv oidi nit()
{
Checkboxc1=newCheckbox( “hello”);
Checkboxc2=newCheckbox( “hi”)
;
add(c1) ;
add(c2) ;
}
}
CheckboxGr oupcl ass: -
Thiscl assi susedt ocr eateradiobut tonont hecont ainer.
Const ruct ors:
Checkbox Gr oup( )
Met hods:
getCur rent (),
get Select edCheckbox( ),voidset Cur rent(
Checkboxbox) ,
voidset Sel ect edCheckbox (Checkboxbox)
(101)Wr i
teapr ogr am t ocr eateaCheckboxGr oup/ radiobuttonclass?
i
mpor tjav [Link] et.
*;
i
mpor tjav [Link] .
* ;
/*<appl etcode=” Myapp8”hei ght=200wi dth=300>
</applet >*/
publiccl assMy app8ex tendsAppl et
{
publicv oidi nit()
{
Checkbox Gr oupc=newCheckboxGr oup( );
Checkboxc1=newCheckbox( “hello”,c,t
rue);
Checkboxc2=newCheckbox( “hi”
,c,false) ;
Checkboxc3=newCheckbox( “bye” ,
c,false);
add(c1) ;
add(c2) ;
add(c3) ;
}
}
Listclass: -
TheLi str epr esent sal istoft exti t
[Link] istcanbeconf igur
edt hat
usercanchooseei theronei t
em ormul tipleitems.
Const ruct ors:
List(
),
Li st(intr ows) ,List(Booleanmul ti
plemode)
Met hods:
void add( String i tem) ,voi
d add( Stri
ng i tem, i nt i ndex), v oid
addItem( String i tem) ,v oid addI tem( St
ri
ng i t
em, i nt index),i nt
countItems( ),
voi ddel Items( i
ntst art,intend) ,v oiddelItem(intposit
ion),
booleani sSel ect ed(inti ndex),bool eani sMul tipleMode( ),voi
dr emove(int
positi
on) , voidr emov e( Stri
ngi t
em) ,voidr emov eAll(
)
(102)Wr i
teapr ogr am t ocr eateaLi stcl ass?
i
mpor tjav [Link] et.
*;
i
mpor tjav [Link] .
* ;
/*<appl etcode=” Myapp9”hei ght=200wi dth=300>
</appl et>* /
publiccl assMy app9ex t
endsAppl et
{
publicv oi di nit(
)
{
Listl=newLi st(
5) ;
l
.add( “one” );
l
.add( “two” );
l
.add( “three” ) ;
l
.add( “four ”);
l
.add( “fi
v e” );
add(l);
}
}
Choi cecl ass: -
Theobj ectofChoi cecl assi susedt oshow popupmenuofchoi ces.
Choi cesel ectedbyuseri sshownont het opofamenu.I ti
nheri
ts
Componentcl ass.
Const ruct or s:
Choi ce()
Met hods:
voidadd( St r
ingi tem) ,
intgetItemCount () ,
voidr emov e( Stringitem) ,voi dremov eAll
(),
voidselect(
Stri
ngstr
),voi
d
select(intpos) ,
intget SelectedIndex( )
,Stri
ngget Sel
ectedIt
em().
(103) Wr iteapr ogr am tocr eat eaChoi ceclass?
i
mpor tjav [Link] et.
*;
i
mpor tjav [Link] .
* ;
/*<appl etcode=” My app10”hei ght=200wi dt
h=300>
</appl et>* /
publiccl assMy app10ext endsAppl et
{
publicv oi di nit(
)
{
Choi cec=newChoi ce( )
;
[Link](" I
tem 1" );
[Link](" I
tem 2" );
[Link](" I
tem 3" );
[Link](" I
tem 4" );
[Link](" I
tem 5" );
add(c) ;
}
}
TextFiel dcl ass: -
Theobj ectofaText Fieldcl assisat extcomponentt hatallowst he
editingofasi ngl elinet ex [Link]
nher itsText Componentcl ass.
Const ruct or s:
Tex tField( ),
Text Field(intcol umns) , TextField(Str
ingtext),
Tex tField( St r
ingt ext ,intcol umns)
Met hods:
intget Col umns( ),
charget EchoChar (),
voidset EchoChar (
charc) ,v
oid
setCol umns( intcol umns) ,voidset Text(St ri
ngt )
(104) Wr i
t eapr ogr am t ocr eat eaText Fieldclass?
i
mpor tjav a. appl et.*;
i
mpor tjav a. awt .*;
/*<appl etcode=” My app11”hei ght=200wi dt
h=300>
</applet >* /
publiccl assMy app11ext endsAppl et
{
publicv oidi nit()
{
Tex tFieldt 1, t
2;
t1=newTex tField(20) ;
t2=newTex tField(20) ;
[Link] (‘*’)
;
add(t1) ;
add(t2) ;
}
}
TextAr eacl ass: -
AText Ar eaobj ecti sat extcomponentt hatallowsfort heedi t
ingofa
mul t
iplel inesoft ex t.
Const ruct or s:
TextAr ea( ),Text Area( int r ows, i nt col umns) , TextArea(Str
ing text)
,
TextAr ea( St ri
ng t ext ,i ntr ows,i ntcol umns) ,TextArea(Stri
ng text
,int
rows, i
ntcol umns, i
ntscr ollbars)
Met hods:
voidappend( Stringst r),i
ntget Columns( ),i
ntget Rows(),v
oid
setColumns( intcol umns) ,v oidset Rows( introws)
(105) Wr i
t eapr ogr am t ocr eat eaText Areacl ass?
i
mpor tjav a. appl et.*;
i
mpor tjava. awt.*;
/*<appl etcode=” My app12”hei ght=200wi dt
h=300>
</appl et>*/
publiccl assMy app12ext endsAppl et
{
publicv oidi ni
t()
{
TextAr eaa=newText Area("Welcomet ojavatpoi
nt");
add(a) ;
}
}
Scrollbarcl ass: -
Scrollbarcont rolr epresent sascr ollbarcomponenti nordertoenabl e
usert osel ectf rom r angeofv alues.
Const ructor s:
Scrollbar (
),Scrollbar(intor i
entati
on),Scr oll
bar(i
ntor ient
ation,i
ntvalue,
i
ntv isible,intmi nimum, i
ntmaxi mum)
Met hods:
int get BlockIncr ement (),
int getLineIncrement(),i ntget
Maxi mum(),
int
getMax imum( ),i
nt getOr
ientation(),
int getPageIncrement
(),
int
getVal ue() ,
intget Visibl
e( )
,i
ntgetPageI ncrement()
(106)Wr i
teapr ogram tocreateaScr ol
lbarclass?
i
mpor [Link]
.*;
i
mpor [Link].*;
/*<appletcode=” Myapp13”hei ght=200width=300>
</applet>*/
publi
ccl assMy app13ext endsAppl et
{
publi
cv oidinit
()
{
Scroll
bars=newScr ol
lbar()
;
[Link]
Bounds( 100,100,
50,100);
add(s);
}
}
Imagecl ass:-
Imagecont rolissuperclassforalli
magecl assesrepr
esent
inggr
aphi
cal
i
mages.
Constructors:
Image( )
Met hods:
abstr acti ntget Hei ght (ImageObser v
erobser ver),abstr
actGr aphics
getGr aphi cs(),
ImageCapabi l
it
iesgetCapabi lit
ies(
Gr aphi
csConfi
gurati
on
gc)
(107) Wr iteapr ogr am t ocr eateaI magecl ass?
i
mpor tjav [Link] et.*;
i
mpor tjav [Link] .*;
/*<appl etcode=” My app14”hei ght=200wi dth=300>
</appl et >* /
publiccl assMy app14ext endsAppl et
{
Imagei mg;
publicv oi dinit
()
{
i
mg=get Image( get Document Base( )
,”abc.j
pg” );
}
publicv oi dpaint (Gr aphicsg)
{
[Link] mage( i
mg, 30, 30,this);
}
Canv as: -
TheCanv ascont r
ol repr esent sabl ankr ectangularareawherethe
applicat i
oncandr awort rapinputev entsfrom [Link]
nheri
tsthe
Componentcl ass.
Const ruct ors:
Canv as( ),
Canv as( Gr aphi csConf igurat i
onconf ig)
Met hods:
voidpai nt (Graphi csg) ,voidupdat e(Graphicsg) ,void
creat eBuf ferSt
r ategy (intnumBuf f
ers)
(108) Wr iteapr ogr am t ocr eateaCanv ascl ass?
i
mpor tjav [Link] .*;
publiccl assDr awi ngOv al extendsFr ame
{
publicDr awingOv al()
{
Canv asExcx=newCanv asEx();
[Link] Size( 125, 100) ;
[Link] Backgr ound( Col [Link]);
add( cx ,"Nor th");
setSiz e( 300, 200) ;
setVi sible( tr
ue) ;
}
publicst at i
cv oidmai n(Stri
ngar gs[]
)
{
newDr awi ngOv al();
}
}
classCanv asExex tendsCanv as
{
publicv oi dpai nt(Gr aphicsg)
{
[Link] or( Col [Link]) ;
[Link]
ll
Ov al(75, 10, 150, 75) ;
}
}
Framecl ass: -
Thecl assFr amei sat opl ev elwindow wi thbor derandtit
[Link]
Border Lay outasdef aultlayoutmanager .
Const ruct or s:
Frame( ),Fr ame( Gr aphi csConf i
gurati
on gc) , Fr ame(St
ri
ng t it
le)
,
Frame( St ringt i
tle,Gr aphi csConfigurati
ongc)
Met hods:
i
ntget Cur sor Ty pe() ,
intget ExtendedState(),
booleanisResi
zable(
),
Str
ing
getTitl
e( ),voi dset St ate(intstate),
voi
dset Titl
e(Str
ingti
tl
e)
(109)Wr iteapr ogr am t odesi gnaf rame?
i
mpor tjav [Link] .*;
classExampl e
{
Exampl e()
{
Framef =newFr ame( "Scroll
barExampl e")
;
f.
setSize( 400, 400) ;
f.
setLay out (nul l
);
f.
setVisi ble( true) ;
}
publicst at i
cv oidmai n(Stri
ngar gs[]
)
{
newEx ampl e();
//f.
setDef aul tCloseOper ati
on(Frame. EXIT_ON_ CLOSE);
}
}
Dialogcl ass: -
Dialogcont r
ol repr esent sat op-l
ev el windowwi thatit
leandabor der
usedt ot akesomef or m ofinputf rom t heuser.
Const ruct or s:
Dialog( Dial ogowner ) ,Dial
og( Frameowner ,Str
ingti
tle),Di
alog(
Window
owner )
,Di al
og( Dialogowner ,Stringt i
tl
e),Dialog(
Dialogowner ,St
ri
ng
ti
tle,bool eanmodal )
(110) Wr iteapr ogr am f ordialogcl ass?
i
mpor tjav [Link] .*;
i
mpor tjav [Link] .ev ent .*;
publ i
ccl assDi alogExampl e
{
privatest at i
cDi alogd;
DialogExampl e( )
{
Framef =newFr ame( );
d=newDi alog( f, "Di alogEx ampl e", tr
ue);
[Link] out (newFl owLay out (
));
But t
onb=newBut t
on( "OK");
[Link] ionLi st ener(newAct ionLi stener()
{
publ i
cv oi dact ionPer formed(Act ionEv ente)
{
DialogExampl [Link] Vi sibl
e(false);
}
}
);
[Link](newLabel ("Clickbut tont ocont i
nue.")
);
[Link]( b);
[Link] e( 300, 300) ;
[Link] ble( tr
ue) ;
}
publ i
cst at icv oi dmai n(Str
ingar gs[])
{
newDi alogEx ampl e() ;
}
}
Fil
eDi alogcl ass: -
Fil
eDi alogcont rolr epr esentsadi al ogwi ndowf rom whichtheusercan
selectaf il
e.
Const ructors:
Fil
eDial og(Dial
og par ent)
, Fi leDialog(Dial
og par ent, Stri
ng t i
tl
e),
Fil
eDial og(Dial
ogparent,Stringtit
le, i
ntmode) ,Fi
l
eDialog(Fr
amepar ent)
Fil
eDial og(Frameparent),
FileDialog(Framepar ent,
Stri
ngt i
tl
e,intmode)
Met hods:
String get Di
rect
ory()
,St
ring get Fil
e()
,i
nt get Mode( )
,Fi
lenameFil
ter
get Fi
lenameFi lt
er(
),
voidset Fil
e(Stri
ngf il
e),voi
dsetDirect
ory(Stri
ngdir)
,
voidset Mode(intmode)
(111) Wapf orfi
ledi
aloginj ava?
i
mpor tjava. awt .Button;
i
mpor tjava. awt .Fil
eDi al
og;
i
mpor tjava. awt .Frame;
i
mpor tjava. awt .[Link] ent;
i
mpor tjava. awt .[Link];
publ icclassMai nCl assext endsFr ame
{
Fil
eDi al
ogf c;
Mai nCl ass( )
{
super ("
Mai nCl ass");
set Size(200, 200) ;
fc=newFi leDi alog( t
his,"Chooseaf il
e",
Fil
eDi
alog.
LOAD)
;
[Link] Director y("C:\\");
But tonb;
add( b=newBut ton("Browse..."))
;
[Link] ionLi stener (newAct ionListener(
)
{
publ icvoidact ionPer formed( Act i
onEvente)
{
[Link] Visible(true) ;
Stringf n=f c. getFile();
i
f( fn==nul l)
Sy stem. out .println("Youcancel ledthechoice"
);
else
Sy stem. out .println("Youchose"+f n);
}
});
}
publ icstaticv oidmai n(Str
ing[]a)
{
newMai
nCl
ass(
).
set
Visi
ble(
true)
;
}
}
Panelcl ass:-
ThePanel i
sasi mpl estcont ainercl [Link]
desspaceinwhichan
applicat i
oncanat t achanyot hercomponent .I
tinheri
tst
heContai
ner
[Link]' thav et i
tl
ebar .
(112) Wr iteapr ogr am f orPanelcl ass?
i
mpor tjav [Link] .*
;
publiccl assPanel Exampl e
{
Panel Exampl e( )
{
Fr amef =newFr ame("Panel Exampl e");
Panel p=newPanel ();
p. setBounds( 40, 80,
200, 200) ;
p. setBackgr ound( [Link] ay);
But t
onb1=newBut ton("But ton1" );
b1. set Bounds( 50,100,80,30) ;
b1. set Backgr ound( Color .yell
ow) ;
But t
onb2=newBut ton("But ton2" );
b2. set Bounds( 100,100,80, 30);
b2. set Backgr ound( Color .green);
p. add( b1) ;
p. add( b2) ;
[Link]( p) ;
[Link] Size(400, 400) ;
[Link] Lay out(nul l);
[Link] Visible(true) ;
}
publ i
cst aticv oi dmai n(St ringar gs[]
)
{
newPanel Ex ampl e();
}
}
Menudesi gn:-
Theobj ectofMenuI tem classaddsasi mplelabeledmenuit
em onmenu.
Thei temsusedi namenumustbel ongtot heMenuI t
em oranyofit
s
subclass. Theobj ectofMenucl assi sapul ldownmenucomponent
whichi sdi splayedont hemenubar .I ti
nheri
tstheMenuI t
em cl
ass.
[Link] ass:-
MenuComponenti sanabst r
actcl assandi sthesuper cl
assf oral
lmenu-
relatedcomponent s.
Const ruct ors:-
MenuComponent ()
Met hods: -
St ri
ngget Name( )
,Fontget Font( )
,MenuCont ai
nerget Par ent
()
[Link] ass: -
TheMenuBarcl asspr ovi
desmenubarboundt oaf rameandi splat
form
speci fi
c.
Const r
uct or s:
-
MenuBar ()
Met hods: -
Menuadd( Menum) ,intcount Menus( ),Menuget Hel pMenu( ),
Menu
get Menu( inti),i
ntget MenuCount (),voidr emov e(intindex)
[Link] tem cl ass: -
TheMenuI tem cl assr epresent stheact uali
tem i [Link] lit
emsi na
menushoul dder ivef rom cl assMenuI tem,oroneofi [Link]
def aul t,itembodi esasi mpl elabel edmenui tem.
Const r
uct or s:
-
MenuI tem( ),
MenuI tem( Stri
ngl abel ),MenuI t
em( St r
ingl abel
,
MenuShor tcuts)
Met hods:
v oiddi sabl e( )
,voiddel et
eShor t
cut() ,
voi denabl e(),
voidenabl e(booleanb),
v oidset Shor tcut(MenuShor t
cuts)
St ri
ngget Label (),
MenuShor t
cutget Shor tcut(
),Stri
ngpar amSt ri
ng()
[Link] ass: -
TheMenucl assr epr esent spul l-
downmenucomponentwhi chis
depl oy edf rom amenubar .
Const r
uct or :
Menu( ),Menu( Stringl abel),Menu( St r
ingl abel,bool eant ear
Of f)
Met hod:
v oidaddSepar ator (),
i
ntcount It
ems( )
,voidadd( Stringl abel)
,int
get I
t emCount (),Stringpar amSt ri
ng( ),
v oidremov e(intindex)
v oidr emov e(i
nti ndex ),voidr emov e(MenuComponenti t
em)
5. CheckboxMenuI tem class: -
TheCheckboxMenuI tem cl assr epr esent sacheckboxwhi chcanbe
includedi [Link] ectingt hecheckboxi nthemenuchanges
cont r ol'
sst atefrom ont oof forf rom of ftoon.
Const ruct or :
CheckboxMenuI t
em( ) ,
CheckboxMenuI tem(label)
,
CheckboxMenuI t
em( label,booleanst at e)
Met hod:
booleanget State(),param( )
,voi
dset St ate(booleanb)
[Link] ass:-
Popupmenur epr esent samenuwhi chcanbedy namicall
ypoppedupat
aspeci f i
edposi ti
onwi thinacomponent .
Const ruct or :
PopupMenu( ),
PopupMenu( Stri
ngl abel )
Met hods:
MenuCont ai nerget Parent()
,voidshow( Componentor i
gin,
intx,
inty
)
(113)Wr iteapr ogr am f ormenudesi gn?
i
mpor tjava. awt .*;
classMenuExampl e
{
MenuEx ampl e()
{
Framef =newFr ame( "
MenuandMenuI tem Example"
);
MenuBarmb=newMenuBar ();
Menumenu=newMenu( "Menu" );
Menusubmenu=newMenu( "Format ");
MenuI tem i 1=newMenuI t
em( "Fi
le" );
MenuI tem i 2=newMenuI t
em( "Edit");
MenuI tem i 3=newMenuI t
em( "View" );
MenuI tem i 4=newMenuI t
em( "Font ")
;
MenuI tem i 5=newMenuI t
em( "Col or"
);
menu. add( i
1) ;
menu. add( i
2) ;
menu. add( i
3) ;
submenu. add( i
4) ;
submenu. add( i
5) ;
menu. add( submenu) ;
mb. add( menu) ;
f.
set MenuBar (mb) ;
f.
set Siz e(400, 400) ;
f.
set Lay out(nul l
);
f.
set Vi sible(true);
}
publ icst at i
cv oidmai n(St ri
ngar gs[ ]
)
{
newMenuEx ampl e( )
;
}
}
Swi ng: -
Iti sapar tofJav aFoundat ionCl asses( JFC)t hati susedt ocreate
wi ndow- based appl i
cat ions.I ti sbui lton t he top ofAWT ( Abst
ract
Wi ndowi ngTool kit)APIandent irelywr i
tteni [Link] i
keAWT,Jav a
Swi ngpr ov i
despl atform- i
ndependentandl ightweightcomponent s.
The
j
av ax. swi ng package pr ovi
des cl asses forj ava swi ng APIsuch as
JBut ton,JTex tField,JText Area,JRadi oBut ton,JCheckbox,JMenu,
JCol orChooseret c.
JBut ton:-
TheJBut toncl assi susedt ocr eat eal abeledbut t
ont hathasplatf
orm
i
ndependenti mpl ement [Link] icati
onr esul
tinsomeact i
onwhen
thebut t
oni spushed.I tinher itsAbst ractButtoncl ass.
Const ruct or:-
JBut ton() ,
JBut t
on( Strings) ,JBut ton( I
coni )
Met hod: -
voi dset Text (
St r
ings) ,St ri
ngget Text(),
voidset Enabled( bool
eanb),void
set I
con( Iconb) ,Iconget I
con( )
(114) Ex:-
i
mpor tjav [Link] .
*;
i
mpor tjav ax .
swing. *;
publ iccl assBut ton1
{
publ icst at i
cv oidmai n(St ri
ng[ ]args)
{
JFr amef =newJFr ame( "But tonExampl e");
JBut tonb=newJBut ton( "Cli
ckHer e");
[Link] Bounds( 50,100, 95, 30) ;
[Link]( b);
[Link] ze( 400,400) ;
[Link] out (null)
;
[Link] sible(true);
[Link] aul tCloseOper ation(JFr ame. EXIT_ON_ CLOSE) ;
}
}
JLabel :-
Theobj ectofJLabel classi sacomponentf orpl acingt extinacontai
ner.
Iti susedt odi spl ayasi nglel i
neofr eadonl yt [Link] extcanbe
changedbyanappl i
cationbutausercannotedi titdirectl
y .Itinheri
ts
JComponentcl ass.
Const ruct or:-
JLabel (),JLabel (St ring s) ,JLabel (
Icon i),JLabel(Str
ing s,I con i,int
hor i
zont al Alignment )
Met hod: -
String getText (),
void setText(Str
ing text), void
set Hor izont alAlignment (i
nt al
ignment ), I
con getIcon()
,i
nt
get Hor iz ont alAlignment ()
(115) Ex: -
i
mpor tjav ax .
swi ng. *;
classLabel Exampl e
{
publ icst aticv oidmai n(
St r
ingar gs[])
{
JFr amef =newJFr ame( "Label Exampl e");
JLabel l
1, l2;
l
1=newJLabel ("FirstLabel .");
l
1. setBounds( 50, 50, 100,30);
l
2=newJLabel ("SecondLabel .");
l
2. setBounds( 50, 100, 100,30);
f.
add( l1) ;[Link]( l2);
f.
set Size( 300, 300) ;
f.
set Lay out (nul l
);
f.
set Vi sibl e(true) ;
}
}
JText Fiel d:-
Theobj ectofaJTex t
Fieldcl assi sat extcomponentt hatal lowst he
edi t
ingofasi ngl el inetex t
.Itinher i
tsJText Componentcl ass.
Const ruct or:-
JTex t
Fi el d(),JTex t Field(Stri
ngt ext),JTextFiel
d(St
ri
ngt ext,intcol umns),
JTex t
Fi el d(intcol umns)
Met hod: -
Act ionget Act ion( ),
v oidset Font (Fontf)
(116) Ex: -
i
mpor tjav ax .
swi ng. *;
classText FieldEx ampl e
{
publ icst aticv oidmai n(
St r
ingar gs[])
{
JFr amef =newJFr ame( "TextFieldExampl e")
;
JTex tFieldt 1,t2;
t1=newJTex tField("Wel comet oJav atpoi
nt.
");
t1. set Bounds( 50, 100, 200,30) ;
t2=newJTex tField("AWTTut ori
al");
t2. set Bounds( 50, 150, 200,30) ;
[Link]( t1) ;
f .
add( t2);
[Link] Si ze(400, 400) ;
[Link] Lay out (nul l
);
[Link] Vi sible(true);
}
}
JText Ar ea:-
Theobj ectofaJText Areacl assi samul t
ili
ner egionthatdispl
aystext.I
t
allowst heedi tingofmul t
ipleli
net [Link]
nheri
tsJText Componentclass
Const ruct or:-
JTex tArea( ),
JTex tAr ea(St r
ing s) , JTextArea( i
nt r ow, int column),
JTex tArea( Strings, introw, i
ntcol umn)
Met hod: -
voi dset Rows( i
ntr ows) ,voidset Columns( i
ntcol s)
, v
oidappend(Str
ings),
voi dset Font (Fontf ),v oidinsert(Stri
ngs, i
ntposi ti
on)
(117) Ex: -
i
mpor tjav [Link] ng. *;
publ iccl assText AreaEx ampl e
{
Text Ar eaEx ampl e()
{
JFr amef =newJFr ame( );
JTex tAreaar ea=newJText Area("Wel cometoj avatpoint")
;
ar ea. set Bounds( 10, 30, 200,200) ;
[Link]( area) ;
[Link] Si ze(300, 300) ;
[Link] Lay out (nul l
);
[Link] Vi sible(true);
}
publ icst aticv oidmai n(St r
ingar gs[]
)
{
newText AreaEx ampl e();
}
}
JPasswor dFiel d:-
Theobj ectofaJPasswor dFieldclassi sat extcomponentspeci al
ized
forpasswor dent r
y .Itallowst heedi ti
ngofasi ngleli
[Link]
s
JTex t
Fi eldcl ass.
Const ruct or:
-
JPasswor dField(),JPasswor dField(i
ntcol umns) ,JPasswordField(Stri
ng
tex t
) ,
JPasswor dFiel d(Stringt ext,i
ntcolumns)
(118) Ex: -
i
mpor tjav [Link] ng. *;
publ iccl assPasswor dFieldExampl e
{
publ icst at i
cv oidmai n(String[]args)
{
JFr amef =newJFr ame( "Passwor dFieldExampl e")
;
JPasswor dFieldv al ue=newJPasswor dField()
;
JLabel l
1=newJLabel ("Passwor d:")
;
l
1. setBounds( 20,100, 80,30) ;
value. set Bounds( 100, 100, 100,30);
[Link]( value) ;f .
add( l
1) ;
[Link]( 300, 300) ;
[Link] out (null);
[Link] sible(true);
}
}
JCheckbox: -
TheJCheckBoxcl assi susedt ocr eateacheckbox.I tisusedtot urnan
opt i
onon( tr
ue)orof f(false).Cl i
ckingonaCheckBoxchangesi tsstate
from " on"t o"of f
"orf rom " off"to" on".I
tinherit
sJToggl eButt
oncl ass.
Const ruct or:
-
JCheckBox (),
JChechBox (St r
ing s) , JCheckBox( Stri
ng text, bool ean
select ed) ,JCheckBox( Act i
ona)
Met hod: -
Accessi bl eCont ext getAccessi bl
eCont ext(),
prot
ected Stri
ng
par amSt ring()
(119) Ex: -
i
mpor tjav [Link] ng. *;
publ iccl assCheckBoxEx ampl e
{
CheckBoxEx ampl e( )
{
JFr amef =newJFr ame( "
CheckBoxExampl e")
;
JCheckBoxcheckBox 1=newJCheckBox( "C++" );
checkBox1. set Bounds( 100,100,50,50);
JCheckBoxcheckBox 2=newJCheckBox( "
Java",true);
checkBox2. set Bounds( 100,150,50,50);
f.
add( checkBox1) ;
f.
add( checkBox2) ;
f.
set Size( 400, 400) ;
f.
set Layout (null);
f.
set Visible( tr
ue) ;
}
publ i
cst at icv oidmai n(Str
ingar gs[]
)
{
newCheckBoxEx ampl e()
;
}
}
JRadi oBut ton: -
TheJRadi oBut toncl assisusedt ocr eatearadi obut [Link] o
chooseoneopt ionf r
om mul ti
pleopt i
[Link] swi delyusedi nexam
systemsorqui z. I
tshoul dbeaddedi nBut t
onGr oupt osel ectoneradio
buttononl y.
Const ruct or :
-
JRadi oBut ton( )
,JRadi oButton(Stri
ngs) ,JRadioBut ton(Str
ings,bool ean
selected)
Met hod: -
voidset Text (Strings) ,Str
ingget Text()
,voi
dsetEnabl ed(booleanb),void
setIcon( Iconb) ,Iconget I
con( )
,voi
dset Mnemoni c(i
nta)
(120) Ex:-
i
mpor tjav ax .swi ng.*;
publ i
ccl assRadi oBut tonExampl e
{
JFramef ;
Radi oBut tonExampl e( )
{
f=newJFr ame( );
JRadi oBut tonr 1=newJRadi oBut t
on(“A”)Male"
);
JRadi oBut tonr 2=newJRadi oBut t
on(“B”)Female");
r1.
set Bounds( 75, 50,100,30);
r2.
set Bounds( 75, 100,100,30);
ButtonGr oupbg=newBut t
onGr oup();
[Link]( r1) ;
bg. add( r2);
f.
add( r1);
f.
add( r2);
[Link] ze( 300, 300) ;
[Link] out (nul l
);
[Link] sible( true) ;
}
publ icst at icv oidmai n(
Str
ing[]ar gs)
{
newRadi oBut tonEx ampl e();
}
}
JComboBox: -
Theobj ectofChoi ceclassi susedt oshow popupmenuofchoi ces.
Choi cesel ectedbyuseri sshownont hetopofamenu.I tinheri
ts
JComponentcl ass.
Const r
uct or :-
JComboBox (
),JComboBox( Obj ect[
]items) ,JComboBox( Vector<?
>items)
Met hod: -
voi daddI tem( Obj ectanObj ect),voidr emov eIt
em( ObjectanObject)
,void
remov eAl l
Items( ),v oidsetEditable(bool eanb)
(121) Ex:-
i
mpor tjav ax .
swi ng. * ;
publ iccl assComboBoxExampl e
{
JFr amef ;
ComboBox Ex ampl e( )
{
f=newJFr ame( "ComboBoxExampl e");
St ri
ngcount ry[]={"Indi a"
,"
Aus" ,
"U.S.A","England",
"Newzealand"
} ;
JComboBoxcb=newJComboBox( country)
;
cb. setBounds( 50, 50,
90,20);
f.
add( cb) ;
f.
set Lay out (null);
f.
set Size( 400, 500) ;
f.
set Vi sible( tr
ue) ;
}
publ icst at icv oidmai n(
Str
ing[]ar gs)
{
newComboBoxEx ampl e()
;
}
}
JLi st:-
Theobj ectofJLi stcl assrepr esent sal istoftextit
[Link] i
stoftext
i
temscanbesetupsot hatt heusercanchooseei theroneitem or
mul t
iplei tems.I tinher it
sJComponentcl ass.
Const ruct or:-
JList (),JLi st(ar y[
]listData) ,
JList (
List
Model <ary>dataModel)
Met hod: -
i
nt get Sel ect edIndex (),
ListModelget Model ()
,voi
d setListDat
a(Obj
ect[
]
l
ist Dat a)
(122) Ex: -
i
mpor tj av ax .swing. *;
publ iccl assLi stEx ampl e
{
ListEx ampl e( )
{
JFr amef =newJFr ame( )
;
Def aul tList Model <St r
ing>l 1=newDef ault
ListModel<>()
;
l
1. addEl ement (
"It
em1" );
l
1. addEl ement (
"It
em2" );
l
1. addEl ement (
"It
em3" );
l
1. addEl ement (
"It
em4" );
JList <St ring>l ist=newJLi st<>(l1);
l
[Link] Bounds( 100, 100, 75,75);
f.
add( list);
f.
set Si ze( 400, 400);
f.
set Lay out (
nul l)
;
f.
set Vi sibl e(true) ;
}
publ icst aticv oidmai n(Stri
ngar gs[])
{
newLi st Exampl e();
}
}
JScr ollBar :
-
Theobj ectofJScr ollbarcl assi susedt oaddhor i
zontalandv er
ti
cal
scr ollbar .I tisani mpl ement ationofascr ol
lbar.I
tinherit
sJComponent
class.
Const ruct or:-
JScr ol l
Bar (),JScr ollBar(i
nt or ientati
on),JScr oll
Bar(i
nt orient
ati
on,int
value, i
ntex tent ,i
ntmi n,intmax)
(123) Ex: -
i
mpor tj av ax .swing. *;
classScr ollBar Exampl e
{
Scrol l
Bar Ex ampl e()
{
JFramef =newJFr ame( "Scroll
barExampl e");
JScr ollBars=newJScr ollBar (
);
[Link]( 100, 100, 50,100) ;
f.
add( s) ;
f.
set Size( 400, 400) ;
f.
set Lay out (null);
f.
set Visibl e(tr
ue) ;
}
publicst aticv oidmai n(St ri
ngar gs[]
)
{
newScr ollBar Exampl e();
}
}
JSepar at or:
-
Theobj ectofJSepar atorcl assi susedt oprovi
deageneralpur
pose
componentf ori mpl ement ingdi vi
derl i
[Link] ali
neto
separ at ewi dget si naLay out.I
tinheritsJComponentclass.
Const ruct or:
-
JSepar ator (
),JSepar at or(intorientati
on)
Met hod: -v oi
dset Or i
ent ati
on( i
ntor i
entati
on) ,i
ntget
Ori
ent
ati
on()
(124) Ex: -
i
mpor tj av [Link]. *;
classExampl e
{
publicst aticv oidmai n(St ri
ngar gs[]
)
{
JMenumenu, submenu;
JMenuI tem i 1, i
2, i3,i
4, i5;
JFramef =newJFr ame( "Separat orExampl e")
;
JMenuBarmb=newJMenuBar ();
menu=newJMenu( "
Menu" )
;
i
1=newJMenuI tem( "Item 1" );
i
2=newJMenuI tem( "Item 2" );
menu. add( i
1);
menu. addSepar ator();
menu. add( i
2);
mb. add( menu) ;
f.
set JMenuBar (
mb) ;
f.
set Size( 400, 400) ;
[Link] (
nul l
);
[Link](true);
[Link] tCloseOper at
ion(JFr ame.EXIT_ ON_ CLOSE) ;
}
}
JTr ee:-
The JTr ee cl ass i s used t o display t he t ree st r uct
ured dat a or
hierarchicaldat [Link] eeisacompl excomponent .I thasa' rootnode' at
thet opmostwhi chi sapar entf oral lnodesi nt het r
ee.I tinherits
JComponentcl ass.
Const r
uct or:-
JTr ee(),
JTr ee( Object[]value),JTree(TreeNoder oot )
(125) Ex:-
i
mpor tjav [Link] ng.*;
i
mpor tjav [Link] [Link]
[Link] ault
Mut ableTr eeNode;
publ i
ccl assTr eeEx ampl e
{
JFr amef ;
Tr eeExampl e()
{
f=newJFr ame( );
Def aultMut abl eTreeNodest yle=newDef aultMut abl eTr eeNode("St yl
e");
Def aultMut abl eTreeNodecol or=newDef aul t
Mut abl eTr eeNode( "color"
);
Def aultMut abl eTreeNodef ont=newDef aul t
Mut abl eTr eeNode( "f
ont ")
;
sty l
[Link]( color )
;
sty l
[Link]( font);
Def aultMut abl eTreeNoder ed=newDef aul tMutabl eTr eeNode( "r
ed" );
Def aultMut abl eTreeNodebl ue=newDef aul tMutabl eTr eeNode( "blue");
Def aultMut abl eTreeNodebl ack=newDef aultMut abl eTr eeNode("black")
;
Def aultMut abl eTreeNodegr een=newDef aultMut abl eTr eeNode( "gr
een");
col
[Link]( r
ed);col
[Link](bl
ue);col
or.
add(
black)
;col
or.
add(
green)
;
JTreejt=newJTr ee(styl
e);
f.
add(jt)
;
f.
setSize(200,
200);
f.
setVisibl
e(tr
ue);
}
publi
cst ati
cv oi
dmai n(Stri
ng[
]args)
{
newTr eeEx ample(
);
}
}
JTabl e:-
TheJTabl ecl assi susedt odi splaydat aint
[Link]
scomposed
ofrowsandcol umns.
Const ruct or:-
JTabl e(),JTabl e(Object[]
[]rows,
Object[
]columns)
(126)Ex: -
i
mpor tjav ax .
swi ng. *;
publiccl assTabl eExampl e
{
JFramef ;
TableEx ampl e()
{
f=newJFr ame( );
Stri
ngdat a[
][]={{"101" ,
"Ami t","
670000" },
{"102" ,"Jai",
"780000" },
{"101" ,"Sachin" ,
"700000" }}
;
Stri
ngcol umn[ ]
={ "ID","NAME" ,"
SALARY" };
JTablej t=newJTabl e(data,column) ;
j
[Link]( 30,40, 200,300) ;
JScrol l
Panesp=newJScr ollPane( jt
);
f.
add( sp) ;
f.
setSi ze(300, 400) ;
f.
setVi sible(true);
}
publicst at i
cv oidmai n(Stri
ng[ ]args)
{
newTabl eEx ampl e();
}
}
JProgr essBar :-
TheJPr ogressBarcl assi susedt odi spl
aytheprogressoft [Link]
i
nher i
tsJComponentcl ass.
Const ruct or:-
JProgr essBar ()
,JPr ogr essBar (i
ntmi n,intmax),JProgressBar
(intor
ient
),
JProgr essBar (i
ntor ient,intmi n, i
ntmax)
Met hod: -
void set St ri
ngPai nted( bool ean b) ,v oid setStr
ing(St
ri
ng s) ,v oi
d
setOrient ation(intor i
ent ati
on) ,voidset Val
ue(
intval
ue)
(127)Ex: -
i
mpor tjav ax .
swi ng. *;
publiccl assPr ogr essBar Exampl eextendsJFrame
{
JProgr essBarj b;
i
nti=0, num=0;
ProgressBar Exampl e()
{
j
b=newJPr ogr essBar(0,2000);
j
[Link]( 40,40,160,30);
j
[Link] ue( 0);
j
[Link] ri
ngPai nted(tr
ue) ;
add( j
b) ;
setSize(250, 150) ;
setLay out(nul l
);
}
publicv oidi terate()
{
while(i<=2000)
{
j
[Link] ue( i
) ;
i
=i+20;
tr
y
{
Thread. sleep( 150) ;
}
catch(Ex cept ione)
{
}
}
}
publicst ati
cv oidmai n(Stri
ng[]args)
{
ProgressBar Exampl em=newPr ogressBar
Exampl
e();
[Link] Visible(true);
[Link]();
}
}
JTabbedPane: -
The JTabbedPane cl ass is used t o swit
ch bet
ween a gr
oup of
component sbycl i
ckingonat abwi thagiventi
tl
eoricon.I
tinher
it
s
JComponentcl ass.
Const ructor :
-
JTabbedPane( )
,JTabbedPane( int tabPlacement),
JTabbedPane(
int
tabPl acement ,
i
ntt abLay outPol icy)
(128) Ex: -
i
mpor tjav ax .
swi ng. *
;
publ iccl assTabbedPaneEx ampl e
{
JFr amef ;
TabbedPaneExampl e()
{
f=newJFr ame( );
JTex tAr eat a=newJTex tArea(200,200) ;
JPanel p1=newJPanel ()
;
[Link]( ta);
JPanel p2=newJPanel ()
;
JPanel p3=newJPanel ()
;
JTabbedPanet p=newJTabbedPane( );
[Link] Bounds( 50,50,200,200) ;
[Link]( "mai n",p1) ;
[Link]( "v i
sit",
p2) ;
[Link]( "hel p",p3) ;
[Link]( tp);
[Link] ze( 400, 400) ;
[Link] out (nul l
);
[Link] si ble(true) ;
}
publ icst at i
cv oidmai n(St r
ing[]args)
{
newTabbedPaneExampl e();
}
}
JCol or Chooser :-
TheJCol orChoosercl assisusedt ocreateacol orchooserdi
alogboxso
thatusercansel ectanycol or
.I ti
nheritsJComponentcl ass.
Const ruct or:-
JCol or Chooser (
) ,
JColor Chooser (
colorini
tial
color)
Met hod: -
voidaddChooser Panel(Abst r
act ColorChooserPanelpanel),stat
icColor
showDi alog( Componentc, Stringtitl
e,Colorinit
ial
Color
)
(129) Ex: -
i
mpor tjava. awt .ev ent.
*;
i
mpor tjava. awt .* ;
i
mpor tjavax .swi ng.*;
publi
cclassCol orChooser ExampleextendsJFr ameimplementsActi
onL
i
stener{
JButtonb;
Containerc;
ColorChooser Ex ampl e()
{
c=getCont ent Pane( );
c.
setLay out (newFl owLay out()
);
b=newJBut ton( "color")
;
[Link] st ener(thi
s);
c.
add( b);
}
publi
cv oidact ionPer formed(Acti
onEvente)
{
Colorini
tialcol or =[Link];
Colorcolor =JCol orChooser .
showDial
og( t
his,
"Selectacol
or"
,i
nit
ial
col
or)
;
1 AWT component
s Java swi
ng component
s
) ar
epl
atf
orm-
dependent
. arepl
atf
orm-
independent
.
2 AWT component
s Swing component
s
) ar
eheav
ywei
ght
. ar
el i
ght
wei
ght
.
3 AWTdoesn't suppor
t Swingsuppor
ts pl
uggabl
elook
) pl
uggabl
elookandf
eel. andfeel
.
4 AWT prov
idesl
ess Swing provi
desmor
e power
ful
) component
sthanSwing. componentssuch as tabl
es,
l
i
sts,scrol
lpanes,col
orchooser
,
t
abbedpaneetc.
5 AWTdoesn't f
ollows Swi
ngf
oll
owsMVC.
) MVC(ModelVi ew Controll
er)
wheremodelrepresent
sdat a,
vi
ew repr
esentspresentati
on
and contr
oll
er acts as an
i
nter
facebetweenmodeland
vi
ew.
6 I
tisadesi
gni
ngt
ool
. I
tisanadv
ancementov
erAWT.
)
7 AWT classes st
art
ed wi
th St
art
ed wit
h cont
rolname and
) cont
rol
name. pr
eceededbyJlet
ter
.
8 Package-
impor
tjav
[Link]
.*; Package-
impor
tjav
ax.
swi
ng.
*;
)
c=getContentPane()
;
card=newCar dLayout(
40,
30)
;
c.
setLayout(card)
;
Jav aI /O: -
Itisusedt opr ocesst hei nputandpr oducet heout put
.Javausest he
conceptofst ream t omakeI /O oper ationf [Link] av a.
io package
cont ainsal lthecl assesr equi r
edf ori nputandout putoper ati
[Link]
per f
or mf ilehandl i
ngi njavabyJav aI/ OAPI .
Pre-def inedf ilei /of unct i
ons: -
[Link]( ):-Readst henex tbyteofdat ai nani [Link]-1ifi
t
encount erst heendofst ream.
[Link] lable( )
:-Ret urnst het otal numberofby t
esav ail
ableforreadingina
stream.
[Link]( longn) :-
Di scar dsorski psnby tesofdat afrom theinputstream.
[Link]( ):
-Releasest her esour ceconnect edt oast ream andcl osethe
stream.
[Link] ():-
Takest hei nputpoi ntertot hepr ev i
ouslysetmar kort he
begi nni ngoft hest ream.
[Link] k(intby te) :
-Placesamar katt hecur rentpointintheinputst r
eam
andt hismar ksr emai nsunt ilndat aby t
esar eread.
[Link] i
te( ):-
Wr itesout putt ot hedi sk.
[Link]( ):
-Closest heby teout putst ream.
[Link]
ush( ):-
For cesanybuf feredout putt obewr i
ttenont hediskandcl ears
thebuf fer s.
[Link] Name( ):-gett henameoft hef i
le.
[Link] Par ent():
-getpar entnameoft hef i
le.
12. get Par ent File():
-gett hepar entf il
e.
13. get Pat h( ):-gett hepat hoffile.
14. isDi rect or y():-checki ngf ordi r
ect oryspecifi
edistrueornot.
15. isFi le() :
-checki ngf orf il
especi fiedistrueornot .
16. cr eat eNewFi le():-usedt ocreateanewf i
le.
17. del et e( ):-usedt odel eteaf il
e.
18. mkdi r():-usedt omakeadi rector y.
19. mkdi rs( ):-usedt omakemor ethanonedi rector
y.
St ream: -
Ast ream i sasequenceofdat [Link] aast ream iscomposedofby tes.
It'
scal ledast ream becausei ti slikeast ream ofwat erthatcont
inuesto
flow. Inj av a,3 st reams ar e creat ed forus aut omat i
call
[Link]
streamsar eat tachedwi t hconsol e.
[Link] andar dSt ream: -
i
.Sy stem. out : standar dout putst r
eam
i
[Link] st em. in: st andar di nputst ream
i
[Link] st em. er r:st andar der rorstream
(144) Ex: -
i
mpor tjav [Link]. *;
publ i
ccl assHel lo
{
publ i
cst aticv oidmai n(St ri
ngar gs[ ]
)throwsI OException
{
Input St reamReadera=nul l;
try
{
a=newI nput St r
eamReader (System. in);
Sy st em. out .
pr intln(“ent er‘ q’t
oqui t” )
;
charch;
do
{
ch=( char )a. read( )
;
Sy st em. out .
pr int(ch) ;
}
whi le( ch! =’ q’);
}
final l
y
{
i
f (a!=nul l)
{
[Link] ose( );
}
}
}
}
Ex: -
i
mpor tj av a.i
o.* ;
publ iccl assHel lo
{
publ icst aticv oidmai n( Str
ingargs[])
{
Filef =newFi l
e(“abc. txt”);
FileReaderf r=newFi leReader (f
);
Buf fer edReaderbr =newBuf f
eredReader(fr)
;
i
ntc=0;
whi le((c=br .r
ead( ))!=-1)
{
charch=( char )c;
Sy stem. out .printl
n( ch);
}
}
}
Ex: -
i
mpor tj av a.i
[Link] iter;
publ iccl assFi leWr iterEx ample
{
publ icst aticv oidmai n( Str
ingargs[])
{
Try
{
FileWr iterf w=newFi leWr it
er("
D:\\t
estout.
txt")
;
fw. wr i
t e("Wel comet oj ava.")
;
fw. close( );
}
cat ch( Ex cept ione)
{
Sy stem. out .printl
n( e);
}
Sy stem. out .
pr i
ntln("Success. ..
")
;
}
}
[Link] teSt ream: -
Jav aby test reamsar eusedt oper f
ormi nputandoutputof8-bitby
tes.
Thought herear emanycl assesr el
atedt oby t
est
reamsbutt hemost
frequent lyusedcl assesar e,Fil
eInputStr
eam andFil
eOutputSt
ream.
(145) Ex: -
i
mpor tjav [Link].*;
publ iccl assHel l
o
{
publ icst at i
cv oi
dmai n(Str
ingar gs[
])thr
owsI OExcept
ion
{
Fil
eI nput St ream i n=null;
Fil
eOut put St ream out =null
;
try
{
i
n=newFi leInput Stream( “
[Link]
”);
out =newFi leOut putStream( “output
.txt
”);
i
ntc;
whi le((c=i [Link]())!=-
1)
{
out .
r ead( c);
}
fi
nal ly
{
i
f(in!=nul l)
{
i
[Link] ose( );
}
i
f(out !
=nul l)
{
out .
cl ose( );
}
}
}
}
[Link] act erSt r
eam: -
Jav aBy test reamsar eusedt oper f
ormi nputandout putof8-
bitbytes,
wher easJav aChar acterstreamsar eusedt operfor
mi nputandout put
for16- bituni [Link] herearemanycl assesrel
atedtocharacter
streams but the most fr
equently used cl
asses
are, FileReaderandFi leWrit
er .
(146) Ex:-
i
mpor tjav [Link].*;
publ iccl assHel l
o
{
publ icst at i
cv oi
dmai n(Str
ingar gs[
])thr
owsI OExcept
ion
{
Fil
eReaderi n=nul l;
Fil
eWr i
terout =nul l
;
tr
y
{
i
n=newFi leReader(“i
nput.
txt
”);
out=newFi l
eWr i
ter(
“output
.t
xt”)
;
i
ntc;
while((c=in.
read())
!=-
1)
{
out.
r ead(c);
}
fi
nally
{
i
f(i
n!=nul l
)
{
i
[Link]();
}
i
f(out !
=null)
{
out.
cl ose();
}
}
}
}
JDBC(
CH-
16)
Whati sJDBC?
JDBCst andsf orJavaDat abaseConnect i
vit
y,whi chisastandardJava
API f or dat abase-independent connect ivi
ty bet ween t he Java
programmi ngl anguageandawi derangeofdat abases.
TheJDBCl ibraryincl
udesAPI sforeachoft het asksmentionedbel
ow
thatarecommonl yassoci atedwithdatabaseusage.
Ma kingaconnect iontoadat abase.
CreatingSQLorMy SQLstatement s.
Execut ingSQLorMy SQLquer i
esinthedat abase.
Viewing&Modi fyi
ngt heresult
ingrecords.
JDBCAr chitecture:
TheJDBC API (Appl icationPor tsuppor tsbot ht wo-t
ierandt hree-
tier
processi ng model sf or dat abase access but i n gener al,JDBC
Architectureconsi stsoft wol ay ers−
J DBC API :Thi s pr ov ides t he appl i
cat ion-t
o-JDBC Manager
connect ion.
J DBC Dr i
v er API :This suppor tst he JDBC Manager -t
o-Driver
Connect ion.
TheJDBCAPIusesadr iv
ermanageranddat abase-speci f
icdr i
verst o
providet ranspar entconnect i
v it
yt ohet erogeneousdat abases.
TheJDBC dr i
v ermanagerensur est hatt hecor rectdri
v erisusedt o
accesseachdat asour [Link] i
vermanageri scapabl eofsuppor ti
ng
mul t
iple concur rent dr ivers connect ed t o mul ti
ple het er
ogeneous
databases.
Component sofJDBC: -
Dr i
v erManager :Thi scl assmanagesal istofdat abasedr i
vers.
Mat chesconnect ionr equest sf rom t hej av aappl i
cationwi ththe
properdat abasedr i
verusi ngcommuni cat i
onsubpr ot
ocol .The
fi
rstdr i
v ert hatr ecogni zesacer tai
nsubpr otocolunderJDBCwi l
l
beusedt oest abli
shadat abaseConnect ion.
Dr i
v er:Thisi nterface handl es t he communi cations wi tht he
databaseser [Link] llinteractdirect l
ywi thDriv
erobj ectsv ery
[Link] ead,y ouuseDr iv
erManagerobj ects,whi chmanages
objectsoft hist [Link] soabst ractst hedet ai
lsassoci atedwi th
wor ki
ngwi thDr iverobject s.
Co nnect ion:Thi si nterface wi th allmet hods f orcont acting a
[Link] connect ion obj ect r epr esents communi cati
on
cont ext ,i.e. ,al l communi cati
on wi th dat abase i st hrough
connect ionobj ectonl y.
S tatement : Youuseobj ectscr eatedfrom t hisi nt
erfacet osubmi t
theSQLst at ement st ot hedat [Link] iv
edi nterfaces
acceptpar amet er sinaddi ti
ont oexecut i
ngst or edprocedur es.
R esul tSet :Theseobj ectshol ddat aretr
ievedf rom adat abaseaf t
er
youex ecuteanSQLquer yusi ngSt at
ementobj [Link]
it
erat ort oal lowy out omov et hr
oughi t
sdat a.
S QLExcept ion: Thi s cl ass handl es any er rorst hatoccuri na
databaseappl i
cat ion.
JDBCDr i
ver s:-
JDBCDr i
veri sasof twar ecomponentt hatenablesj av aappl i
cati
ont o
i
nteractwi tht hedat abase. Ther eare4t ypesofJDBCdr ivers:
[Link]- ODBCbr i
dgedr i
ver (
type1dr i
ver)
[Link] ive-APIdr i
v er/ par ti
allyjavadr i
ver(t
ype2dr iver)
[Link] wor kPr ot ocol dri
v er/full
yjavadr i
ver(ty
pe3dr i
ver)
[Link] ndr iv er
/ful lyj av adr i
v er(t
ype4dr i
ver)
1)Ty pe1Dr iver:
-
TheJDBC- ODBC br idgedr iverusesODBC dr iv ert oconnectt ot he
[Link]- ODBCbr idgedr i
verconv er tsJDBCmet hodcal l
s
i
ntot heODBCf unct i
oncal [Link] sisnowdi scour agedbecauseoft hin
dri
v er.
Advantages:
o e asytouse.
o c anbeeasil
yconnectedtoanydat
abase.
Di
sadvantages:
o P erf
ormancedegr adedbecauseJDBC met
hodcal
lisconv
ert
ed
i
ntotheODBCf uncti
oncall
s.
o TheODBCdr i
v erneedstobeinstal
ledonthecl
ientmachine.
2)Type2Dr iv
er:
-
TheNativeAPIdriverusesthecl
ient-
sidel
ibr
ari
[Link]
dri
verconvert
sJDBCmet hodcallsintonat
ivecall
softhedat abase
API.I
tisnotwrit
tenentirel
yinj
ava.
Adv antage:
o p erf
ormanceupgr adedt hanJDBC- ODBCbr i
dgedri
ver.
Disadv antage:
o T heNat i
vedriverneedst obeinstal
ledontheeachcli
entmachine.
o T heVendorcl i
entli
braryneedst obeinst
all
edonclientmachine.
3)Ty pe3Dr i
ver:
-
o T heNet workPr ot
ocoldr i
verusesmi ddl
eware(appli
cati
onserver)
thatconvertsJDBC cal l
sdirectlyorindir
ect
lyintothev endor-
specif
icdatabaseprotocol.I
tisfull
ywrit
teninj
ava.
Advant
age:
o Noc l
i
entsi
del
i
brar
yisr
equi
redbecauseofappl
i
cat
ionser
vert
hat
canper form manyt askslikeauditi
ng,l
oadbal ancing,
loggingetc.
Disadvant age:
o Ne t
wor ksuppor ti
sr equi
redoncl i
entmachi ne.
o R equiresdat abase-speci
fi
ccodi ngtobedonei nthemi ddl
et i
er.
o Ma i
ntenanceofNet workPr ot
ocoldriverbecomescost l
ybecause
itrequiresdat abase-speci
f i
ccodingtobedonei nthemi ddleti
er.
4)Type4Dr iver:-
Thet hindr i
v erconvertsJDBCcal l
sdi r
ectlyintothev endor-specif
ic
databasepr otocol
.Thati swhyi tisknownast hi
ndr i
[Link] ul
ly
writ
teni nJav alanguage.
Adv antage:
o B etterper formancet hanal lotherdr i
vers.
o Nos oftwarei srequi r
edatcl ientsideorser verside.
Disadv ant age:
o Dr iver sdependont heDat abase.
Stepst oconnectt odat abasei nj
av a:-
Ther ear e5st epst oconnectanyj av aapplicationwi ththedat abasein
j
av ausi ngJDBC.
1)Regi stert hedr i
vercl ass
Thef orName( )met hodofCl asscl assi susedt or egisterthedr i
ver
cl
[Link] smet hodi susedt ody nami call
yloadt hedr i
verclass.
Syn:-
publ i
cst at i
cvoidf orName( Stri
ngcl assName) t
hrowsCl assNotFoundExc
ept i
on
ex:-
[Link]( "[Link]
[Link]
");
2)Cr eatet heconnect ionobj ect
The get Connect i
on( )met hod ofDr iverManagercl ass is used to
establishconnect i
onwi t
ht hedat abase.
Syn:-
1.1)publ icst ati
cConnect i
onget Connect ion(Stri
ngur l)
throwsSQLExcept i
on
2.2)publ icst aticConnect i
onget Connect i
on( Stri
ngur l
,Str
ingname, Stri
ngp
asswor d)
[Link] owsSQLEx cept i
on
ex :-
[Link] ioncon=Dr i
verManager .getConnect ion(
2."jdbc: oracle: t
hin:@l ocal host :1521:xe","syst em","
passwor d"
) ;
3)Cr eat etheSt atementobj ect
Thecr eat eStat ement ()met hodofConnect i
oni nterfacei susedt o
cr eatest atement .Theobj ectofst atementi sresponsi blet oexecut e
quer i
eswi ththedat abase.
[Link] n:-
[Link] icSt atementcr eateSt atement (
)throwsSQLExcept i
on
ex :-
St atementst mt =con. cr eateSt atement ();
4)Ex ecut et hequer y
The ex ecut eQuer y()met hod ofSt atementi nterf
ace i s used t o
execut equer iest ot hedat [Link] smet hodr eturnst heobj ectof
Resul tSett hatcanbeusedt ogetal lther ecordsofat able.
Sy n:-
publ icResul t
Setexecut eQuer y(Stri
ngsql )throwsSQLExcept i
on
ex :-
[Link] tSetr s=st mt .execut eQuer y("
select*f rom emp" );
[Link] l
e([Link] ())
3.{
[Link] stem. [Link]([Link](1) +""+[Link] Stri
ng(2));
5.}
5)Cl oset heconnect i
onobj ect
Bycl osingconnect ionobj ectst atementandResul tSetwi llbecl osed
aut omat i
cal l
[Link] ose( )met hodofConnect i
oni nterfacei susedt o
closet heconnect i
on.
Sy n:-
publ icv oidcl ose( )throwsSQLExcept i
on
ex :-
con. close( );
Dr iverManagercl ass: -
TheDr iverManagercl assact sasani nt erfacebet weenuseranddr iver
s.
Itkeepst rackoft hedr iverst hatareav ailableandhandl esest abl
ishinga
connect ion bet ween a dat abase and t he appr opriate dr i
[Link]
Dr i
v erManagercl ass mai ntains a l i
stofDr iv
ercl asses t hathav e
registered themsel ves by calli
ng t
he met hod
DriverManager .regi st erDr iver().
Met hods: -
[Link] icst aticv oi dr egi ster Driver(Dr
iverdr iver)
[Link] icst aticv oi dder egisterDr iv
er(Driv erdr i
v er)
[Link] icst aticConnect ionget Connect ion( Stringur l)
4. publ ic st at ic Connect ion get Connect ion(
Stri
ng ur l
,
St ri
ng
user Name, Stringpasswor d)
Connect ioncl ass: -
AConnect i
oni st hesessi onbet weenj av aappl icati
onanddat [Link]
Connect ioni nter facei saf act oryofSt at ement ,PreparedStatement,and
DatabaseMet aDat ai .[Link] ectofConnect ioncanbeusedt ogett he
objectofSt at ementandDat abaseMet aDat [Link] ioninterface
prov i
de many met hods f ort ransaction managementl i
ke commi t
(),
roll
back( )etc.
Met hods: -
[Link] icSt atementcr eat eSt atement ()
[Link] icSt atementcr eat eSt atement (i
ntr esultSet Type,
int
resultSet Concur rency )
[Link] icv oidset Aut oCommi t(booleanst atus)
[Link] icv oidcommi t()
[Link] icv oidr ollback( )
[Link] icv oidcl ose( )
Statementcl ass: -
TheSt atementi nt er facepr ov i
desmet hodst oexecut equeri
eswi ththe
[Link] atementi nterfacei saf actor yofResul tSeti.e.i
t
prov i
desf actor ymet hodt ogett heobjectofResul tSet.
Met hods: -
[Link] icResul tSetex ecut eQuer y (
Str
ingsql )
[Link] ici ntexecut eUpdat e(Stringsql)
[Link] icbool eanex ecut e(St ri
ngsql )
[Link] ici nt[
]execut eBat ch( )
Resul tSetcl ass: -
Theobj ectofResul tSetmai ntainsacur sorpoi nt i
ngt oarowofat able.
I
niti
al l
y ,cursorpoi ntst obef oret hefir
str ow.
Met hods: -
[Link] icbool eannext ()
[Link] icbool eanpr ev ious( )
[Link] icbool eanf irst ()
[Link] icbool eanl ast ()
[Link]
icbooleanabsol ute(introw)
[Link]
icbooleanr elat i
ve( i
ntr ow)
[Link]
icintgetI
nt(intcol umnI ndex)
[Link]
icintgetI
nt(St ri
ngcol umnName)
[Link]
icStri
ngget St ri
ng( intcol umnIndex)
[Link]
icStri
ngget String( Stri
ngcol umnName)
Prepar
edStatementcl ass:-
ThePreparedStatementi nterfacei sasubinterf
aceofSt at
ement
.Iti
s
usedtoexecutepar amet erizedquer y.
Methods:-
[Link]
icvoidsetInt(intpar amI ndex,intval
ue)
[Link]
icvoidsetString( intpar amI ndex,Str
ingvalue)
[Link]
icvoidsetFloat (intpar amI ndex,fl
oatv al
ue)
[Link]
icvoidsetDoubl e(intpar amI ndex,doublevalue)
[Link]
icintexecuteUpdat e()
[Link]
icResultSetex ecut eQuer y()