0% found this document useful (0 votes)
241 views214 pages

Core Java Progrmmers

The document provides an introduction to Java programming, detailing key concepts such as compilers, algorithms, flowcharts, and programming languages. It outlines the historical development of programming languages, features of object-oriented programming (OOP), and the history and versions of Java. Additionally, it discusses the Java Development Kit (JDK), Java Runtime Environment (JRE), and the Java Virtual Machine (JVM), along with the features that make Java a popular programming language.

Uploaded by

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

Core Java Progrmmers

The document provides an introduction to Java programming, detailing key concepts such as compilers, algorithms, flowcharts, and programming languages. It outlines the historical development of programming languages, features of object-oriented programming (OOP), and the history and versions of Java. Additionally, it discusses the Java Development Kit (JDK), Java Runtime Environment (JRE), and the Java Virtual Machine (JVM), along with the features that make Java a popular programming language.

Uploaded by

Pranjal Nale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

I

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

[Link] yoper at or:-theoper atorwhi chisusedt oper f


or m ov era
si
ngl eoper andi scal ledunar yoper ator.
ex:-a++
[Link] nar yoper ator :
-theoper atorwhi chisuset ooper ateov ertwo
oper andi scal ledbi naryoper at or .
ex:-a+b
[Link] nary /condi t
ionaloper ator :-t he oper atorwhi ch is used t o
oper ateov ermor ethant wooper andsi scalledt er
naryoper ator
.
syn: -dat atypev ar iable=(condi ti
on) ?st atement 1:statement 2;
(9)Wr iteapr ogr am t of indt hegr eat ernumberamongt woi nputt
ed
numberusi ngt ernar yoper ator?
classHi
{
publ icst aticv oidmai n(Stringargs[ ]))
{
i
nta=5, b=6;
Strings=( a>b) ? “ai sgr eater”:
“bisgr eat er ”;
Sy stem. out .print(s) ;
}
}
(10) Wr i
t eapr ogr am t ocheckf orleapy earusingt ernaryoper ator?
classLeap
{
publ icst aticv oidmai n(Stringargs[ ]))
{
i
nt2018;
Strings=( ((y%100! =0)&&( y%4==0) )
||(y%400==0) )?“leapy ear”
:“not”;
Sy stem. out .print(s) ;
}
[Link] twise oper ator:-
the oper atorwhi ch is used t o perform bi t
oper ationov ertheoper andorv ariabl eas0and1i scal l
edbi twise
oper ator.
typs:
i
. bi wi seand( &)
i
i. bi twi seor (|)
i
i
i. bi t
wi sex or(^)
i
v. bi t
wi secompl ement (~)
v
. bi t
wi selef tshift(<<)
v
i. bi wiser i
ghtshi ft(
>>)
(11)Wr i
teapr ogr am f orbit wiselef
tshiftoperat
or?
classTest
{
publicstati
cv oidmai n(Stringar gs[
])
)
{
i
nta=15, b=2,c;
c=a<<b;
Sy st
em. out
.print(“v
al ueofc=” +c);
}
}
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0
5 4 3 2 1 0
(11110)2=1x2+1x2+1x 2+1x2+0x2+0x2=32+16+8+4+0+0=60
(12)Wr i
teapr ogr am f orbit wisecompl ementoperat
or?
classDemo
{
publicstati
cv oidmai n(Stringar gs[
])
)
{
i
nta=14, b;
b=~a;
Sy st
em. out
.print(“v
al ueofc=” +b);
}
}
(13)Wr i
teapr ogr am f orbit wiseandoper ator?
classHel l
o
{
publicstati
cv oidmai n(Stringar gs[
])
)
{
i
nta=14, b=7,c;
c=a&b;
Sy st
em. out
.print(“v
al ueofc=” +c);
}
}
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
0
(110) 2=1x22+1x 21+0x20=4+2+0=6
10. Increment /decr ementoper at or:-
i
. I ncrementoper ator :
-t hisoper atori
susedt oi ncreasethe
valueoft hev ar
iabl ebyonei ntwodi f
ferentway s.
[Link] e-increment :-firstincreaset hevalueaf terthatupdat eit
.
ex -++a
[Link] -i
ncr ement :
-f i
rstupdat ethevalueaf t
eri ncreaseit.
ex -a++
(14)Wr i
teapr ogr am f ori ncrementoper ator?
classI ncr ease
{
publ i
cst at i
cv oidmai n(St ri
ngar gs[]))
{
i
nta=5, b,c;
b=a+++ ++a;
c=++a+a++;
Sy stem. out .
println(“valueofb=” +b) ;
Sy stem. out .
println(“valueofc=” +c) ;
}
}
i
i. Decr ementoper ator:-t hisoper atori
susedt odecr easethe
valueoft hev ar
iabl ebyonei ntwodi f
fer entway s.
[Link] e-decr ement :-firstincreaset hevalueaf terthatupdateit.
ex ---
a
[Link] -decr ement :
-f i
rstupdat et hevalueafteri ncreaseit
.
ex -a--
(15)Wr i
teapr ogr am f ordecr ementoper ator?
classDecr ease
{
publ i
cst at i
cv oidmai n(St ri
ngar gs[]))
{
i
nta=- 8,b,c;
b=- -
a;
c=a- -
;
Syst
em.
out
.pr
int
ln(
“val
ueofb=”
+b)
;
Syst
em.
out
.pr
int
ln(
“val
ueofc=”
+c)
;
}
}
Cont
rolSt
ruct
ure(
CH-
3)
Cont rolst ructur eist hecont rolfl
owofpr ogram execut ionwherewecan
usedi f
fer entt y pesofst atement stopr ocessourpr [Link] ear e
differentt ypesofst atement savail
ableincont r
ol str
ucturethatare:
i. sel ectionst atements
ii. l oopi ngst atement s
iii
. j umpi ngst atements
Condi t
ionalst atement s:-Thesear ethet ypesofst atement swher ewe
use condi tions t o process t he pr ogram usi ng some r elat
ional
oper ator stopr oducet rueorf al
sev alue.
Ty pes:-
1.I f/simpl ei f:
-
Her ewear eabl eto specifyonl yonecondi t
ionand onepr int
stat ement .thedemer itofthisst atementi sitcannotgot othe
def aultpar t
.
sy n:-
if(
condi t
ion)
printst atement ;
(16) Writeapr ogr am t ocheckwhet herani nputtednumberi sev enor
notusi ngsi mpl eif?
classHel lo
{
publ i
cst at i
cv oi dmai n(St
ri
ngar gs[])
)
{
i
nta=6;
i
f(a%2==0)
Sy stem. out .
print (
“numberi seven”);
}
}
2.I felse: -
Wear eabl et ospeci f
yonl yonecondi ti
onbutt woprintstatement
meansonef ort ruepartandanot herf orfalsepar t.
sy n:-
i
f(condi t
ion)
printstatement1;
else
printstatement2;
(17)Wr iteapr ogram toi nputt woi ntegernumberandf i
ndthegreater
oneusi ngi felse?
classTest
{
publicst ati
cv oidmain( Str i
ngar gs[]
))
{
i
nta=5, b=7;
i
f(a>b)
Sy st
em. out .
print(
“aisgr eat er ”
);
else
Sy st
em. out .
print(“bi
sgr eat er”)
;
}
}
[Link] edif:-
Her ewear eabl et ospeci fynnoofcondi ti
onsandnnumberof
printstatement [Link] hepr oblem isthati
tisaverycomplexty
pe
ofst atementwher ewegetconf useaboutthestar
tingandendi
ng
ofifblockbecauseofnest edstructur
e.
syn:-
i
f(condi t
ion1)
i
f(conditi
on2)
.
.
printstatement 1;
else
printstatement 2;
.
.
else
i
f(condi t
ionn)
printstatement -1;
else
printstatement n;
(18) Writeapr ogr am t oinputay earandcheckwhetheri
tisl
eapyearor
notusi ngnest edi f?
classTest
{
publ icstati
cv oidmai n(Stri
ngar gs[]
))
{
i
nty =2018;
i
f(y %100! =0)
i
f(y %4==0)
Sy stem. out.
print(“l
eapy ear” )
;
else
Sy stem. out.
print(“not”)
;
else
i
f(y %400==0)
Sy stem. out.
print(“leapy ear”);
else
Sy stem. out.
print(“not ”
);
}
}
(19) Writeapr ogr am t oinputt hreeint
egernumberandfi
ndthegr
eatest
oneusi ngnest edi f?
classTest
{
publ icstati
cv oidmai n(Stri
ngar gs[]
))
{
i
nta=85, b=124, c=17;
i
f(a>b)
i
f(a>c)
Sy stem. out.
print(“aisgr eatest”)
;
else
Sy stem. out.
print(“cisgr eatest”)
;
else
i
f(b>c)
Sy stem. out.
print(“bisgr eatest”)
;
else
Sy stem. out.
print(“cisgr eatest”)
;
}
}
[Link] seif:-
Itisthet ypeofcondi ti
onalstatementwher ewecanspeci fyn
noofcondi t
ionsandnnoofpr intstatement
[Link]
ysimple
ascompar et onestedifbecauseher enonesti
ngofconditi
onis
thereandwecanspeci fyoneconditionandonepr i
ntst
atement
soon.
syn:-
if(
conditi
on1)
printstatement 1;
elseif(condit
ion2)
printstatement 2;
.
.
else
printstatement ;
(20)Wr iteapr ogram t oinputanintegernumberandcheckwhet heri
tis
evenoroddandposi ti
veornegat i
veusingladderelseif?
classTest
{
publicst ati
cv oidmai n(Str
ingargs[
]))
{
i
ntn=9;
i
f(n%2==0&&n>0)
Sy st
em. out.
print
(“numberi sevenandposi t
ive”)
;
elseif(n%2! =0&&n<0)
Sy st
em. out.
print
(“numberi soddandnegat ive”)
;
elseif(n%2==0&&n<0)
Sy st
em. out.
print
(“numberi sevenandnegat i
v e”
);
elseif(n%2! =0&&n>0)
Sy st
em. out.
print
(“numberi soddandposi ti
ve”);
else
Sy st
em. out.
print
(“specialnumber”);
}
}
(21)wr i
t eapr ogram toi nputt
hreeintegernumberandf i
ndthegreat
est
oneusi ngl adderel seif?
classTest
{
publ i
cst ati
cv oidmai n(Stringar gs[]
) )
{
i
nta=89, b=21,c=56;
i
f(a>b&&a>c)
Sy [Link] .
print
( “
aisgr eat est ”
);
elsei f
(b>a&&b>c)
Sy [Link] .
print
( “
bisgr eat est ”
);
else
Sy [Link] .
print
( “
cisgr eat est ”
);
}
}
(22) Writ
eapr ogram t of indt heel ectr
ici
tychargesaccor
dingt
othe
followingcondi t
ionsusi ngl adderel seifstatement?
[Link] ts char gesinrupees
wit hi
nf i
rst100uni t
s 100r s
next50uni ts 1.0r s/ u
next75uni ts 1.5r s/ u
next125uni t
s 2.0rs/ u
next200uni t
s 2.5r s/ u
mor ethant hat 5.0r s/ u
classTest
{
publ i
cst ati
cv oidmai n(Stringar gs[]
) )
{
doubl eunit=325, charge;
i
f(uni t
>=1&&uni t<=100)
char ge=100;
elsei f
(unit>=101&&uni t
<=150)
char ge=100+( unit-
100) *
1;
elsei f
(unit>=151&&uni t
<=225)
char ge=100+50+( unit
-150) *1. 5;
elsei f
(unit>=226&&uni t
<=350)
char ge=100+50+112. 50+( hr -225)*2.0;
elsei f
(unit>=351&&hr <=551)
char ge=100+50+112. 50+250+( unit-350) *
2.5;
else
char ge=100+50+112. 50+250+400+( unit-
550) *5.0;
pr i
nt f(“
elect ri
citychar ges=”+char ge)
;
}
}
i
. Uncondi t i
onalst atement s:
-Thesear et hetypesofst atements
wher ewedon’ tuseanycondi t
ionr at
[Link] o
producet rueorf alsestatement .Casesconsi stofconstantsor
expr essi ons.
Ty pes: -
[Link] tch- casest atement :-
Itist het ypeofuncondi t
ionalstatementwher ewear eabl etospecifyn
[Link] ocksar ecreatedbyt hehel pofkey wordcaseand
ex itedbyt hehel pt hekey wordbr [Link] ssatisfiedi
nsidethe
swi tch bl ockt hen i tgoest ot hedef aultbl ockspeci fi
ed bydef aul
t
key wor d.
sy n:-swi tch( expressi on)
{
case<case- constant1>:
statement (s);
break;
.
.
case<case- constantn>:
statement (s);
break;
defaul t:
statement (s);
}
( 23) Wr it
eapr ogr am t oimpl ementacal culat
orusi ngswi tchcase?
classTest
{
publ i
cst aticv oidmai n( Str
ingargs[])
)
{
i
nta=10, b=2, c;
charchoi ce=’ *’
;
swi tch( choi ce)
{
case‘+’:
c=a+b;
break;
case‘-‘
:
c=a-b;
break;
case‘*’:
c=a*b;
break;
case‘/’:
c=a/b;
break;
case‘%’:
c=a%b;
break;
defaul
t:
[Link] .
print(“
wrongchoi ce”);
}
[Link] .
print(“
calculatedv alue=”+c) ;
}
}
i
i. Loopi ng st atement s:- These ar e al
so cal l
ed i t
erative or
repeat at
ivest atement [Link] oexecut eorpr i
ntone
statementf ormor et hanonet i
mewi t
hasi nglespeci ficati
on
thenweuset heconceptofl [Link] eateingal ooping
statementweneedcomponent s.
[Link]
zation:-from whi cht hev ari
ablev al
uest art
sexecut i
on
orpr i
nti
ng.
[Link] ti
on:-upt owhi chthev ar
iablevalueshouldgoes.
[Link] /decr:-usedt oi ncreaseordecr easethev alueoft he
variabl
eaf tereachexecut i
on.
Types:-
[Link] leloop:-
Itisot herwisecal ledast op-testedl ooporpr e-t
estedl ooporent r
y
cont r
olloop.i nt hi
st ypeofl oopingst atementf i
rstthecondi ti
onis
checkedaf terthest atement sar egetexecut edandpr [Link]
condi tioni sfalset hennost atementi
sexecut
edorpri
nted.
syn:-
variablev alueinitializat
ion;
whi l
e(condi ti
on)
{
st atement ( s);
incr /decr;
}
printst atement (s);
(24)Wr iteapr ogr am t opr i
nt1t o10? 1
classDemo
2
{
publ i
cst aticv oidmai n( Stri
ngar gs[
])) 3
{ 4
i
nti =1; 5
whi l
e(i<=10)
6
{
Sy [Link] .println(
i); 7
i
++; 8
} 9
}
10
}
2 2 2 2
(25)Wr iteapr ogr am t of indtheout putof1+2+3+. .
..
n?
i
mpor [Link] il
.*;
classx
{
publ i
cst aticv oidmai n( Stri
ngar gs[
])
{
i
ntn;
Scannersc=newScanner (System.i
n);
Sy [Link] .println(
“ent eranumber ”);
n=sc. nextInt();
i
nti =1,sum=0;
whi l
e(i<=n)
{
sum=sum+( i*i)
;
i
++;
}
Sy [Link] .print(
“sum=” +sum);
}
}
(26)Wr iteapr ogr am toinputanumberandcheckwhetheri
tispri
meor
not?
i
mpor [Link] i
l.*;
classx
{
publ i
cst aticv oidmai n(Str
ingargs[
])
{
i
nta, i=1,c=0;
Scannersc=newScanner (Syst
em.i
n);
Sy [Link] .printl
n(“ent
eranumber ”);
a=sc. nex t
Int();
whi l
e( i
<=a)
{
i
f(a%i ==0)
c++;
i
++;
}
i
f(c==2)
Sy [Link] .print(
“numberi sprime”
);
else
Sy [Link] .print(
“numberi snotpri
me” )
;
}
}
(27)Wr ite a pr ogram t oi nputa numberand check whetheriti
s
pal i
ndromeornot?
i
mpor [Link] i
l.*;
classx
{
publ i
cst aticv oidmai n(Str
ingargs[
])
{
i
ntnum, rem, rev =0,t
emp;
Scannersc=newScanner (Syst
em.i
n);
Sy [Link] .printl
n(“ent
eranumber ”);
num=sc. nex tInt();
temp=num;
whi le(num! =0)
{
rem=num%10;
rev =rev *10+r em;
num=num/ 10;
}
i
f(temp==r ev )
Sy stem. [Link](“numberi spal i
ndrome” )
;
else
Sy stem. [Link](“numberi snotpal indrome”
);
}
}
(28) Wr ite a pr ogr am t o conv erta decimalnumberi
ntoits bi
nar
y
equi val ent?
i
mpor tjav [Link].
*;
classx
{
publ icst aticv oidmai n(Stri
ngar gs[
])
{
i
ntnum, prd=1, sum=0, rem;
Scannersc=newScanner ([Link]);
Sy stem. [Link](“enteranumber ”);
num=sc. nex tInt();
whi le(num! =0)
{
rem=num%2;
sum=sum+r em* prd;
prd=pr d* 10;
num=num/ 2;
}
Sy stem. [Link](“binaryequivalent
=” +sum);
}
}
(29) Wr iteapr ogr am toi nputanumberandcheckwhet heri
tisstr
ong
numberornot?
145=1!
+4!
+5!
=1+24+120=1
45
i
mpor [Link]
.*;
classx
{
publicst ati
cv oidmain(Stri
ngargs[]
)
{
i
ntnum, fact=1,sum=0,rem,temp;
Scannersc=newScanner (
Syst
em. i
n);
Sy st
em. out .
pr i
ntl
n(“
enteranumber ”)
;
num=sc. nex tI
nt()
;
temp=num;
whi l
e(num! =0)
{
fact=1;
rem=num%10;
whi l
e(rem! =0)
{
fact=fact*rem;
rem- -
;
}
sum=sum+f act;
num=num/ 10;
}
i
f(sum==t emp)
Sy st
em. out .
pr i
nt(
“numberisstrong”)
;
else
Sy st
em. out .
pr i
nt(
“numberisnotstrong”)
;
}
}
(30)Wr iteapr ogram t
oi nputanumberandcheckwhet
heri
tisper
fect
numberornot?
i
mpor [Link]
.*;
classx
6=1+2+3
{ =6
publicst ati
cv oidmain(Stri
ngargs[]
)
{
i
ntnum, i=1,sum=0;
Scannersc=newScanner (
Syst
em. i
n);
Sy stem. out .printl
n(“ent
eranumber ”)
;
num=sc. nex tI
nt ()
;
whi le(i<num)
{
i
f(num%i ==0)
sum=sum+i ;
i
++;
}
i
f(sum==num)
Sy stem. out .print(
“numberisper fect”
);
else
Sy stem. out .print(
“numberisnotper fect”)
;
}
}
Wapt oi nputanumberandcheckwhet heri
tisami
rr
ornumberornot
?
12- >144- >441- >21->12
i
mpor tjav [Link]
l.*;
i
mpor tjav a.l
ang. *;
6=1+2+3
classx =6
{
publ icst aticv oidmai n(
Str
ingar gs[]
)
{
i
ntnum, rev 1,r
ev 2,r
em1,rem2,s1,s2;
Scannersc=newScanner (System. i
n);
Sy stem. out .printl
n(“ent
eranumber ”)
;
num=sc. nex tI
nt ()
;
s1=num* num;
whi le(num! =0)
{
rem1=num%10;
rev 1=rev 1* 10+r em1;
num=num/ 10;
}
s2=Mat [Link] t
(rev1);
whi le(s2! =0)
{
rem2=s2%10;
rev 2=rev 2* 10+r em2;
s2=s2/ 10;
}
i
f(rev 2==num)
Sy stem. out .pr i
nt (“numberi smi r
ror”)
;
else
Sy stem. out .pr i
nt (“numberi snotmi rr
or”);
}
}
Wapt oi nputanumberandcheckwhet heritisadi sari
um numberor
not ?
1 2 3
175- >1+7+5=1+49+125=175
Wapt oinputanumberandcheckwhet heritisamagi cnumberornot ?
199- >19- >10- >1
(or)
1729- >19- >91- >19X91=1729
Wapt oinputanumberandcheckwhet heritisaperfectsquar enumber
ornot ?
2
10- >10>- 100
[Link]- whi lel oop: -
Itisot her wi secal ledasbot tom-testedlooporpost -testedloopor
exitcont roll oop.I nt hi
st ype ofl ooping statementf i
rstthe
statement sar egetex ecutedandpr int
edaf t
erthatt heconditi
onis
checked.I ft hecondi ti
oni sfalset henalsoitpr ints/executesa
statement .
syn:-
variabl ev aluei ni
tiali
zati
on;
do
{
stat ement (s);
i
ncr /decr ;
}
whi l
e( condi tion);
printst at ement (s);
(31) Wr it
eapr ogr am t opr i
ntt heseriesli
ke11,22,33,
...
.,
99?
classDemo
{
publ i
cst at
icvoidmai n(Stri
ngargs[]
)
{
i
nti =11;
do
{
Sy [Link]
intln(
i)
;
i
=i+11;
}
whi l
e(i<=99);
}
}
(32)Wr iteapr ogram toinputani ntegernumberandfi
ndthesum ofi
ts
digits?
i
mpor [Link]
il.
*;
classx
123=1+2+3=
{ 6
publ i
cst at
icvoidmai n(Stri
ngargs[]
)
{
i
ntnum, rem,sum=0;
Scannersc=newScanner (Syst
em. i
n);
Sy [Link]
intln(
“enteranumber ”);
num=sc. nextI
nt();
do
{
rem=num%10;
sum=sum+r em;
num=num/ 10;
}
whi l
e(num! =0);
printf(
“sum ofdi git
s=%d” ,
sum);
}
}
(33)Wr iteaprogr am toinputanumberandf i
ndit
sfact
ori
alval
ue?
i
mpor [Link]
il.
*;
classx
5!=5x4x3x2x1=12
{ 0
publ i
cst at
icvoidmai n(Stri
ngargs[]
)
{
i
ntnum, fact=1;
Scannersc=newScanner ([Link]);
Sy st
em. [Link]
n(“enteranumber ”)
;
num=sc. nextInt(
);
do
{
fact=fact*num;
num- -;
}
whi l
e(num! =0) ;
Sy st
em. [Link](
“factori
alvalue=”+fact)
;
}
}
(34)Wr ite a pr ogram t oi nputa numberand check whet
heri
tis
armst rongornot?
i
mpor [Link]
.*; 153=13+53+33=1+125+27=1
classx
{ 53
publicst at
icv oidmai n(Str
ingar gs[
])
{
i
ntnum, rem,sum=0;
Scannersc=newScanner ([Link]);
Sy st
em. [Link]
n(“enteranumber ”)
;
num=sc. nextInt(
);
temp=num;
do
{
rem=num%10;
sum=sum+( rem* rem* rem);
num=num/ 10;
}
whi l
e(num! =0) ;
i
f(temp==sum)
Sy st
em. [Link](
“numberi sar mstrong”);
else
Sy st
em. [Link](
“numberi snotar mst r
ong”)
;
}
}
[Link] oop: -
Itist hesi mpl estt ypeofl oopingst at
ementbecauseher eallt
he
threepar tsoft hel oopwr i
tteninonel i
ne;soitreducethel
ineof
codes.
syn: -for(initial
ization; condi t
ion;i
ncr/decr)
(35) Wr iteapr ogr am t opr i
ntt heseriesli
ke50,45,
40,
...
.5?
classSer i
es
{
publ icst aticv oidmai n(Stringargs[])
{
i
nti ;
for(i=50; i
>=5; i
=i-
5)
{
Sy stem. out .printl
n( i
);
}
}
}
(36) Wr iteapr ogr am t ofindt hehcfandl cm oftwointegernumber?
i
mpor tjav [Link]
.*;
classHel l
o
{
i
ntnum1, num2, hcf,l
cm, i;
publ icst aticv oidmai n(Stringargs[])
{
Scannersc=nwScanner (
Sy [Link]);
Sy stem. out .printl
n( “
ent er2number ”
);
num1=sc. next I
nt();
num2=sc. next I
nt();
for(i=1;i<=num1, i
<=num2; i++)
{
i
f(num1%i ==0&&num2%i ==0)
hcf =i;
}
l
cm=( num1* num2) /
hcf ;
Sy stem. out .print(
“ hcfv al
ue=” +hcf);
Sy [Link] .
print(
“ l
cm value=”+l
cm);
}
}
(37)Wr i
teapr ogr am tofindnf i
bonaccinumber
sstart
ingfrom 0?
i
mpor tj
[Link]
.*;
classFi bo
{
Intpr ev=0,curr=1,
nex t
=0,i,
num;
publ i
cst ati
cv oidmai n(Stri
ngargs[]
)
{
Scannersc=nwScanner (
Sy st
[Link])
;
Sy [Link] .
printl
n(“enterrange”
);
num=sc. nextInt()
;
Sy [Link] .
printl
n(prev);
Sy [Link] .
printl
n(curr);
for(i
=1; i
<=num- 2;
i++)
{
next =prev+cur r;
Sy [Link] .
printl
n(next);
prev =curr;
cur r
=next ;
}
}
}
(38)Wr i
te a pr ogram t o displ
aysum ofal lthe even number
sand
productofal ltheoddnumber sinbetween1to10?
classSer i
es
{
publ i
cst ati
cv oidmai n(Stri
ngargs[]
)
{
i
nti ,
ev en=0,odd=1;
for(i
=1; i
<=10;i++)
{
i
f (
i%2==0)
even=ev en+i;
else
odd=odd* i;
}
Sy st
em. [Link]
ln(“
ev ensum=” +even);
Sy st
em. [Link]
ln(“
oddpr oduct=”+odd);
}
}
(39)Wr i
teapr ogram t oprintal
lthepr i
menumbersbetween1and100?
classSer ies
{
publicstat i
cv oidmai n(Str
ingargs[]
)
{
i
nti ,
j
,c=0;
for(i
=1;i
<=100; i
++)
{
for(j
=1;j
<=i ;
j++)
i
f(i%j==0)
c++;
i
f(c==2)
Sy st
em. [Link]
ln(i
);
}
}
}
Nest edf or:
-
Whenoneormor et hanonef orloopsar enest
edi
nsi
deanotherf
orl
oop
theni ti
scal lednestedf orloop.
(40)Wr i
teapr ogram f orpyramidseries?
classSr eies1
{
publicstat i
cv oidmai n(Str
ingargs[]
)
{
i
nti ,
j
;
for(i
=1;i
<=5; i++)
{
for(j
=1;j
<=i ;
j++)
Sy st
em. [Link]
(j)
;
Sy st
em. [Link]
ln(“
”);
}
}
}
(41)Wr iteapr ogr am forpyramidseri
es?
classSer i
es2 1 2 3 4
{ 5
publicst ati
cv oidmai n(Str
ingargs[
])
1 2 3 4
{
i
nti ,
j
; 1 2 3
for(i
=5;i>=1;i--
) 1 2
{
1
for(j
=1;j<=i;
j++)
Sy st
em. [Link](j
);
Sy st
em. [Link]
n(“”)
;
}
}
}
(42)Wr iteapr ogr am forpyramidseri
es?
classSer i
es3
{
publicst ati
cv oidmai n(Str
ingargs[
])
{
*
i
nti ,
j
,k=1;
for(i
=1;i<=5;i++,k=k+2) * * *

{ * * * * *
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
.

7) Applethas five methods Appl


icat
ion has a si
ngle st
art
which will automati
call
y poi
ntwhichismainmet hod.
i
nvoked on occurance of
specif
icev
ent.

8) Usedf
orGUI Usedf
orCUI

9) Specif
ic cl ass cal
l
ed Nospeci
fi
ccl
assr
equi
red
Appletrequi
red.

10) Run- appl


etv
iewer Run-j
avaf
il
ename
fi
l
ename.
jav
a

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)
;

[Link] ound( color);


}
publ i
cst ati
cv oidmai n(Str
ing[]args)
{
ColorChooser Ex ampl ech=newCol orChooserExampl e()
;
[Link](400, 400);
[Link](true);
[Link] aultCloseOper ation(EXIT_ON_ CLOSE);
}
}
JSlider:-
TheJav aJSl i
dercl assi susedt ocr eatetheslider .Byusi ngJSl i
der,a
usercansel ectav al
uef r
om aspeci f
icrange.
Const ructor:-
JSlider()
,JSlider (
intorientation)
,JSlider(
intmin,intmax) ,JSl i
der(i
ntmi n,
i
ntmax ,
intv alue),JSlider(i
ntorientati
on,intmin,intmax, intvalue)
Met hod:-
publ i
c void set Minor Ti
ckSpacing(int n), publ ic void
setMaj orTickSpaci ng( i
ntn) ,publi
cv oidsetPaint
Ti cks(booleanb) ,publi
c
voidset PaintLabel s(booleanb) ,publicvoidsetPaintTracks(booleanb)
(130) Ex: -
i
mpor tjav ax .swi ng. *;
publ iccl assSl ider Ex ampl e1ext endsJFr ame
{
publ icSl ider Exampl e1()
{
JSl i
dersl ider=newJSl i
der (
[Link] ZONTAL, 0,
50, 25);
JPanel panel =newJPanel ();
panel .add( sli
der );
add( panel );
}
publ icst at i
cv oidmai n(Stri
ngs[ ])
{
SliderEx ampl e1f rame=newSl iderExampl e1();
frame. pack( );
frame. set Visible( true) ;
}
}
JSpi nner :-
Theobj ectofJSpi nnercl assi sasi nglel ineinputfiel
dt hatal
lowsthe
usert osel ectanumberoranobj ectv aluef rom anorderedsequence.
Const ruct or :
-
JSpi nner (),
JSpi nner (Spinner Model model )
Met hod: -
voidaddChangeLi stener (ChangeLi stenerl i
stener)
,ObjectgetVal
ue()
(131) Ex: -
i
mpor tjav ax .swi ng. *;
publ iccl assSpi nner Exampl e
{
publ icst at i
cv oidmai n(Stri
ng[]args)
{
JFr amef =newJFr ame( "SpinnerExampl e");
Spi nner Model value=newSpi nnerNumber Model(5,/
/ini
tialv
alue
0, //mi nimum v alue
10, // max imum v alue
1) ;//step
JSpi nnerspi nner=newJSpi nner(value);
spinner .
set Bounds( 100,100, 50,
30) ;
f.
add( spi nner );
f.
set Size( 300, 300) ;
[Link] out(nul l);
[Link](true) ;
}
}
JFi l
eChooser :-
Theobj ectofJFi leChoosercl assrepresentsadialogwindowfrom which
theusercansel ectf il
[Link]
sJComponentcl ass.
Const r
uct or:-
JFi l
eChooser (),
JFi l
eChooser (Fi
le current
Direct
ory),JFi
leChooser
(Str
ing
cur r
ent Direct oryPat h)
(132) Ex:-
i
mpor tjav ax .
swi ng.* ;
i
mpor tjav [Link] .
ev ent.*;
i
mpor tjav [Link].*;
publ i
ccl assFi leChooser Ex ampleextendsJFr amei mpl
ementsActionLis
tener
{
JMenuBarmb;
JMenuf il
e;
JMenuI tem open;
JTex tAr eata;
FileChooser Exampl e()
{
open=newJMenuI tem( "OpenFi l
e");
open. addAct ionLi stener (t
his);
fi
le=newJMenu( "File");
fi
[Link]( open) ;
mb=newJMenuBar ();
mb. setBounds( 0, 0,
800, 20);
mb. add( fi
le);
ta=newJTex tAr ea( 800,800) ;
[Link]( 0,20,800, 800) ;
add( mb) ;
add( ta);
}
publ i
cv oidact ionPer formed( Acti
onEvente)
{
i
f( e.
get Sour ce( )==open)
{
JFi l
eChooserf c=newJFi l
eChooser (
);
i
nti =[Link] alog(this);
i
f(i
==JFi l
eChooser .APPROVE_ OPTI ON)
{
Fil
ef =f c.
get Select edFi l
e();
Stri
ngf il
epat h=f .getPath();
try
{
Buffer edReaderbr =newBuf feredReader (
newFi l
eReader (
fil
epath));
Stri
ngs1=" ",s2=" ";
while((s1=br .readLi ne( )
)!=null)
{
s2+=s1+" \n";
}
ta.
set Tex t(s2) ;
br.
cl ose( );
}
catch( Except i
onex )
{
[Link] ackTr ace();
}
}
}
}
publ i
cst at icv oidmai n(St r
ing[]ar gs)
{
Fil
eChooser Exampl eom=newFi leChooserExample();
om. set Size( 500, 500) ;
om. set Lay out (nul l
);
om. set Visible( true);
om. set Def aul t
Cl oseOper ation(EXI T_ON_CLOSE) ;
}
}
JTool Bar :-
JTool Barcont ai neral lows us t o group othercomponent s,usually
buttonswi thi consi nar oworcol [Link] Barprovidesacomponent
whichi susef ul fordi splayingcommonl yusedact i
onsorcont rols.
Const ruct or :
-
JTool Bar (),JTool Bar(int or ientati
on), JTool Bar(Stri
ng name),
JTool Bar (St ri
ngname, intor i
ent ati
on)
Met hod: -voi daddSepar ator ()
,add( Acti
ona),get
UI()
,set
UI (
),
setOrientat
ion(
)
(133) Ex: -
i
mpor [Link] .Bor der Layout ;
i
mpor [Link] .Cont ainer;
i
mpor tjavax .swi ng. JBut ton;
i
mpor tjavax .swi ng. JComboBox;
i
mpor tjavax .swi ng. JFr ame;
i
mpor tjavax .swi ng. JScr oll
Pane;
i
mpor tjavax .swi ng. JTex t
Area;
i
mpor tjavax .swi ng. JTool Bar ;
publiccl assJTool Bar Exampl e
{
publicst aticv oidmai n( f
inal Stri
ngar gs[])
{
JFramemy fr
ame=newJFr ame( "JTool BarExampl e");
my frame. setDef aul tCloseOper ation( JFr ame. EXI T_ON_ CLOSE) ;
JTool Bart ool bar=newJTool Bar ();
toolbar .setRol lov er(true) ;
JBut tonbut ton=newJBut t
on( "File" );
toolbar .add( but ton) ;
toolbar .addSepar at or();
toolbar .add( newJBut ton("
Edi t"
));t ool bar .
add( newJComboBox( newSt r
i
ng[]{" Opt -1", "Opt -2", "Opt3","Opt -4"} ));
Cont ainercont ent Pane=my fr
ame. get Cont ent Pane( )
;
cont ent Pane. add( tool bar,Bor derLay out .NORTH) ;
JTex tAr eat ex tAr ea=newJText Ar ea( );
JScr ollPanemy pane=newJScr ollPane( textAr ea) ;
cont ent Pane. add( my pane, Bor derLay out .EAST) ;
my frame. setSi ze( 450, 250);
my frame. setVi sible( true);
}
}
JFrame: -
Thej av [Link] ng. JFr amecl assi sat y peofcont ai
nerwhi chi nheri
tsthe
j
av [Link] .
Frame cl [Link] ame wor ks l i
ke t he mai n wi ndow wher e
component sl ike l abel s,but tons,t extfields ar e added t o createa
GUI Unl ikeFr ame,JFr amehast heopt i
ont ohi deorcl oset hewindow
witht hehel pofset Def ault
Cl oseOper at i
on( i
nt )met hod.
Const ructor :
-
JFrame( ),
JFr ame( Gr aphi csConf i
gur ation gc) , JFr ame( Stri
ng t it
le)
,
JFrame( Stri
ngt itl
e, Gr aphicsConf igur at i
ongc)
Met hod: -
protect edv oi df rameI nit(
),voi
dsetCont entPane(Cont
ainercp)
(134)Ex: -
i
mpor tjav [Link] .
FlowLay out;
i
mpor tjav [Link] [Link] t
on;
i
mpor tjav [Link] [Link];
i
mpor tjav [Link] [Link] ;
i
mpor tjav [Link] [Link] ;
publiccl assJFr ameEx ampl e
{
publicst aticv oidmai n(Stri
ngs[ ]
)
{
JFramef rame=newJFr ame( "JFr
ameExampl e")
;
JPanel panel =newJPanel ();
[Link] Lay out (newFl owLay out(
));
JLabel label =newJLabel (
"JFrameByExampl e"
);
JBut t
onbut ton=newJBut ton();
[Link] Text ("
But ton");
[Link]( label )
;
[Link]( but ton);
frame. add( panel );
frame. set Siz e( 200, 300) ;
frame. set Locat i
onRel ativeTo(null
);
frame. set Def aultCloseOper ati
on(JFrame.EXIT_ON_CLOSE);
frame. set Visi ble( t
rue) ;
}
}
No. Jav
aAWT Jav
aSwi
ng

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.
*;
)

Lay outManager s:-


TheLay out Manager sar eusedt oar r
angecomponent sinapar ti
cul
ar
manner .Lay outManageri sani nterfacethatisimplement edbyal lthe
classesofl ayoutmanager s.
Ty pes: -
[Link] der Lay out
[Link] owLay out
[Link] dLay out
[Link] idLay out
[Link] Lay out
[Link] der Lay out:-
TheBor der Layouti susedt oar ranget hecomponent sinf iv
er egi
ons:
nor t
h,sout h,east ,westandcent [Link] egi
on(area)maycont ai
none
componentonl [Link]
hedef aultlayoutoff rameorwi ndow.
Const ant :
Bor der .
NORTH, Bor der
.SOURT, [Link],Border
.WEST, Border.
CENTE
R
Const ruct or:
Bor der Lay out ()
,Border
Lay out(
inthgap, intvgap)
(135) Wr iteapr ogr am forBorderLay out?
i
mpor tj av [Link] .
*;
publ i
ccl assBor der
{
Framef ;
Bor der()
{
f=newFr ame( )
;
Buttonb1=newBut ton("NORTH" )
;
Buttonb2=newBut ton("SOUTH" );
Buttonb3=newBut ton("EAST" )
;
Buttonb4=newBut ton("WEST" );
Buttonb5=newBut ton("CENTER" );
f.
add( b1, [Link]) ;
f.
add( b2, [Link]) ;
f.
add( b3, [Link]) ;
f.
add( b4, [Link]) ;
f.
add( b5, [Link]) ;
f.
setSi ze(300,300) ;
f.
setVi sible(t
rue);
}
publ i
cst ati
cv oidmai n(Stri
ng[]args)
{
newBor der();
}
}
[Link] owLay out :
-
TheFl owLay outi susedt oarranget hecomponent sinaline,oneaf
ter
anot her( inaf low).Itisthedef aultlay
outofappletorpanel.
Const ant :
Fl owLay out .
LEFT,FlowLay [Link]
GHT, Fl
[Link]
Const ructor s:
Fl owLay out (
),
FlowLay out(intali
gn),
FlowLayout
(i
ntalign,
inthgap,i
nt
v gap)
(136) Ex: -
i
mpor tj [Link] .
*;
publ i
ccl assMy Fl
owLay out
{
Framef ;
My Fl
owLay out()
{
f=newFr ame( )
;
Buttonb1=newBut t
on("1")
;
Buttonb2=newBut t
on("2")
;
Buttonb3=newBut t
on("3")
;
Buttonb4=newBut t
on("4")
;
Buttonb5=newBut t
on("5")
;
f.
add( b1) ;
f.
add(b2) ;
f.
add(b3) ;
f.
add(b4) ;
f.
add(b5) ;
f.
set Layout (
newFl owLay out(
FlowLayout .
LEFT) )
;
f.
set Layout (
newFl owLay out(
FlowLayout .
RIGHT) )
;
f.
setLay out (
newFl owLay out(
[Link]) );
f.
set Size(300,300) ;
f.
set Visibl
e(tr
ue) ;
}
publi
cst ati
cv oi
dmai n(Stri
ng[]args)
{
newMy FlowLay out ()
;
}
}
[Link] out :
-
TheCar dLay outcl assmanagest hecomponent sinsuchamannert hat
onlyonecomponenti sv i
sibl
eatat i
me.I ttr
eat seachcomponentasa
cardt hati swhyi ti sknownasCar dLayout.
Const ructor:
CardLay out()
,CardLay out(i
nthgap, i
ntvgap)
Met hod:
publicv oidnext (Cont ai
nerparent),
publ
icv oidpr ev
ious(Cont
ainer
parent ),
publicv oidf i
rst
(Cont ainerparent),
publ
icv oidlast(
Cont ai
ner
parent ),
publ i
cvoi dshow( Containerparent,Stri
ngname)
(137)Ex: -
i
mpor tj [Link].*;
i
mpor tj [Link] .
*;
i
mpor tj avax .
swing. *;
publi
ccl assCar dLay outExampleextendsJFr ameimpl ements
Acti
onLi stener
{
CardLayoutcar d;
JButtonb1,b2,b3;
Containerc;
CardLayoutEx ampl
e()
{

c=getContentPane()
;
card=newCar dLayout(
40,
30)
;
c.
setLayout(card)
;

b1=newJBut ton( "


Appl e");
b2=newJBut ton( "
Boy "
) ;
b3=newJBut ton( "
Cat ");
[Link] i
onLi st
ener (this);
[Link] i
onLi st
ener (this);
[Link] i
onLi st
ener (this);
[Link]( "a",b1) ;
[Link]( "b",b2);[Link]( "
c",
b3);
}
publicv oidact ionPer formed( Act ionEvente){
[Link] (c) ;
}
publicst aticv oidmai n( St ri
ng[]ar gs)
{
Car dLay out Ex ampl ecl =newCar dLayoutExample(
);
cl.
set Siz e(400, 400) ;
cl.
set Visi ble(true);
cl.
set Def aul tCloseOper ati
on( EXIT_ON_ CLOSE);
}
}
[Link]
dLay out :-
TheGr i
dLay outi susedt oar r
anget hecomponent sinrect
angulargr
id.
Onecomponenti sdi splay edi neachr ectangle.
Const ructor s:
Gr i
dLay out(),Gr idLay out(intr ows, intcolumns) ,
Gri
dLayout
(i
ntrows,i
nt
columns)
(138)Ex: -
i
mpor tj [Link] .*;
publi
ccl assMy GridLay out
{
Framef ;
My GridLay out ()
{
f=newFr ame( );
But tonb1=newBut ton("1"
);
But tonb2=newBut ton("2"
);
But tonb3=newBut ton("3"
);
But tonb4=newBut ton("4"
);
But tonb5=newBut ton("5"
);
But tonb6=newBut ton("6"
);
But tonb7=newBut ton("7"
);
But tonb8=newBut ton("8"
);
But tonb9=newBut ton("9"
);
f.
add( b1) ;
f.
add( b2) ;
f.
add( b3) ;
f.
add( b4) ;
f.
add( b5) ;
f.
add( b6) ;
f.
add( b7) ;
f.
add( b8) ;
f.
add( b9) ;
f.
set Lay out (newGr i
dLay out(
3, 3))
;
f.
set Size( 300, 300);
f.
set Visi ble(tr
ue) ;
}
publicst at i
cv oi
dmai n(Stri
ng[]args)
{
newMy Gr idLayout();
}
}
[Link] out :-
TheBoxLay outi susedt oar ranget hecomponent seit
herv er
ti
call
yor
horizont [Link] hispur pose,BoxLay outpr
ovidesfourconstant
s.
Const ant s:
Box Lay out .X_ AXIS,BoxLay out
.Y_ AXIS,
BoxLayout.
LINE_AXIS,
BoxLayout.
P
AGE_ AXI S
Const ruct or :
Box Lay out (Cont ainerc,intaxis)
(139)Ex: -
i
mpor tjav [Link] .*;
publ icclassBoxLay outEx ampl e1ext endsFr ame
{
But tonbut tons[ ]
;
publ icBoxLay outExampl e1( )
{
but t
ons=newBut ton[5]
;
for( i
nti =0; i<5;i++)
{
but t
ons[ i]=newBut t
on( "But ton"+( i +1) );
add( but t
ons[ i])
;
}
//set Lay out( newBox Lay out( thi
s,BoxLay out .
Y_ AXI S));
setSi ze(400, 400) ;
setVi sible(true) ;
}
publ icst aticv oidmai n(St ri
ngar gs[]
)
{
Box Lay out Ex ampl e1b=newBoxLay out Exampl e1( )
;
}
}
EventHandl ing: -
Changei nt hest ateofanobj ectisknownasev enti .
[Link] i
bes
thechangei nst ateofsour [Link] ent sar egener atedasr esultofuser
i
nt eract i
onwi ththegr aphi caluseri nterfacecomponent [Link] e,
cli
cki ngonabut t
on,mov ingt hemouse,ent eringachar actert hrough
key boar d,sel ect i
ngani tem f rom li
st, scrolli
ngt hepagear et heact i
v i
ti
es
thatcausesanev entt [Link] lev ent sar ecomeunderi mpor t
j
av [Link] .
ev ent .*;
EventCl asses: -
TheEv entcl assesr epresentt heev ent .TheEv entcl assisobsol eteand
i
sav ail
abl eonl yf orbackwar dscompat i
l
ibili
ty .Ithasbeenr eplacedby
theAWTEv entcl assandi tssubclasses.
EventCl ass Ev entLi stener s(i
nterface)
Act i
onEv ent Act i
onLi stener
MouseEv ent MouseLi st ener
Key Ev ent Key Listener
It
emEv ent It
emLi stener
Text Ev ent Text Listener
Adjust ment Ev ent Adj ustment Listener
WindowEv ent Wi ndowLi st ener
Component Ev ent Component Listener
Cont ainer Ev ent Cont ainerLi stener
FocusEv ent FocusLi stener
ActionEv ent :-
TheAct ionEv enti sgener atedwhenbut toni scl i
ckedort hei tem ofal i
st
i
sdoubl ecl i
cked.
Const ruct or:-
ActionEv ent ( jav a. [Link] ectsource,i nti d,jav [Link]. St
ringcommand) ,
ActionEv ent ( jav a. [Link] ectsource,i nti d,jav [Link],
i
ntmodi fier s)
Met hod: -
i
ntget Modi fier s( ),
longget When( ),
paramSt r
ing(),get Act i
onCommand( )
MouseEv ent :-
Thisev enti ndi cat esamouseact ionoccur redinacomponent .Thisl ow-
l
evelev enti sgener atedbyacomponentobj ectf orMouseEv entsand
Mousemot i
onev ent s.
Const ant :
MOUSE_ CLI CKED, MOUSE_ DRAGGED, MOUSE_ ENTERED, MOUSE_ EXITED,
MOUSE_ FI RST, MOUSE_ LAST,MOUSE_ PRESSED, MOUSE_ RELEASED, MO
USE_ MOVED
Const ruct or:
MouseEv ent (Componentsour ce,intid, longwhen, intmodi f
iers, i
ntx, i
nt
y,i
ntcl ickCount , bool eanpopupTr i
gger )
MouseEv ent (Componentsour ce,intid, longwhen, intmodi f
iers, i
ntx, i
nt
y,i
ntcl ickCount , bool eanpopupTr i
gger ,intbut ton)
MouseEv ent (Componentsour ce,intid, longwhen, intmodi f
iers, i
ntx, i
nt
y,i
ntxAbs, i
nty Abs, intclickCount,bool eanpopupTr i
gger, i
ntbut t
on)
Met hod:
intget But ton( ),intget Cli
ckCount (
),Pointget Point ()
,intget X()
,int
getY( ),St ri
ngpar amSt ri
ng( )
Key Ev ent :-
Onent er ingt hechar actertheKeyev enti sgener [Link] ear et hree
typesofkeyev ent swhi charerepresent edbyt hei nt egerconst ants.
Const ant :
KEY_ PRESSED, KEY_ RELEASED, KEY_ TYPED
Const ruct or :
KeyEv ent (Componentsour ce,i nti d,l ong when,i ntmodi fiers,i nt
keyCode) ,Key Ev ent(Componentsour ce,i nti d,longwhen,i ntmodi fi
er s,
i
ntkey Code,charkey Char ),Key Ev ent(Componentsour ce,i nti d,long
when, i
ntmodi f i
ers, i
ntkey Code, charkey Char ,intkey Locat ion)
Met hod:
char get Key Char (
) ,
int get Key Code( ),i
nt get Key Locat ion( ),
void
setKey Code( i
nt key Code) ,v oid set Key Char ( char key Char ), St ring
paramSt r
ing(),
bool eani sAct ionKey ()
It
emEv ent:-
Usedt of i
r eeventonanyev entt ochanget hest at eofev entonact ion.
Const ant :
SELECTED, DESELECTED, I
TEM_ FIRST, ITEM_ LAST, ITEM_ STATE_ CHANG
ED
Const ruct or:
It
emEv ent (It
emSel ectabl esour ce,intid, Objecti tem, i
ntst at echange)
Met hod:
getI
t em( ),getIt
emSel ect able( ),get StateChange( ),par amSt ring( )
TextEv ent :-
Theobj ectoft hiscl assr epr esent st het extev ent [Link] Ev enti s
gener atedwhenchar act eri sent er edi nt het extf ieldsort extar [Link]
TextEv enti nstancedoesnoti ncludet hechar act erscur rent lyint het ex t
componentt hatgener at edt heev entr atherwear epr ovidedwi t
hot her
met hodst or etri
ev ethati nfor mat i
on.
Const ant :
TEXT_ FIRST, TEXT_ LAST, TEXT_ VALUE_ CHANGED
Const ruct or:
TextEv ent (Objectsour ce, inti d)
Met hod:
Str
ingpar amSt ring()
Adjust ment Event :-
The Cl assAdj ust ment Ev entr epr esent s adj ustmentev entemi tted by
Adjust ableobj ect s.
Const ant :
ADJUSTMENT_ FIRST, ADJUSTMENT_ LAST, BLOCK_ INCREMENT, BLOCK
_DECREMENT, UNI T_INCREMENT, UNI T_ DECREMENT
Const ruct or:
Adjust ment Event (
Adj ust able sour ce, i nt i d, i nt t ype, i nt v al
ue) ,
Adjust ment Event (
Adj ust ablesour ce,i nti d,i ntt ype,i ntv al ue,bool ean
isAdj ust i
ng)
Wi ndowEv ent :-
Theobj ectoft hisclassr epr esent st hechangei nst ateofawi [Link]
low- l
ev elev enti sgener atedbyaWi ndow obj ectwheni tisopened,
closed, activ ated,deact i
vat ed, i
coni fied, ordei conifi
ed, orwhenf ocusi s
transf eredi nt ooroutoft heWi ndow.
Const ant:
WNI DOW_ ACTI VATED, WINDOW_ DEACTI VATED, WINDOW_ CLOSING, WI
NDOW_ CLOSED, WI NDOW_ ICONI FIED, WI NDOW_ DEICONI FIED,WINDOW_
OPENED, WNI DOW_ STATE_ CHANGED, WI NDOW_ GAI NED_ FOCUS, WIND
OW_ LOST_ FOCUS
Const ructor :
Wi ndowEv ent (Windowsour ce,i nti d),Wi ndowEv ent (Windowsour ce,int
id,i ntol dSt ate,i ntnewSt at e),Wi ndowEv ent(Window sour ce,intid,
Wi ndow opposi te),Wi ndowEv ent(Wi ndow sour ce,i nt i d,Wi ndow
opposi te,intol dStat e,intnewSt ate)
Met hod:
intget NewSt ate(),
intget Ol dSt ate(),
Wi ndowget Opposi t
eWi ndow(),
Wi ndowget Wi ndow( )
,Stri
ngpar amSt ring()
Component Ev ent :
-
The Cl assComponent Ev entr epr esent s t hat a component mov ed,
changedsi ze, orchangedv isibil
ity.
Const ant :
COMPONENT_ FIRST, COMPONENT_ HIDDEN, COMPONENT_ LAST,
COMPONENT_ MOVED, COMPONENT_ RESI ZED,COMPONENT_ SHOWN
Const ruct or:
Component Ev ent(Componentsour ce, intid)
Met hod:
Componentget Component (),Stringpar amSt ri
ng()
Cont ainer Ev ent :
-
The Cl assCont ainerEv entr epr esent s t hat a cont ainer '
s cont ents
changedbecauseacomponentwasaddedorr emov ed.
Const ant :
COMONENT_ ADDED, COMPONENT_ REMOVED, CONTAI NER_ LAST,
CONTAI NER_ FIRST
Const ruct or:
Cont ainer Ev ent(Componentsour ce, i
nti d,Componentchi ld)
Met hod:
Componentget Chi l
d(),Cont ainerget Cont ainer (),Stringpar amSt r
ing()
FocusEv ent :-
Thei nter faceFocusLi st eneri susedf orr eceiv i
ngkey boar df ocusev ents.
Thecl asst hatpr ocessf ocusev ent sneedst oi mpl ement sthisi nterface.
Met hod:
voidfocusGai ned( FocusEv ente) ,voidf ocusLost (FocusEv ente)
Ev entList ener s:-
TheEv entl istenerr epr esentt hei nter f
acesr esponsi blet ohandl eev ents.
Jav aprov i
desusv ariousEv entl istenercl assesbutwewi lldiscusst hose
whi char emor ef r
equent [Link] erymet hod ofan ev entl i
stener
met hod has a si ngle ar gumentas an obj ectwhi ch i s subcl ass of
Ev ent
Obj ectcl [Link] e,mouse ev entl i
st enermet hods wi l
l
accepti nstance of MouseEv ent ,wher e MouseEv entder ives f r
om
Ev ent
Obj ect.
Act i
onLi stener :-
The cl ass whi ch pr ocesses t he Act ionEv entshoul di mpl ementt his
i
nt erf
ace. Theobj ectoft hatcl assmustber egi steredwi thacomponent .
Theobj ectcanber egi stered usi ngt headdAct ionLi stener ()met hod.
Whent heact ionev entoccur s,t hatobj ect'sact ionPer formedmet hodi s
i
nv oked.
Met hod:
voidact ionPer formed( Act i
onEv ente)
Component List ener:
-
Thecl asswhi chpr ocessest heComponent Ev entshoul di mpl ementt his
i
nt erf
ace. Theobj ectoft hatcl assmustber egi steredwi thacomponent .
Theobj ectcanber egist eredusi ngt headdComponent Listener ()met hod.
Componentev entar er aisedf ori nfor mat iononl y .
Met hod:
voidcomponent Hidden( Component Evente) , voi d
component Mov ed(Component Ev ente) ,voi d
component Resi zed(Component Ev ente) ,v oi
d
component Shown( Component Ev ente)
ItemList ener :
-
The cl ass whi ch pr ocesses t he I t
emEv entshoul di mpl ementt his
i
nt erf
ace. Theobj ectoft hatcl assmustber egi steredwi thacomponent .
Theobj ectcanber egi steredusi ngt headdI temLi stener ( )met [Link]
the act ion ev entoccur s,t hatobj ect '
si temSt ateChanged met hod i s
i
nvoked.
Method:
voi
di temSt at eChanged( ItemEv ente)
KeyList ener :-
The cl ass whi ch pr ocesses t he Key Eventshoul di mpl ementt his
i
nterface. Theobj ectoft hatcl assmustber egi steredwi thacomponent .
Theobj ectcanber egisteredusi ngt headdKey Listener ()met hod.
Method:
voidkey Pressed( Key Evente) ,v oidkey Rel eased( Key Evente) ,voi
d
keyTy ped( Key Ev ente)
MouseLi st ener :-
Thecl asswhi chpr ocessest heMouseEv entshoul di mpl ementt his
int
erf ace. Theobj ectoft hatcl assmustber egi steredwi thacomponent .
Theobj ectcanber egister edusi ngt headdMouseLi stener (
)met hod.
Met hod:
voidmouseCl i
cked( MouseEv ente) ,v oidmouseEnt ered( MouseEv ente) ,
voidmouseExi ted( MouseEv ente) ,v oidmousePr essed( MouseEv ente) ,
voidmouseRel eased( MouseEv ente)
TextLi stener :-
The cl ass whi ch pr ocesses t he Text Ev entshoul di mpl ementt his
i
nterface. Theobj ectoft hatcl assmustber egi steredwi thacomponent .
Theobj ectcanber egisteredusi ngt headdText Listener ()met hod.
Method:
voi
dt ext Val ueChanged( Tex tEv ente)
Adjust ment Listener :
-
Theint er faceAdj ustment Listeneri susedf orr ecei vi
ngadj ustmentev ents.
Thecl asst hatpr ocessadj ust mentev ent sneedst oi mplement st his
i
nterface.
Method:
voi
dadj ust ment Val ueChanged( Adj ust ment Ev ente)
Contai ner List ener :
-
Thei nt er faceCont ainerList eneri susedf orr ecei vingcont ainerev ents.
The cl ass t hatpr ocess cont ainerev ent s needs t oi mpl ement st his
i
nterface.
voi
dcomponent Added( Cont ai
ner Ev ente) , v
oi d
component Remov ed(Cont ainer Ev ente)
FocusLi stener :-
Thei nt erfaceFocusLi steneri susedf orr ecei vingkey boar dfocusev ents.
Thecl asst hatpr ocessf ocusev entsneedst oi mpl ementsthisi
nter
face.
Met hod:
voidf ocusGai ned(FocusEv ente) ,
voi dfocusLost(FocusEv ente)
(140) wr iteapr ogr am foract i
onev ent?
i
mpor tj [Link] .
*;
i
mpor tj [Link] .
ev ent
.*;
classAEv entext endsFr ameimpl ement sActionListener
{
TextFi eldt ;
AEv ent ()
{
t=newText Field();
t.
set Bounds( 60,50,170,20) ;
Buttonb=newBut ton("clickme" );
[Link]( 100, 120,80, 30)
;
[Link] ionListener(this);
add( b);
add( t);
setSiz e(300,300) ;
setLay out (null
);
setVisi ble(tr
ue) ;
}
publicv oidact i
onPer formed( Act i
onEv ente)
{
t.
set Text ("Welcome" )
;
}
publicst ati
cv oidmai n( Stri
ngar gs[]
)
{
newAEv ent()
;
}
}
Wr i
teapr ogram f oract ionev ent.
i
mpor tj [Link] .
*;
i
mpor tj [Link] .
ev ent
.*;
i
mpor tj [Link].*;
/*
<appl etcode=" Q2"hei ght =200wi dth=300></ applet>
*/
publiccl assQ2ex tendsAppl etimpl ement sAct i
onListener
{
TextFieldt1=newTex t
Field( 10);
TextFieldt2=newTex t
Field( 10);
TextFieldt3=newTex t
Field( 10);
Label l
1=newLabel ("FIRSTNO=: ");
Label l
2=newLabel ("SECONDNO: "
);
Label l
3=newLabel ("SUM: ")
;
Buttonb=newBut ton("ADD" );
publicv oi
di ni
t()
{
[Link](Col or
.r ed);
add( l
1);
add( t1)
;
add( l
2);
add( t2)
;
add( l
3);
add( t3)
;
add( b);
[Link] i
onLi st
ener (
this) ;
}
publicv oi
dact i
onPer formed( Acti
onEvente)
{
i
f( [Link]()==b)
{
intn1=I nteger.
parseI nt(t1.
getText
())
;
intn2=I nteger.
parseI nt(t2.
getText
())
;
[Link] t
(""+( n1+n2) );
}
}
}
(141)Writeapr ogram f ormouseevent?
i
mpor [Link].*;
i
mpor [Link].*;
publi
cclassMouseLi stener
Exampl
e2extendsFr
amei
mpl
ement
sMouse
List
ener
{
MouseLi stenerExampl e2()
{
addMouseLi st
ener(this);
setSiz
e(300,300) ;
setLayout(null
);
setVisible(true);
}
publicv oidmouseCl i
cked( MouseEv ente)
{
Graphi csg=get Gr aphics( );
[Link] or([Link]) ;
[Link]
ll
Ov al([Link]( )
,[Link] Y(),
30, 30);
}
publicv oidmouseEnt ered( MouseEv ente){}
publicv oidmouseExi ted(MouseEv ente){}
publicv oidmousePr essed( MouseEv ente){}
publicv oidmouseRel eased( MouseEv ente){}
publicst aticv oidmai n(String[]args)
{
newMouseLi stener Exampl e2( );
}
}
(142)Wr i
teapr ogr am f orkeyev ent?
i
mpor tjav [Link].*;
i
mpor tjav [Link] .
ev ent.*;
i
mpor tjav [Link] .
*;
/*<appl etcode=” Test ”hei ght=200wi dth=250>
</applet >*/
publiccl assTestext endsAppl etimpl ementsKey
List
ener
{
Stri
ngmsg=” ”;
publicv oidi nit
()
{
addKey Listener (
this);
}
publicv oidkey Pressed( Key Eventke)
{
showSt atus( “
akeyi spr essed” );
}
publicv oidkey Released( Key Eventke)
{
showSt atus( “
akeyi sr eleased” );
}
publ i
cv oidkey Ty ped( Key Eventke)
{
msg=msg+ke. get Key Char ()
;
repaint ();
}
publ i
cv oidpai nt(Gr aphi csg)
{
[Link] ri
ng( msg, 20,40) ;
}
}
(143) Wr iteapr ogr am f orit
em ev ent?
i
mpor [Link] .*;
i
mpor [Link] .ev ent.*;
classChoi ceAct ionex tendsFr ame
{
Choi cec;
publ i
cChoi ceAct ion( )
{
setTit l
e("Choi cewi thI temListenerDemo" )
;
setSiz e(400, 400) ;
setLay out(newFl owLay out(
) )
;
setVi sible(tr
ue) ;
c=newChoi ce();
[Link]( "red");
[Link]( "green" );
[Link]( "blue");
add( c);
}
publ i
cv oiditemSt at eChanged( I
temEventi
e)
{
Stringar g=e. get Act i
onCommand( );
i
f( arg==" red" )
setBackgr ound( Col [Link]);
i
f( arg==" gr een")
setBackgr ound( Col [Link]);
i
f( arg==" blue" )
setBackgr ound( Col [Link]);
}
publ
i
cstaticvoi
dmain(
Str
ingar
gs[
])
{
newChoiceActi
on(
);
}
}
Fi
leI
/OHandl
ing(
CH-
15)

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()

Stepst oconnectdat abasewi thor acl e:


-
[Link] oadt hejarf i
leodbc14. jarf oror acle.
[Link] orei tinsidejava/ j
re/ l
ib/extf older .
[Link] hecl asspath, f
orex ampl e-
Set
classpat h=C:\oraclexe\ app\ oracle\ product \10.2.0\server\
jdbc\l
ib\ojdbc
14. j
ar .
(147) Wapt oconnectj av awi thor acl edat abase?
i
mpor [Link].*;
classOr acleCon
{
publ i
cst ati
cv oidmai n( Stri
ngar gs[ ]){
try
{
Class. forName( "or
acl e.j
dbc. dri
ver .
Or acleDr iver"
);
Connect i
oncon=Dr iverManager .get Connect i
on(" j
dbc:oracle:
thi
n:@local
host :1521: xe",
"system" ,"oracle")
;
Statementst mt =[Link] eStatement (“
insertintosi gnup………) ;
Resul tSetr s=st mt.
ex ecut eQuer y("select*f r
om emp" )
;
whi l
e( [Link]())
Sy stem. out .
printl
n([Link] I
nt(1)+"" +r [Link](2)+"" +r
[Link]
ing(3))
;
con. close( );
}
cat ch(Ex ceptione)
{
Sy stem. [Link]
n(e);
}
}
}
(148) Wapt oconnectj avawi thmy sqldatabase?
i
mpor [Link].*;
classMy sqlCon
{
publ icst ati
cv oidmai n( Stringar gs[ ])
{
try
{
Class. forName( "com. my sql .
jdbc. Driver")
;
Connect i
oncon=Dr i
verManager .get Connection(
"j
dbc: my sql:
//localhost:3306/ sonoo" ,
"root"
,"
");
Stat ementst mt =[Link] eSt atement ();
Resul tSetr s=st [Link] eQuer y("select*from emp" )
;
whi le([Link]())
Sy stem. [Link]
n([Link] (
1) +"" +[Link]
ing(2)
+"" +rs.
getStr
ing(
3))
;
con. close( )
;
}
cat ch(Ex ceptione)
{
Sy stem. [Link]
n(e);
}
}
}
(149) Wapt oconnectj avawi thmsaccessdat abasewi thoutdsn?
i
mpor [Link].*;
classTest
{
publ icst ati
cv oidmai n( Stringar [])
{
Tr y
{
Stringdat abase=" student .accdb" ;
Stringur l
="jdbc:odbc:Dr iver={Mi crosof tAccessDr iv
er( *
.mdb) }
;
DBQ="+dat abase+" ;Dr i
ver I
D=22; READONLY=t rue"
;
Class. forName( "sun.j
[Link] i
ver")
;
Connect i
onc=Dr iv
erManager .
getConnecti
on(url
);
Stat ementst =[Link] (
);
Resul tSetr s=st .
executeQuer y("
select*fr
om login"
);
whi le([Link]())
{
Sy stem. [Link]
n(rs.
getSt r
ing(1))
;
}
}
cat ch(Ex ceptionee)
{
Sy stem. [Link]
n(ee);
}
}
}
(150) Wapt oconnectj av awi t
hmsaccessdat abasewi
thdsn?
i
mpor [Link].*;
classTest
{
publ icst ati
cv oidmai n(Stri
ngar []
)
{
try
{
Stringur l
="jdbc:odbc:my dsn";
Class. forName( "sun.j
[Link] i
ver")
;
Connect i
onc=Dr iv
erManager .
getConnecti
on(url
);
Stat ementst =[Link] (
);
Resul tSetr s=st .
executeQuer y("
select*fr
om login"
);
whi le([Link]()){
Sy stem. [Link]
n(rs.
getSt r
ing(1))
;
}}
cat ch(Ex ceptionee)
{
Sy stem. [Link]
n(ee);
}}}
Col
lect
ionFr
amewor
kandUt
il
it
yCl
asses(
CH-
17)
Uti
li
tyCl asses: -
Uti
l
itycl assi sacl asst hatdef inesasetofmet hodst hatper form
common,of ten r e-used f [Link] il
itycl asses def i
ne these
common met hods underst atic [Link] es ofut ili
ty classes
i
ncludej [Link].
Col lectionswhi chpr ov idessev eralut i
li
tymet hodssuch
assortingonobj ectst hati mplementaCol lection( j
av [Link].
collecti
on) .
[Link] ractCol lection:-I mplement smostoft heCol l
ect i
oni nterf
ace.
[Link] ractList:-Ext endsAbst ractCol l
ect i
onandi mpl ement smostof
theLi stinterface.
[Link] ractSequent i
alLi st
:- Ext ends Abst ractList f or use by a
collecti
ont hatusessequent i
alr athert hanr andom accessofi ts
element s.
[Link] nkedLi st:- I mpl ement s a l i
nked l ist by ext endi ng
Abst ractSequent ialList.
[Link] ray Li
st :
-I mpl ement sady nami car raybyext endi ngAbst ractList.
[Link] ractSet :-Ex tendsAbst r
actCol lectionandi mpl ement smostof
theSeti nt erface.
[Link] :-Ex tendsAbst r
act Setf orusewi thahasht able.
[Link] nkedHashedSet :
- Ext ends HashSet t o al low i nser ti
on-order
i
ter at
ions.
[Link] eeSet :-Impl ement sasetst oredi nat r
[Link] endsAbst r
actSet .
10. Abst ract Map: -I mplement smostoft heMapi nterface.
11. HashMap: -Ex tendsAbst ractMapt ouseahasht abl e.
12. TreeMap: -Ex tendsAbst ractMapt ouseat r
ee.
13. WeakHashMap: -Ext endsAbst ractMapt ouseahasht able
withweakkey s.
14. LinkedHashMap: -Ext endsHashMapt oal lowi nsertion- order
i
terations.
15. Ident it
yHashMap: -Ext endsAbst r
act Mapandusesr ef erence
equal i
tywhencompar i
ngdocument s.
16. Vect or :
-Thi si mpl ement sady nami car ray.I tissi mi l
art o
ArrayList ,butwi thsomedi ffer ences.
17. St ack: -St acki sasubcl assofVect ort hati mpl ement sa
standar dl ast -in,f i
rst-outst ack.
18. Di ctionar y:-Dict i
onar yi sanabst ractcl asst hatr epr esent sa
key/val uest orager eposi toryandoper atesmuchl i
keMap.
19. Hasht abl e:-Hasht abl ewaspar toft heor i
[Link] ilandi s
aconcr et ei mpl ement at i
onofaDi ctionary .
20. Pr oper t
ies: -Pr oper t
iesi sasubcl assofHasht able.I tisused
tomai nt ainl i
st sofv aluesi nwhi chthekeyi saSt ringandt hev alue
isalsoaSt ri
ng.
21. Bit set :
-ABi tSetcl asscr eatesaspeci alt y
peofar rayt hat
holdsbi tv [Link] sar raycani ncreasei nsi zeasneeded.
Col
lectionI nter f
aces: -
[Link] i
on: -Thi senabl esy out owor kwi thgr oupsofobj ect s;itis
atthet opoft hecol l
ect ionshi er archy .
[Link]:
-Thi sext endsCol lect ionandani nst anceofLi stst oresan
orderedcol lect i
onofel ement s.
[Link]:-Thi sext endsCol l
ect iont ohandl eset s,whi chmustcont ain
uniqueel ement s.
[Link] :-Thi sext endsSett ohandl esor tedset s.
[Link]: -Thi smapsuni quekey st ov al
ues.
[Link]. Ent r y:-Thi smapsuni quekey st oval ues.
[Link]: -Thi sext endsMapsot hatt hekey sar emai nt ainedi n
anascendi ngor der.
[Link] ation:-Thi si sl egacyi nterfacedef inest hemet hodsby
whichy oucanenumer ate( obt ainoneatat ime)t heel ement sina
coll
ect ionofobj [Link] sl egacyi nterfacehasbeensuper ceded
byIterat or.
Exampleofcol l
ect ionut il
itycl assusi ngAr r
ay List:-
i
[Link] il
.*;
cl
assTest1
{
publ icst at icv oidmai n(Stri
ngar gs[]
)
{
Arr ayList <St ri
ng>l ist=newAr rayList<Str
ing>()
;
l
ist .
add( "appl e");
l
ist .
add( "banana" );
l
ist .
add( "appl e");
l
ist .
add( "papay a");
It
er atori tr=[Link]
erator();
whi le(itr.
hasNex t())
{
Sy stem. out .printl
n(itr
.next(
));
}
}
}
Exampl eofcol lectionutili
tyclassusi ngLinkedLi
st:
-
i
mpor tjav a. uti
l.*;
publ iccl assTest 2
{
publ icst at icv oidmai n(Stri
ngar gs[]
)
{
LinkedLi st <String>al =newLi nkedList<Stri
ng>()
;
[Link]( "Rav i")
;
[Link]( "Vi j
ay ");
[Link]( "Rav i")
;
[Link]( "Aj ay ")
;
It
er ator <St ring>i tr
=al.i
terator
();
whi le(itr.
hasNex t())
{
Sy stem. out .printl
n(itr
.next(
));
}
}
}
Exampl eofcol lectionutili
tyclassusi ngVector:
-
i
mpor tjav a. uti
l.*;
publ iccl assTest 2
{
publ icst at icv oidmai n(Stri
ngar gs[]
)
{
Vect or <St ring>v =newVect or
<String>();
[Link]( "Rav i");
[Link]( "Vi j
ay " )
;
[Link]( "Rav i");
[Link]( "Aj ay ");
It
erator<St r
ing>i t
r=v.
iterator()
;
whi l
e(it
[Link] t()
)
{
System. [Link]
n(i
tr.
nex t(
));
}
}
}
Exampl eofcol lecti
onut ili
tyclassusingSt
ack:
-
i
mpor [Link]
l.*;
publicclassTest 2
{
publicst ati
cv oidmai n(Stri
ngar gs[
])
{
Stack<St ri
ng>al =newSt ack<Stri
ng>()
;
al.
add( "
Rav i")
;
al.
add( "
Vi j
ay");
al.
add( "
Rav i")
;
al.
add( "
Aj ay")
;
It
erator<St r
ing>i t
r=al.
iterator(
);
whi l
e(it
[Link] t()
)
{
System. [Link]
n(i
tr.
nex t(
));
}
}
}
Exampl eofcol lecti
onut ili
tyclassusingPr
ior
it
yQueue:-
i
mpor [Link]
l.*;
publicclassTest 2
{
publicst ati
cv oidmai n(Stri
ngar gs[
])
{
Priori
tyQueue<St ri
ng>al =newPr ior
it
yQueue<Str
ing>(
);
al.
add( "
Rav i")
;
al.
add( "
Vi j
ay");
al.
add( "
Ram" );
al.
add( "
Aj ay")
;
System. [Link]
n(al
.element ()
);
System. [Link]
n(al
.peek( ))
;
It
erator<St r
ing>i t
r=al.
iterator(
);
whi l
e(it
[Link] t()
)
{
System. [Link]
n(i
tr.
nex t(
));
}
al.
remov e()
;
al.
pool (
);
It
erator<St r
ing>i t
r1=al.i
terator(
);
while(it
[Link] t()
)
{
System. [Link]
n(i
[Link]()
);
}
}
}
Exampl eofcol lecti
onut ili
tyclassusingTreeSet
:-
i
mpor [Link]
l.*;
publicclassTest 2
{
publicst ati
cv oidmai n(Stri
ngar gs[
])
{
TreeSet <Stri
ng>al =newTr eeSet<Str
ing>(
);
al.
add( "
Rav i")
;
al.
add( "
Vi j
ay");
al.
add( "
Rav i")
;
al.
add( "
Aj ay")
;
It
erator<St r
ing>i t
r=al.i
terator(
);
while(it
[Link] t()
)
{
System. [Link]
n(i
tr.
nex t(
));
}
}
}
Net
wor
king(
CH-
18)
Thet er
m net workpr ogrammi ngreferstowr i
ti
ngpr ogramst hatexecute
across mul t
iple dev i
ces (comput ers),in which t he devices are al
l
connectedt oeachot herusi
nganet wor [Link] wor ki
ngisaconcept
ofconnect i
ngt woormor ecomput ingdev i
cest ogethersot hatwecan
sharer esour [Link] ogrammi ng providesf aci
l
ityto share
databet weendi f
ferentcomput i
ngdev i
ces.
Adv ant
agesofnet wor ki
ng:-
[Link]
ngofr esources
[Link]
z esof t
war emanagement
Javanet wor kingt erminol
ogies:-
1.I PAddr ess
[Link] ot ocol
[Link] tNumber
[Link] ess
[Link] i
on- or i
ent edandconnect i
on-lesspr otocol
[Link]
1.I
PAddr ess:-
IPaddr essi sauni quenumberassi gnedt oanodeofanet worke. g.
192.168. 0.1.I tiscomposedofoct etst hatrangef r
om 0t o255.
Iti
sal ogi cal addr esst hatcanbechanged.
[Link] :
-
Apr otocoli sasetofr ulesbasi call
yt hati sf oll
owedf orcommuni cati
on.
Forexampl e:
o T CP
o F TP
o T elnet
o S MTP
o P OPet c.
[Link] :
-
Thepor tnumberi susedt ouni quelyi dent i
fydi f
ferentapplicati
ons.I t
actsasacommuni cationendpoi ntbet weenappl icati
ons.
Thepor tnumberi sassoci atedwi tht heI Paddr essf orcommuni cat
ion
betweent woappl i
cat ions.
[Link] ess:-
MAC ( Medi a AccessCont r ol)Addr essi sa uni quei dent
if
ierofNI C
(Networ kI nterfaceCont rol ler).Anet worknodecanhav emul ti
pleNI C
buteachwi thuni queMAC.
[Link] i
on- orient edandconnect i
on- lesspr ot ocol:-
In connect ion-orient ed pr ot ocol,acknowl edgementi s sentby t he
[Link] tisr eli
abl ebutsl [Link] eofconnect ion-ori
ented
protocol isTCP.
But,inconnect ion- lesspr ot ocol,acknowl edgementi snotsentbyt he
[Link] tisnotr eliabl ebutf ast .Theexampl eofconnect ion-l
ess
protocol isUDP.
[Link] :-
Asocketi sanendpoi ntbet weent wowaycommuni cation.
Socketcl ass: -
Asocketi ssi mpl yanendpoi ntf orcommuni cationsbet weenthe
machi [Link] asscanbeusedt ocr eateasocket .
Met hods: -
[Link] i
cI nput Stream get Input Str
eam( )
[Link] i
cOut putSt ream get Out putStream( )
[Link] i
csy nchroni zedv oi dcl ose()
ServerSocketcl ass: -
TheSer verSocketcl asscanbeusedt ocr eateaser [Link]
objecti susedt oest abli
shcommuni cationwi ththecl i
ents.
Met hods: -
[Link] icSocketaccept ()
[Link] icsy nchr oni zedv oi
dcl ose()
(151) Wapt osendandr eceiv einfor
mat i
onf rom cl i
enttoserv er?
Forser ver:
-
i
mpor [Link].* ;
i
mpor [Link] .
*;
publiccl assMy Ser ver
{
publicst ati
cv oidmai n(Str
ing[]args)
{
try
{
Server Socketss=newSer verSocket(6666) ;
Sockets=ss. accept ();
DataInput Str eam di s=newDat aInputStream( [Link]
eam( ));
Stri
ng st r
=(St ring)di s.r
eadUTF( )
;
System. out .println("message=" +str
);
[Link]( )
;
}
catch( Except ione)
{
System. out .println(e) ;
}
}
}
Forcl ient:-
(152) Ex:-
i
mpor [Link].* ;
i
mpor [Link] .
*;
publiccl assMy Client
{
publicst ati
cv oidmai n(Str
ing[]args)
{
try
{
Sockets=newSocket ("
localhost",
6666) ;
DataOut putSt ream dout =newDat aOut putStr
eam( [Link]
St r
eam()
);
[Link]
teUTF("Hell
oSer
ver
");
[Link]
ush()
;
[Link]
ose();
s.
close();
}
catch(Excepti
one)
{
[Link]
intl
n(e)
;
}
}
}
Not e:-opent wocommandpr omptandr unbot htheprogr am atat i
met o
viewt heo/ p.
URLcl ass: -
TheJav aURLcl assr epresent [Link] sanacr ony mf orUnifor
m
Resour ceLocat [Link] ntst oar esour
ceont heWor ldWi [Link]
cont ainsmanyi nformat i
on:
[Link] otocol: I
nt hiscase, httpi
st heprotocol.
[Link] vernameorI PAddr ess:Inthi
scase, www. javatpoint
.com isthe
ser vername.
[Link] t Number : I
t i s an opt ional at tri
bute. I f we wr i
te
ht tp//ww. j
av atpoint .
com: 80/sonoojai
swal /,80ist hepor tnumber.
Ifpor tnumberi snotment i
onedint heURL, itr
eturns-1.
[Link] leNameordi rect oryname: I
nthiscase, i
ndex.j
spi sthef i
l
ename.
Met hods: -
[Link] icSt ri
ngget Prot ocol()
[Link] icSt ri
ngget Host ()
[Link] icSt ri
ngget Por t()
[Link] icSt ri
ngget Fil
e( )
[Link] icURLConnect ionopenConnect ion()
(153) Wapf orj avaURLcl ass?
i
mpor tj ava.i
o.*;
i
mpor tj [Link].*;
publ i
ccl assURLDemo
{
publ i
cst ati
cv oidmai n(Stri
ng[ ]ar
gs)
{
try
{
URLur l
=newURL( "[Link] j
av atpoint.
com/ j
ava-tutori
al"
);
System. [Link]("Prot ocol:"+ur l
.getProtocol());
System. [Link]("HostName: "+ur l.
getHost());
System. [Link]("Por tNumber :"+url.
getPor t
());
System. [Link]("FileName: "+ur l
.getFi
le()
);
}
catch(Ex ceptione)
{
System. [Link](e);
}
}
}
InetAddr esscl ass: -
Jav a I netAddr esscl ass r epresent s an I P addr ess. The
j
av [Link].I
netAddr esscl asspr ov idesmet hodst ogett heI Pofanyhost
namef orexampl ewww. j
avatpoi [Link], [Link].
com,
www. f
acebook. com et c.
Met hods: -
1. publ ic st atic I netAddr ess get By Name( Stri
ng host ) throws
UnknownHost Ex cept ion
2. public static Inet Addr ess getLocalHost() t
hrows
UnknownHost Ex cept ion
[Link] i
cSt ri
ngget Host Name( )
[Link] i
cSt ri
ngget Host Addr ess( )
(154) Wapf orI net Addr esscl ass?
i
mpor tjava.i
o.* ;
i
mpor [Link].*;
publicclassI net Demo
{
publicst ati
cv oidmai n( Stri
ng[]ar gs)
{
try
{
InetAddr essip=I net Addr [Link] ByName( "www. javatpoint.
com");
System. [Link]("HostName: "+[Link] Name( ));
System. [Link]("IPAddr ess: "+[Link] ess());
}
catch(Ex ceptione)
{
System. [Link](e);
}
}
}
Dat agramSocketcl ass: -
Jav a Dat agr amSocketcl ass represents a connect ion-l
ess socketf or
sendi ng and r eceiv i
ng dat agram packet s.A dat agram i sbasi call
yan
i
nf ormat ionbutt herei snoguar anteeofi t
scont ent ,
ar r
ivalorarrivalti
me.
Const r
uct ors:-
[Link] agramSocket ()thr owsSocket Eeption
[Link] agramSocket (i
ntpor t
)throwsSocket Eeption
[Link] agramSocket (i
ntpor t
,InetAddressaddr ess)t hrowsSocket Eept i
on
Dat agramPacketcl ass: -
Jav aDat agramPacketi samessaget hatcanbesentorr eceived.I fyou
sendmul ti
plepacket ,itmayar r
ivei nanyor [Link] t
ionall
y ,packet
deliveryisnotguar ant eed.
Const r
uct ors:-
[Link] agr amPacket (by te[]barr,i
ntlength)
[Link] agr amPacket (by te[]barr,i
ntlength,I
net Addressaddr ess,intport)
(155) Wapf orsendi ngpacket s?
i
mpor tjav [Link].*
;
publ i
ccl assDSender
{
publ i
cst aticv oidmai n(Stri
ng[]args)throwsExcept ion
{
Dat agramSocketds=newDat agramSocket ();
Stringst r=" Wel comej ava";
InetAddr essi p=I netAddr [Link]( "[Link]");
Dat agramPacketdp=newDat agramPacket (str.
getBy tes(
),str.
lengt h(
),i
p,
3000) ;
[Link]( dp) ;
[Link]( );
}
}
(156) Wapf orr eceiv i
ngpacket s?
i
mpor tjav [Link].*
;
publ i
ccl assDRecei ver
{
publ i
cst aticv oidmai n(Stri
ng[]args)throwsExcept ion
{
Dat agramSocketds=newDat agramSocket (3000);
byte[]buf=newby te[1024] ;
Datagr amPacketdp=newDat agramPacket(
buf,1024);
[Link](
dp);
Str
ingst r=newSt ri
ng(dp.
get
Data()
,0,
[Link]
h())
;
System. out.
pri
ntl
n(st
r);
[Link]();
}
}
I
nter
viewQuest
ions
[Link] ouknowaboutJav a?
Jav ai sahi gh- l
ev elpr ogr ammi ngl anguageor i
gi nallydev elopedbySun
Mi crosy st emsandr eleasedi [Link] arunsonav ar i
etyofpl at f
orms,
suchasWi ndows, MacOS, andt hev ar i
ousv ersionsofUNI X.
[Link] et hesuppor t edpl atfor msbyJav aPr ogr ammi ngLanguage?
Jav ar unsonav ar ietyofpl at for ms, suchasWi ndows, MacOS, andt he
variousv er sionsofUNI X/Linuxl ikeHP- Unix,SunSol ari
s,RedhatLi nux,
Ubunt u, Cent OS, etc.
[Link] ivef eat uresofJav a?
Somef eat ur esincl udeObj ectOr ient ed,Pl at
for mI ndependent ,Robust ,
Interpr eted, Mul t
i-threaded
[Link] sJav aAr chi tect ural Neut ral?
It’
scompi lergener at esanar chi tect ur e-neut r
alobj ectf i
lef ormat ,whi ch
makest hecompi ledcodet obeexecut ableonmanypr ocessor s,wi th
thepr esenceofJav ar untimesy st em.
[Link] aenabl edHi ghPer for mance?
Jav ausesJust -
In-Ti mecompi lert oenabl ehi ghper [Link] -I
n-
Time compi l
eri sa pr ogram t hatt ur nsJav a by t
ecode,whi ch isa
progr am t hatcont ains i nst ruct ions t hatmustbe i nterpreted i nto
instruct ionst hatcanbesentdi rect l
yt ot hepr ocessor .
[Link] ai sconsi der eddy nami c?
Itisdesi gnedt oadaptt oanev olv i
ngenv i
ronment .Jav apr ogramscan
car ryex tensi v
eamountofr un- ti
mei nf or
mat iont hatcanbeusedt o
verifyandr esol veaccessest oobj ect sonr un-time.
[Link] sJav aVi rtualMachi neandhow i ti sconsi deredi ncont extof
Jav a’
spl at for mindependentf eat ure?
When Jav ai s compi led,i ti s notcompi l
ed i nto platfor m speci fi
c
machi ne,r atheri nt opl at f
ormi ndependentby [Link] sby t
ecodei s
distribut edov ert hewebandi nt erpr et edbyv irtualMachi ne( JVM)on
whi chev erpl at f
ormi ti sbei ngr un.
[Link] woJav aIDE’ s?
Net beans, Ecl ipse, etc.
[Link] akey wor ds( unl ikeC, C++key wor ds) ?
SomeJav akey wor dsar ei mpor t, super , f
inal l
y, etc.
[Link] oumeanbyObj ect ?
Obj ecti sar unt imeent i
tyandi t’sst atei sst or edi nf ieldsandbehav ioris
shownv i
amet [Link] hodsoper ateonanobj ect '
si nter nalstat eand
ser veast hepr imar ymechani sm f orobj ect -
t o-objectcommuni cation.
[Link] i
necl ass?
Acl assi sabl uepr intf rom whi chi ndi vidualobj ect sar ecr eat [Link] ass
cancont ainf ieldsandmet hodst odescr i
bet hebehav iorofanobj ect .
[Link] ndofv ariabl esacl asscanconsi stof ?
Acl assconsi stofLocal v ar i
abl e, inst ancev ar iablesandcl assv ariables.
[Link] saLocal Var iabl e?
Var iablesdef inedi nsi demet hods,const ruct orsorbl ocksar ecal led
localv ariabl [Link] ar i
abl ewi llbedecl aredandi nitializedwi thint he
met hodandi twi l
l bedest roy edwhent hemet hodhascompl eted.
[Link] saI nst anceVar iabl e?
Instancev ar iabl esar ev ariabl eswi thinacl assbutout sideanymet hod.
Thesev ariabl esar ei nst ant iat edwhent hecl assi sl oaded.
[Link] saCl assVar iabl e?
Thesear ev ar iabl esdecl ar edwi t
hi nacl ass,out sideanymet hod,wi th
thest ati
ckey wor d.
[Link] sSi ngl et oncl ass?
Singl etoncl asscont rolobj ectcr eat i
on,l i
mi ti
ngt henumbert oonebut
allowi ngt hef lex i
bilityt ocr eat emor eobj ect sift hesi tuat i
onchanges.
[Link] oumeanbyConst ruct or?
Const ructorget si nv okedwhenanewobj ecti scr eat [Link] eryclasshas
aconst r
uct or .I fwedonotexpl icitlywr i
teaconst ruct orf oracl asst he
javacompi l
erbui ldsadef aul tconst ruct orf ort hatcl ass.
[Link] stthet hr eest epsf orcr eat i
nganObj ectf oracl ass?
AnObj ecti sf irstdecl ar ed, theni nst ant iatedandt heni tisi niti
ali
zed.
[Link] st hedef aul tv al ueofby tedat atypei nJav a?
Def aul tvalueofby t edat at ypei s0.
[Link] st hedef aul tv al ueoff loatanddoubl edat at ypei nJav a?
Def aul tval ueoff loatanddoubl edat atypei ndi fferentascompar edt o
C/ C++.Forf l
oati ts0. 0fandf ordoubl ei t’s0. 0d
[Link] tedat at ypei sused?
Thi sdat at ypei susedt osav espacei nl argear ray s,mai nl yinpl aceof
integer s,si nceaby tei sf ourt imessmal lert hanani nt .
[Link] sast at icv ariabl e?
Classv ar i
abl esal soknownasst at i
cv ariablesar edecl aredwi t
ht he
statickey wor di nacl ass, butout si deamet hod, const ructororabl ock.
[Link] oumeanbyAccessModi fier?
Jav a pr ov i
des access modi fier st o setaccess l ev el
sf orcl asses,
variabl es, met hodsandconst r uct or [Link] aul t
accessi bilitywhennoaccessi bilitymodi fi
eri sspeci fied.
[Link] spr ot ectedaccessmodi fi
er ?
Variabl es,met hodsandconst r uct or swhi char edecl aredpr otect edina
super cl asscanbeaccessedonl ybyt hesubcl assesi not herpackageor
anycl asswi thint hepackageoft hepr otect edmember s'class.
[Link] oumeanbysy nchr oni zedNonAccessModi fier?
Jav apr ov idest hesemodi fiersf orpr ov idingf unctional i
tiesot hert han
AccessModi fiers,sy nchr onizedusedt oi ndi catethatamet hodcanbe
accessedbyonl yonet hreadatat ime.
[Link] di ng t o Jav a Oper at or pr ecedence, whi ch oper ator i s
consi der edt obewi thhi ghestpr ecedence?
Post fixoper ator si.e()[ ].isatt hehi ghestpr ecedence.
Variabl esusedi naswi t
chst atementcanbeusedwi thwhi chdat atypes?
Variabl esusedi naswi tchst at ementcanonl ybeast ri
ng,enum,by te,
shor t,int, orchar .
[Link] seI nt()met hodcanbeused?
Thismet hodi susedt ogett hepr i
mi ti
v edat at ypeofacer t
ainSt ri
ng.
[Link] sSt ringcl assconsi der edi mmut abl e?
TheSt ri
ngcl assi si mmut abl e,sot hatoncei tiscreat edaSt r
ingobj ect
[Link] nceSt r i
ngi si mmut ablei tcansaf elybeshar ed
between many t hreads , whi ch i s consi dered v eryi mpor tant f or
mul tithreadedpr ogrammi ng.
[Link] sSt ringBuf fercal ledmut able?
TheSt ri
ngcl assi sconsi deredasi mmut abl e,sot hatoncei tiscr eateda
Stri
ngobj ectcannotbechanged.I ft her ei sanecessi tyt omakeal otof
modi fi
cat ionst oSt r
ingsofchar act erst henSt r
ingBuf fershoul dbeused.
[Link] st hedi f
ferencebet weenSt ringBuf ferandSt ri
ngBui l
dercl ass?
Use St ringBui lder whenev er possi ble because i ti sf ast er t han
Stri
ngBuf [Link] ,ift hreadsaf etyi snecessar ythenuseSt ringBuf fer
object s.
[Link] ch package i s used f or pat ter n mat chi ng wi th r egul ar
expressi ons?
[Link] i
[Link] susedf ort hispur pose.
j
ava. util.
regexconsi stsofwhi chcl asses?
[Link] i
[Link] stsoft hreecl asses−Pat terncl ass,Mat chercl ass
andPat ter nSy ntax Except ioncl ass.
[Link] sf inal i
ze( )met hod?
Iti spossi bl et odef ineamet hodt hatwi llbecal l
edj ustbef orean
obj ect'sf inal dest ruct i
onbyt hegar bagecol l
ect [Link] hodi scal l
ed
finalize() , andi tcanbeusedt oensur ethatanobj ectter mi nat escl eanly.
[Link] sanExcept ion?
Anexcept ioni sapr obl em t hatar isesdur ingt heexecut ionofapr ogram.
Ex cept ions ar e caughtby handl ers posi t
ioned al ong t he t hr
ead's
met hodi nv ocat i
onst ack.
[Link] oumeanbyCheckedExcept ions?
Itisanex cept iont hati st ypicall
yauserer rororapr obl em t hatcannot
bef oreseenbyt hepr ogr ammer .Forexampl e,i faf il
ei st obeopened,
butt hef ilecannotbef ound,anexcept ionoccur [Link] ions
cannotsi mpl ybei gnor edatt het imeofcompi lation.
[Link] ai nRunt i
meExcept ions?
Itisanex cept iont hatoccur st hatpr obabl ycoul dhav ebeenav oidedby
the pr ogr ammer . As opposed t o checked except ions, r unti
me
except i
onsar ei gnor edatt het imeofcompl i
at i
on.
[Link] char et het wosubcl assesunderExcept ioncl ass?
TheEx cept ioncl asshast womai nsubclasses:I OExcept ioncl assand
Runt i
meEx cept ionCl ass.
[Link] hr owskey wor di sused?
Ifamet hoddoesnothandl eacheckedexcept ion,t hemet hodmust
decl arei tusi ngt het hr owskey wor [Link] hr owskey wor dappear satt he
endofamet hod' ssi gnat ure.
[Link] hr owkey wor di sused?
Anexcept ioncanbet hr own,ei t
heranewl yi nst antiatedoneoran
ex cept i
ont haty ouj ustcaught ,byusi ngt hr owkey word.
[Link] i
nal lyusedunderExcept ionHandl ing?
Thef inal l
ykey wor di susedt ocr eateabl ockofcodet hatf ollowsat r
y
block.A f inal lybl ockofcodeal way sexecut es,whet herornotan
except i
onhasoccur red.
[Link] hings shoul d be kepti n mi nd whi le creat ing y ourown
except i
onsi nJav a?
Whi l
ecr eat ingy ourownex ception−
 Al lex cept ionsmustbeachi ldofThr owabl e.
 I fy ouwantt owr iteacheckedexcept i
ont hati saut omat i
call
y
enf or cedbyt heHandl eorDecl ar
eRul e,y ouneedt oext endt he
Ex cept ioncl ass.
 Youwantt owr itear unt imeexcept ion,y ouneedt oext endt he
Runt imeEx cept i
oncl ass.
[Link] ineI nher i
tance?
Itist hepr ocesswher eoneobj ectacqui rest hepr oper tiesofanot her.
Wi tht heuseofi nher itancet hei nformat i
oni smademanageabl ei na
hierar chical order.
[Link] wor di sused?
Ift hemet hodov er ri
desoneofi t
ssuper cl ass'smet hods,ov err
idden
met hodcanbei nv okedt hrought heuseoft hekey wor dsuper .Itcanbe
alsousedt or efert oahi ddenf ield.
[Link] sPol ymor phi sm?
Pol ymor phi sm ist heabi li
tyofanobj ectt ot akeonmanyf [Link]
mostcommonuseofpol ymor phism i nOOPoccur swhenapar entcl ass
refer encei susedt or ef ertoachi ldclassobj ect .
[Link] sAbst ract ion?
Itref erst ot heabi li
tyt omakeacl assabst racti nOOP.I thel pst or educe
thecompl exi t
yandal soi mpr ov est hemai ntai nabilit
yoft hesy st em.
[Link] sAbst ractcl ass?
These cl asses cannot be i nstant i
ated and ar e ei t
her par tiall
y
impl ement edornotatal l i
mpl ement [Link] scl asscont ainsoneormor e
abst ractmet hodswhi char esi mpl ymet hoddecl arati
onswi thoutabody .
[Link] ractmet hodsar eused?
Ify ouwantacl asst ocont ainapar ticularmet hodbuty ouwantt he
act ual impl ement at ionoft hatmet hodt obedet erminedbychi ldcl asses,
youcandecl aret hemet hodi nt hepar entcl assasabst r
act .
[Link] sEncapsul ation?
Itist het echni queofmaki ngt hef i
eldsi nacl asspr ivateandpr oviding
accesst ot hef i
el dsv iapubl icmet hods.I faf ieldisdecl aredpr i
vate,it
cannotbeaccessedbyany oneout sidet hecl ass,t herebyhi dingt he
fiel
dswi thint hecl [Link] efor eencapsul ationi sal sor eferredt oas
dat ahi ding.
[Link] st hepr imar ybenef itofEncapsul at ion?
The mai n benef itof encapsul ati
on i st he abi li
tyt o modi fy our
impl ement edcodewi thoutbr eaki ngt hecodeofot herswhouseour
[Link] tht his Encapsul ati
on gi ves mai ntainability,f l
exi bili
ty and
ex t
ensi bil
ityt oourcode.
[Link] sanI nter face?
Ani nter f
acei sacol l
ect ionofabst r
actmet [Link] assi mpl ement san
inter face, therebyi nher itingt heabst ractmet hodsoft hei nterface.
Giv
esomef eat uresofI nter f
ace?
Iti
ncludes−
 Inter facecannotbei nst antiat ed
 Ani nter facedoesnotcont ainanyconst ruct ors.
 All oft hemet hodsi nani nter facear eabst ract.
52.
Def inePackagesi nJav a?
A Packagecan bedef ined asagr ouping ofr elat ed t y
pes(classes,
int
erfaces, enumer at i
onsandannot ati
ons)pr ov idingaccesspr otecti
on
andnamespacemanagement .
53.
WhyPackagesar eused?
Packagesar eusedi nJav ai n-or dert opr ev entnami ngconf li
cts,to
controlaccess,t o make sear chi ng/ l
ocating and usage ofcl asses,
int
erfaces, enumer at i
onsandannot ati
ons,et c.,easi er.
54.
Whatdoy oumeanbyMul ti
thr eadedpr ogr am?
A mul tithreaded pr ogr am cont ai nst wo ormor epar tst hatcanr un
concur rent l
y .Eachpar tofsuchapr ogram iscal ledat hr ead,andeach
thr
eaddef inesasepar atepat hofexecut ion.
55.
Whatar et het woway si nwhi chThr eadcanbecr eat ed?
Threadcanbecr eatedby :impl ement ingRunnabl ei nt erface,extending
theThr eadcl ass.
56.
Whati sanappl et?
Anappl eti saJav apr ogr am t hatr unsi naWebbr owser .Anappl etcan
beaf ul l
yf unct ionalJav aappl icat i
onbecausei thast heent i
reJav aAPI
atitsdisposal .
57.
Anappl etext endwhi chcl ass?
Anappl etex tendsj av [Link] [Link] etclass.
58.
Expl aingar bagecol l
ect ioni nJav a?
Ituses gar bage col lect ion t of ree t he memor [Link] eaning those
objectst hati snol ongerr eferencebyanyoft hepr ogr am.
59.
Def inei mmut ableobj ect ?
Animmut abl eobj ectcan’ tbechangedoncei ti scr eat ed.
60.
Expl aint heusageoft his()wi t hconst r
uct ors?
Iti
susedwi thv ari
abl esormet hodsandusedt ocal lconst ructerof
samecl ass.
61.
Expl ainSetI nt erface?
Iti
sacol l
ect ionofel ementwhi chcannotcont aindupl icateelement s.
TheSeti nter facecont ai
nsonl ymet hodsi nher i
tedf rom Col l
ecti
onand
addst her est ri
ct iont hatdupl icat eel ement sar epr ohibi ted.
62.
Expl ainTr eeSet ?
Iti
saSeti mpl ement edwhenwewantel ement si nasor tedor der.
[Link] sCompar abl eInt erface?
Iti s used t o sor tcol lections and ar rays of obj ects usi ng the
collections. sor t()andj av [Link]
[Link] ect soft hecl assi mpl ement i
ng
theCompar ablei nter f
acecanbeor der ed.
[Link] encebet weent hr owandt hrows?
Iti
ncl udes:
 T hrowi susedt otriggeranexcept ionwher east hrowsi susedi n
decl arat i
onofexcept ion.
 Wi thoutt hr ows,Checkedexcept ioncannotbehandl edwher eas
checkedex cept i
oncanbepr opagat edwi tht hrows.
[Link] aint hef ol lowi nglineusedunderJav aPr ogr am −
publ i
cst aticv oi dmai n(St ri
ngar gs[] )
Thef ol lowi ngshowst heexpl anat ioni ndiv i
dual ly−
 p ubl ic−i ti st heaccessspeci fi
er.
 s tat ic− i tal l
ows mai n( )t o be cal led wi thouti nst antiati
ng a
par t i
cul ari nst anceofacl ass.
 v oi d−i taf firnst hecompi l
ert hatnov aluei sret urnedbymai n(
).
 ma in()−t hismet hodi scal l
edatt hebegi nningofaJav apr ogram.
 S t ri
ngar gs[]−ar gspar amet erisani nst ancear rayofcl assSt ri
ng
[Link] ineJREi .[Link] aRunt i
meEnv ironment ?
Jav aRunt imeEnv ironmenti sani mpl ement ati
onoft heJav aVi r
tual
Machi ne whi ch execut es Jav a pr ograms.I tpr ov i
des t he mi nimum
requirement sf orexecut ingaJav aappl icat i
on;
[Link] sJARf il
e?
JARf ilesi sJav aAr chiv
ef lesandi taggr egat esmanyf il
esi ntoone.I t
holdsJav acl assesi nal ibrary .JARf il
esar ebui ltonZI Pf i
lef ormatand
hav [Link] i
leex t ensi on.
[Link] saWARf ile?
Thisi sWebAr chi v eFileandusedt ost or eXML,j avacl asses,and
Jav aSer v [Link] chi susedt odi stribut eacol l
ect ionofJav aServer
Pages, Jav aSer v l
et s,Jav acl asses, XMLf iles, st
at i
cWebpageset c.
[Link] ineJI Tcompi l
er?
Itimpr ov est her unt i
meper for manceofcomput erpr ogr amsbasedon
bytecode.
Whati st hedi f
f erencebet weenobj ector i
ent edpr ogrammi ngl anguage
and70. obj ectbasedpr ogr ammi ngl anguage?
Objectbasedpr ogr ammi ngl anguagesf ol l
ow al lt hef eat uresofOOPs
except I nher itance. Jav aScr ipt i s an exampl e of obj ect based
progr ammi ngl anguages.
[Link] st hepur poseofdef aul tconst r
uct or?
Thej av acompi lercr eat esadef aultconst ruct oronl yi ft her ei sno
const ruct ori nt hecl ass.
[Link] r
uct orbemadef inal ?
No, thisi snotpossi bl e.
[Link] sst at i
cbl ock?
Itisusedt oi nitializ et hest aticdat amember ,Itisexcut edbef oremai n
met hodatt het imeofcl assl oadi ng.
[Link] i
necomposi tion?
Hol dingt her efer enceoft heot hercl asswi thinsomeot hercl assi s
knownascomposi tion.
[Link] sf unct ionov er l
oadi ng?
If a cl ass has mul tiplef unct i
ons by same name but di fferent
par amet er s, itisknownasMet hodOv erloadi ng.
[Link] sf unct ionov er ri
di ng?
Ifasubcl asspr ov idesaspeci fi
ci mpl ement ationofamet hodt hati s
alreadypr ov idedbyi tspar entcl ass, i
tisknownasMet hodOv erriding.
[Link] ffer encebet weenOv er loadi ngandOv erriding?
Met hodov erloadi ngi ncr easest her eadabi li
t yoft hepr ogr [Link] hod
over ridingpr ov idest hespeci f i
ci mpl ement ationoft hemet hodt hati s
alreadypr ov i
dedbyi tssupercl asspar amet ermustbedi f
ferenti ncase
ofov erloadi ng, par amet ermustbesamei ncaseofov er r
iding.
[Link] sf inal cl ass?
Finalcl assesar ecr eat edsot hemet hodsi mpl ement edbyt hatcl ass
cannotbeov er r
idden.I tcan’ tbei nher it
ed.
[Link] sNul lPoi nt er Except ion?
ANul l
Poi nter Except i
oni sthr ownwhencal li
ngt hei nst ancemet hodofa
null obj ect ,accessi ngormodi f yingt hef i
eldofanul lobj ectet c.
[Link] et heway si nwhi chat hreadcanent ert hewai t
ingst ate?
At hr eadcanent ert hewai tingst atebyi nvoki ngi t
ssl eep( )met hod,by
blocki ngonI O, byunsuccessf ullyat tempt ingt oacqui r eanobj ect'slock,
orbyi nv oki nganobj ect 'swai t()met hod.I tcanal soent ert hewai ting
stat ebyi nv oki ngi ts( depr ecat ed)suspend( )met hod.
[Link] doesmul ti-thr eadi ngt akepl aceonacomput erwi thasi ngle
CPU?
Theoper ating sy st em' st askschedul eral l
ocat esexecut ion t ime t o
mul tiplet [Link] ckl yswi tchi ngbet weenexecut ingt asks, itcr eates
thei mpr essi ont hatt asksexecut esequent ially.
[Link] nv okesat hr ead' sr un( )met hod?
Afterat hr eadi sst arted,v iai t sst art
()met hodoft heThr eadcl ass,t he
JVM i nvokest het hread' sr un( )met hod whent het hread i si nitially
execut ed.
[Link] i t mat ter i n what or der cat ch st atement s f or
Fil
eNot FoundExcept ionandI OExcept i
onar ewr itten?
Yes,i t does. The Fi leNoFoundExcept i
on i s i nher ited f r
om t he
IOExcept i
[Link] cept ion'ssubcl asseshav et obecaughtf irst.
[Link] st hedi fferencebet weeny ieldingandsl eeping?
Whenat aski nv okesi t
sy i
eld()met hod,i treturnst ot her eadyst at e.
Whenat aski nv okesi tssl eep( )met hod, itr eturnst ot hewai t
ingst at e.
[Link] orcl assi sused?
TheVect orcl asspr ovidest hecapabi l
ityt oi mpl ementagr owabl ear ray
ofobj ect [Link] orpr ovest obev eryusef uli fyoudon' tknowt hesi zeof
thear rayi nadv ance,ory ouj ustneedonet hatcanchangesi zesov er
thel ifetimeofapr ogr am.
[Link] manybi tsar eusedt or epr esentUni code,ASCI I,UTF- 16,and
UTF- 8char act er s?
Uni coder equi res16bi tsandASCI Ir equi r e7bi [Link] thought heASCI I
char act ersetusesonl y7bi t
s,i ti susual l
yr epresent edas8bi t
[Link]- 8
repr esent schar act ersusi ng8,16,and18bi tpat [Link]- 16uses16-
bitandl ar gerbi tpat terns.
[Link] eWr appercl asses?
Thesear ecl assest hatal lowpr i
mi t
ivet ypest obeaccessedasobj ect s.
Exampl e: Integer ,Char act er,Doubl e, Bool eanet c.
[Link] st hedi fferencebet weenaWi ndowandaFr ame?
TheFr amecl assext endsWi ndowt odef ineamai nappl i
cat ionwi ndow
thatcanhav eamenubar .
[Link] chpackagehasl ightwei ghtcomponent s?
javax .Swi [Link] lcomponent sinSwi ng, exceptJAppl et,JDi alog,
JFr ameandJWi ndowar el ightwei ghtcomponent s.
[Link] st hedi fferencebet weent hepai nt ()andr epaint ()met hods?
The pai nt ()met hod suppor ts pai nting v ia a Gr aphi cs obj [Link]
repai nt()met hodi susedt ocausepai nt ()t obei nvokedbyt heAWT
paint ingt hr ead.
[Link] st hepur poseofFi l
ecl ass?
Iti s used t o cr eat e obj ectst hatpr ov ide access t ot he f iles and
direct oriesofal ocal fil
esy stem.
[Link] st hedi ffer encebet weent heReader /Wr i
tercl asshi erar chy
andt heI nput Stream/ Out put Stream cl asshi erarchy ?
The Reader /Wr iter cl ass hi erar chy i s char act er-
or i
ent ed,and t he
Input St r
eam/ Out put St r
eam cl asshi er archyi sby te-oriented.
[Link] chcl assshoul dy ouuset oobt aindesi gni nf ormat i
onaboutan
object ?
TheCl asscl assi susedt oobt aini nfor mat i
onaboutanobj ect'sdesi gn
andj av [Link]. Cl asscl assi nstancer epresentcl asses,i nterfacesi na
runningJav aappl icat ion.
[Link] st hedi ffer encebet weenst aticandnon- stat i
cv ariables?
Ast at i
cv ar i
abl ei sassoci atedwi tht hecl assasawhol er at
hert hanwi t
h
speci fici nst ancesofacl [Link]- stat i
cv ariablest akeonuni quev alues
witheachobj ecti nst ance.
[Link] sSer ializat ionanddeser i
al i
zation?
Ser i
aliz ationi st hepr ocessofwr i
tingt hest ateofanobj ectt oaby t
e
[Link] i
al i
z ationi sthepr ocessofr estor i
ngt heseobj ect s.
[Link] eusecases?
Itispar toft heanal y si
sofapr ogr am anddescr ibesasi t
uat iont hata
progr am mi ghtencount erandwhatbehav iort hepr ogr am shoul dexhi bit
inthatci rcumst ance.
[Link] ai nt heuseofsubl assi naJav apr ogr am?
Sub cl ass i nher i
ts al lt he publ ic and pr otected met hods and t he
implement ation.I tal soi nher i
tsal lt hedef aultmodi f
iermet hodsand
theirimpl ement ation.
[Link] oaddmenushor tcuttomenui t
em?
Ifther ei sabut toni nst ancecal ledb1,y oumayaddmenushor tcutby
calli
ngb1. set Mnemoni c( '
F'),sot heusermaybeabl et ouseAl t+Ft o
cli
ckt hebut ton.
[Link] ouwr iteaJav acl asst hatcoul dbeusedbot hasanappl etas
wellasanappl icat ion?
Yes, justaddamai n()met hodt ot heappl et.
[Link] st hedi ffer encebet weenSwi ngandAWTcomponent s?
AWTcomponent sar eheav y-
wei ght ,wher easSwi ngcomponent sar e
li
ghtwei ght .Heav ywei ghtcomponent sdependont hel ocalwi ndowi ng
[Link] e,j ava. [Link] ton isaheav ywei ghtcomponent ,
wheni ti sr unni ngont heJav apl atfor mf orUni xpl atform,i tmapst oa
realMot ifbut ton.
[Link] 'st hedi fferencebet weenconst r
uct orsandot hermet hods?
Const ruct orsmusthav et hesamenameast hecl assandcannotr eturn
av [Link] eonl ycal l
edoncewhi leregul armet hodscoul dbecal led
manyt imes.
[Link] her eanyl i
mi t ationofusi ngI nher it
ance?
Yes,si ncei nher itancei nher it
sev ery t
hingf rom t hesupercl assand
int
er face, itmaymaket hesubcl asst oocl ust eri
ngandsomet i
meser ror-
prone when dy nami c ov er ri
ding ordy nami c over l
oadi ng i n some
situat i
on.
103. Wheni st heAr ray St oreExcept iont hrown?
When copy i
ng el ement s bet ween di f
ferentar rays,i ft he sour ce or
dest inationar gument sar enotar raysort heirtypesar enotcompat ible,
anAr r
ay StoreEx cept i
onwi ll bet hrown.
104. Cany oucal loneconst ruct orf r
om anot herifacl asshasmul tiple
const r
uct ors?
Yes, uset his( )sy nt ax.
105. What '
st hedi ff erencebet weent hemet hodssl eep( )andwai t()?
Thecodesl eep( 2000) ;put st hreadasi def orexact l
yt [Link]
codewai t(2000) ,causesawai tofupt ot [Link] hreadcoul d
stopwai t
ingear lieri fi tr ecei vest henot i
fy()ornot i
f yAll(
)cal l
.The
met hodwai t()isdef inedi nt hecl assObj ectandt hemet hodsl eep()is
def inedi nt hecl assThr ead.
106. WhenAr i
t hmet icExcept i
oni st hrown?
TheAr ithmet i
cEx cept i
oni st hr ownwheni ntegeri sdi videdbyzer oor
takingt her emai nderofanumberbyzer o.I tisnevert hrowni nfloati
ng-
poi ntoper ations.
107. Whati sat r
ansi entv ariabl e?
At ransi entv ariabl ei sav ar i
abl et hatmaynotbeser iali
zeddur ing
Ser iali
zat i
onand whi chi si nitiali
zed byi t
sdef aultv aluedur i
ng de-
ser i
al i
zat i
on,
108. Whati ssy nchr oni zat ion?
Synchr oniz ation i st he capabi lit
yt o cont r
olt he access ofmul tipl
e
threadst oshar edr esour [Link] nchr onizedkey wor di nj av aprovides
locki ngwhi chensur esmut ualexcl usiveaccessofshar edr esourceand
prev entdat ar ace.
109. Whati st heCol lect ionsAPI ?
TheCol l
ect i
onsAPIi sasetofcl assesandi nterfacest hatsuppor t
oper ati
onsoncol l
ect ionsofobj ect s.
110. Doesgar bagecol lect ionguar ant eet hatapr ogram wi llnotr unout
ofmemor y?
Gar bagecol lectiondoesnotguar anteet hatapr ogram wi llnotrunout
ofmemor y.I tispossi bl ef orpr ogramst ouseupmemor yresources
fast erthant heyar egar bagecol [Link] salsopossi bl ef orprograms
tocr eateobj ect st hatar enotsubj ectt ogar bagecol lection.
111. Thei mmedi at esuper classoft heAppl etclass?
Paneli st hei mmedi at esuper [Link] ov i
desspacei nwhichan
appl icationcanat tachanyot hercomponent ,i
ncl udi ngot herpanel s.
112. Whi chJav aoper atori srightassoci ative?
The=oper at ori sr i
ghtassoci ative.
113. Whati st hedi fferencebet weenabr eakst atementandacont i
nue
statement ?
Abr eakst atementr esul t
si nt het ermi nat ionoft hest at
ementt owhi ch
itappl ies( swi t ch, f
or ,do, orwhi le).Acont i
nuest at ementi susedt oend
thecur rentl oopi terat i
onandr et urncont rol tot hel oopst atement .
114. Ifav ariabl ei sdecl aredaspr i
v ate,wher emayt hev ar i
abl ebe
accessed?
Apr ivatev ariabl emayonl ybeaccessedwi thi
nt hecl assi nwhi chi tis
decl ared.
115. Whati st hepur poseoft heSy stem cl ass?
The pur pose oft he Sy stem cl assi st o pr ov i
de accesst o sy stem
resour ces.
Listpr i
mi ti
veJav at ypes?
Theei ghtpr i
mi ti
v et ypesar eby te, char ,shor t,i
nt ,long, fl
oat ,doubl e,and
bool ean.
116. Whati st her elat i
onshi pbet weencl i
ppingandr epai nt
ingunder
AWT?
Whenawi ndow i sr epai ntedbyt heAWTpai nt i
ngt hread,i tset st he
clippingr egionst othear eaoft hewi ndowt hatr equi resr epainting.
117. Whi chcl assi st hei mmedi atesuper cl assoft heCont ainercl ass?
Componentcl assi st hei mmedi at esupercl ass.
118. Whatcl ass ofexcept ions ar e gener ated byt he Jav ar un- t
ime
syst em?
The Jav ar unt i
me sy st em gener ates Runt imeExcept ion and Er ror
except i
ons.
119. Underwhatcondi tionsi sanobj ect 'sf inalize( )met hodi nv okedby
thegar bagecol l
ect or?
Thegar bagecol l
ect ori nvokesanobj ect '
sf i
nal ize( )met hodwheni t
det ectst hatt heobj ecthasbecomeunr eachabl e.
120. Howcanadeadt hreadber est arted?
Adeadt hreadcannotber est arted.
121. Whi ch ar ithmet ic oper ations can r esul ti nt he t hrowi ng ofan
Arithmet icExcept i
on?
Integer/and%canr esul tint het hr owingofanAr it
hmet i
cExcept i
on.
122. Var i
abl eoft hebool eant ypei saut omat i
cal l
yi ni t
iali
zedas?
Thedef aultv al ueoft hebool eant y peisf alse.
123. Cant ryst at ement sbenest ed?
Yes
124. Whatar eCl assLoader s?
Acl assl oaderi sanobj ectt hati sresponsi blef orloadingcl [Link]
classCl assLoaderi sanabst ractclass.
125. Whati st hedi ffer encebet weenanI nterfaceandanAbst ractcl ass?
Anabst ractcl asscanhav ei nstancemet hodst hati mplementadef ault
behav ior .An I nterface can onl y decl ar e const ants and i nst ance
met hods,butcannoti mpl ementdef aultbehav iorandal lmet hodsar e
impl icitly abst [Link] i nter f
ace has al lpubl ic member s and no
impl ement ati
on.
126. Whatwi llhappeni fst aticmodi fierisr emov edf rom t hesi gnat ure
oft hemai nmet hod?
Pr ogr am t hrows" NoSuchMet hodError "erroratr unt i
me.
127. Whati st hedef aul tv alueofanobj ectr eferencedecl aredasan
i
nst ancev ariabl e?
Nul l,unl essi tisdef i
nedex pli
citl
y.
128. Canat opl evelcl assbepr ivateorpr otect ed?
No,at opl evelcl asscannotbepr ivat eorpr [Link] eei t
her
"publ ic"ornomodi fier.
129. Whydoweneedwr appercl asses?
Wecanpasst hem ar oundasmet hodpar amet erswher eamet hod
expect sanobj ect .Ital sopr ov i
desut ili
tymet hods.
130. Whati st hedi ffer encebet weener rorandanexcept ion?
Aner rori sani rr
ecov er ablecondi tionoccur ri
ngatr unt [Link]
Out Of Memor yer [Link] i
onsar econdi ti
onst hatoccurbecauseof
badi nputet c.e. [Link] leNot FoundExcept i
onwi llbet hrowni ft hespeci fi
ed
fil
edoesnotex ist.
131. Isi tnecessar yt hateacht rybl ockmustbef ol
lowedbyacat ch
block?
Itisnotnecessar yt hateacht ryblockmustbef oll
owedbyacat chbl ock.
Itshoul dbef ol l
owedbyei theracat chbl ockoraf inall
yblock.
132. Whenat hr eadi scr eat edandst arted, whati si t
sinitialst ate?
At hreadi si nt her eadyst ateasi nitialst ateaf terithasbeencr eated
andst arted.
133. Whati st heLocal ecl ass?
TheLocal ecl assi susedt otailorpr ogram out putt otheconv entionsof
apar ticul argeogr aphi c, pol i
ti
cal,orcul tural r
egi on.
134. Whatar esy nchr oni zedmet hodsandsy nchr onizedst atement s?
Sy nchr oniz edmet hodsar emet hodst hatar eusedt ocont r
olaccesst o
an obj ect .A sy nchr oni zed st atementcan onl ybeexecut ed af tera
threadhasacqui redt hel ockf ort heobj ectorcl assr eferencedi nthe
sy nchr oniz edst atement .
135. Whati sr unt i
mepol ymor phi sm ordy nami cmet hoddi spat ch?
Runt imepol ymor phi sm ordy nami cmet hoddi spat chi sapr ocessi n
whi chacal ltoanov er ri
ddenmet hodi sr esol vedatr untimer athert han
atcompi l
e-time.I nt hi spr ocess, anov er r
iddenmet hodi scal ledt hrough
ther eferencev ariabl eofasuper class.
136. Whati sDy nami cBi ndi ng( l
atebi ndi ng) ?
Bindi ngr eferst ot hel inki ngofapr ocedur ecal lt ot hecodet obe
execut edi nr esponset ot hecal l
.Dy nami cbi ndingmeanst hatt hecode
associ atedwi thagi v enpr ocedur ecal lisnotknownunt i
lthet i
meoft he
cal latr un-time.
137. Canconst ruct orbei nher ited?
No, const ruct orcannotbei nher ited.
138. Whatar et headv ant agesofAr rayListov erar ray s?Whydel eti
onin
LinkedLi sti sf astt han Ar ray List?How do y ou deci de when t o use
Array ListandLi nkedLi st?
Ify ouneedt of requent lyaddandr emov eel ement sf rom t hemi ddleof
thel istandonl yaccesst hel istel ement ssequent ially,thenLi nkedList
shoul d be used.I fy ou need t o suppor tr andom access,wi t
hout
inser tingorr emov ingel ement sf rom anypl aceot hert hant heend, then
Ar ray Listshoul dbeused.
139. Whati saVal uesCol lect ionVi ew?
Itisacol l
ect i
onr etur nedbyt hev alues( )met hodoft heMapI nterface,I
t
cont ainsal ltheobj ect spr esentasv al uesi nt hemap.
140. Whati sdotoper at or?
The dotoper at or(.)i s used t o access t he i nst ance v ariables and
met hodsofcl assobj ect [Link] sal sousedt oaccesscl assesandsub-
packagesf rom apackage.
141. Wher eandhowcany ouuseapr ivateconst ructor ?
Pr i
v at e const r uct ori s used i fy ou do notwantot hercl asses t o
inst ant i
atet heobj ectandt opr ev entsubcl assing. T
142. Whati st y pecast ing?
Ty pecast ingmeanst reat ingav ariabl eofonet y peast houghi tis
anot hert ype.
143. Descr i
bel i
f ecy cleoft hread?
At hr eadi saexecut ioni napr ogr [Link] if
ecy cleofat hreadi ncl ude−
 Ne wbor nst at e
 R unnabl est ate
 Runni ngst ate
 B lockedst ate
 De adst at e
[Link] st hedi fferencebet weent he>>and>>>oper ators?
The>>oper at orcar ri
est hesi gnbi twhenshi ft
ingr i
[Link]>>>zer o-
fil
l
sbi tst hathav ebeenshi f
t edout .
[Link] chmet hodoft heComponentcl assi susedt osett heposi t
ion
andsi zeofacomponent ?
setBounds( )met hodi susedf orthi spur pose.
[Link] st her angeoft heshor tty pe?
Ther angeoft heshor tty pei s-(2^15)t o2^ 15-1.
[Link] st hei mmedi at esuper cl assofMenu?
MenuI tem cl ass
[Link] aal lowDef aul tAr gument s?
No, Jav adoesnotal l
owDef aultAr gument s.
[Link] chnumberi sdenot edbyl eadi ngzer oinj av a?
Oct alNumber sar edenot edbyl eadi ngzer oinj ava, example: 06
[Link] chnumberi sdenot edbyl eadi ng0xor0Xi njava?
Hex adeci malNumber sar edenot edbyl eadi ng0xor0Xi njava,exampl e
−0XF
[Link] eakst at ementcanbeusedasl abelsi nJav a?
Yes, anex ampl ecanbebr eakone.
[Link] ei mpor tst atementi susedi naJav apr ogr am?
Impor tst at ementi sal l
owedatt hebegi nningoft heprogram f i
leafter
packagest at ement .
[Link] ainsuspend( )met hodunderThr eadcl ass?
Iti
susedt opauseort empor aril
yst opt heexecut ionoft het hread.
[Link] aini sAl ive()met hodunderThr eadcl ass?
Iti
susedt of indoutwhet herat hreadi sst il
lrunni ngornot .
[Link] scur rent Thr ead( )?
Itisapubl i
cst aticmet hodusedt oobt ainar ef erencetot hecurrent
thread.
[Link] ainmai nt hreadunderThr eadcl assexecut i
on?
Themai nt hread i scr eat ed aut omat i
cal l
yand i tbeginst o execute
immedi atelywhenapr ogr am st ar [Link] athreadf r
om whi chal lother
childthr eadsor iginat e.
[Link] cleofanappl eti ncludeswhi chst eps?
Lifecy cleinv olv est hef ol l
owi ngst eps−
 Ini ti
alizat ion
 S tarting
 St oppi ng
 De st roy i
ng
 P aint i
ng
158. Whyi st her oleofi ni t
()met hodunderappl ets?
Itiniti
alizest heappl etandi st hef irstmet hodt obecal led.
159. Whi chmet hodi scal l
edbyAppl etclasst ol oadani mage?
get Image( URLobj ect , f
ilename)i susedf ort hispur pose.
160. Def inecodeasanat t
ribut eofAppl et ?
Itisusedt ospeci fyt henameoft heappl etcl ass.
161. Def inecanv as?
Itisasi mpl edr awi ngsur facewhi char eusedf orpai nt i
ngi magesort o
per form ot hergr aphi cal oper ations.
162. Def ineNet wor kPr ogr ammi ng?
Itr eferst o wr iting pr ogr ams t hatexecut e acr oss mul t
iple devi
ces
(comput ers) ,inwhi cht hedev icesar eallconnect edt oeachot herusing
anet wor k.
163. Whati saSocket ?
Socket s pr ov ide t he communi cati
on mechani sm bet ween t wo
comput ersusi [Link] i
entpr ogram cr eatesasocketoni tsendof
thecommuni cat ionandat tempt st oconnectt hatsockett oaser ver.
164. Adv ant agesofJav aSocket s?
Socket sar ef lex ibleandsuf fi
cient .Effi
cientsocketbasedpr ogrammi ng
canbeeasi lyi mpl ement edf orgener alcommuni cations.I tcausel ow
net wor kt raf f
ic.
165. Disadv ant agesofJav aSocket s?
Socketbasedcommuni cat ionsal lowsonl yt osendpacket sofrawdat a
bet ween appl icat [Link] ht he cl ient-side and ser v er-
side havet o
prov idemechani smst omaket hedat ausef ul i
nanyway .
166. Whi chcl assi susedbyser verappl i
cat ionst oobt ainapor tand
l
istenf orcl ientr equest s?
[Link] .Ser ver Socketcl assi susedbyser verappl i
cat i
onst oobt aina
por tandl istenf orcl ientr equest s
167. Whi chcl assr epr esent st hesockett hatbot ht hecl i
entandser ver
uset ocommuni cat ewi theachot her ?
[Link] .Socketcl assr epr esent st hesockett hatbot ht hecl i
entand
ser veruset ocommuni cat ewi theachot her .
168. WhyGener icsar eusedi nJav a?
Gener i
cspr ov idecompi l
e-timet ypesaf et yt hatal l
owspr ogr ammer sto
cat chi nv alidt y pesatcompi l
et [Link] aGener i
cmet hodsandgener i
c
classes enabl e pr ogr ammer st o speci f y,wi th a si ngle met hod
decl ar at i
on, asetofr elatedmet hodsor ,withasi nglecl assdecl arati
on,
asetofr elatedt y pes.
169. Whatenv i
ronmentv ar iabl esdoIneedt osetonmymachi nei n
ordert obeabl et or unJav apr ogr ams?
CLASSPATHandPATHar et het wov ariables.
170. Ist her eanyneedt oi mpor tj av a.l
angpackage?
No,t her ei snoneedt oi mpor tt hi spackage.I ti sbydef aultloaded
inter nal l
ybyt heJVM.
171. Whati sNest edt op- lev elcl ass?
Ifacl assi sdecl aredwi thinacl assandspeci fyt hest ati
cmodi f
ier,the
compi lert reat st hecl assj ustl ikeanyot hert op- l
ev [Link] edt op-
level classi sanI nnercl ass.
172. Whati sExt er nal i
zabl ei nter face?
Ex ter nal i
zabl ei sani nter facewhi chcont ainst womet hodsr eadExternal
and wr iteExt ernal .These met hods gi v ey ou a cont rolov er t he
ser i
al izat ionmechani sm.
173. IfSy stem. exi t( 0) ;iswr i
ttenatt heendoft het ryblock,wi llthe
fi
nal lybl ockst i
llexecut e?
Noi nt hiscaset hef i
nal lybl ockwi l
lnotexecut ebecausewheny ousay
Sy stem. exi t( 0);t hecont roli mmedi atelygoesoutoft hepr ogram,and
thusf i
nal lynev erex ecut es.
174. Whati sdaemont hr ead?
Daemont hreadi sal owpr i
or ityt hr ead,whi chr unsi nt ermitt
entlyint he
backgr ounddoi ngt hegar bagecol l
ect i
onoper ati
onf orthej avarunt i
me
syst em.
175. Whi chmet hodi susedt ocr eat et hedaemont hread?
set Daemonmet hodi susedt ocr eat eadaemont hread.
176. Whi chmet hodmustbei mpl ement edbyal lthreads?
All tasksmusti mpl ementt her un( )met hod
177. Whati stheGr egor ianCal endarcl ass?
The Gr egor i
anCal endar pr ov i
des suppor tf or t raditi
onal West ern
calendar s
178. Whati stheSi mpl eTi meZonecl ass?
TheSi mpl eTimeZonecl asspr ov idessuppor tforaGr egor iancalendar.
179. Whati sthedi ffer encebet weent hesi zeandcapaci t
yofaVect or?
Thesi zei st henumberofel ement sact uall
yst oredi nt hev ector,whi l
e
capaci t
yi st hemax imum numberofel ement sitcanst oreatagi ven
instanceoft i
me.
180. Canav ectorcont ainhet erogenousobj ects?
YesaVect orcancont ai nhet er ogenousobj [Link] or
stor esev erythingi ntermsofObj ect.
181. Whati sanenumer ation?
Anenumer ationi sani nt erfacecont ai ningmet hodsf oraccessi ngt he
under l
y i
ngdat ast ructuref rom whi cht heenumer ationi sobt ained.I t
allowssequent i
al accesst oal ltheel ement sst oredi nt hecol l
ect ion.
182. Whati sdi ffer encebet weenPat handCl asspat h?
Pat handCl asspat har eoper atingsy st em l ev elenv ironmentv arial
es.
Pat hi sdef ineswher et hesy st em canf indt heexecut abl es(.exe)f i
les
andcl asspat hi susedt ospeci fyt hel ocat ionof. classf il
es.
183. Canacl assdecl aredaspr i
v atebeaccessedout si dei t'spackage?
No, it'
snotpossi bl etoaccessedout sidei t'spackage.
184. Whatar et her estrictioni mposedonast aticmet hodorast ati
c
blockofcode?
Ast aticmet hodshoul dnotr efert oi nst ancev ar i
ableswi thoutcr eating
ani nst anceandcannotuse" this"oper atort or ef erthei nst ance.
185. CananI nt erfaceext endanot herI nt er face?
Yes an I nter f
ace can i nher itanot herI nterf ace,f ort hatmat teran
Interfacecanex tendmor et hanoneI nter face.
186. Whi chobj ector ientedConcepti sachi ev edbyusi ngov er loading
andov er ri
ding?
Pol ymor phism
187. Whati sanobj ect'slockandwhi chobj ect '
shav el ocks?
Anobj ect '
sl ocki samechani sm t hati susedbymul tiplet hr eadst o
obt ainsy nchr oni zedaccesst ot heobj ect.A t hreadmayexecut ea
sy nchr onizedmet hodofanobj ectonl yaf terithasacqui redt heobj ect'
s
lock.
188. Whati sDowncast ing?
Itist hecast ingf rom agener al toamor especi fictype, i.
[Link] i
ngdown
thehi er archy .
189. Whatar eor derofpr ecedenceandassoci ati
v i
tyandhow ar et hey
used?
Or derofpr ecedence det ermi nes t he or deri n whi ch oper ator s are
ev aluated i n expr essi ons. Associ at i
t y det ermines whet her an
expr essi oni sev aluatedl ef t-
to- r
ightorr ight -to-left.
190. Ifamet hodi sdecl ar edaspr ot ect ed,wher emayt hemet hodbe
accessed?
Apr otect edmet hodmayonl ybeaccessedbycl assesori nterfacesof
thesamepackageorbysubcl assesoft hecl assi nwhi chi ti sdecl ared.
191. Whati st hedi fferencebet weeni nnercl assandnest edcl ass?
When a cl ass i s def ined wi thin a scope ofanot hercl ass,t hen it
becomesi nnercl ass.I ft heaccessmodi f
ieroft hei nnercl assi sst atic,
theni tbecomesnest edcl ass.
[Link] estrictionsar epl acedonmet hodov erri
di ng?
Ov err
iddenmet hodsmusthav et hesamename,ar gumentl i
st ,and
returnt y [Link] er ridingmet hodmaynotl i
mi tt heaccessoft he
met hodi tov erri
des.
[Link] sconst ruct orchai ningandhowi si tachi ev edi nJav a?
Achi ldobj ectconst ruct oral waysf irstneedst oconst r
ucti t
spar [Link]
Jav aiti sdonev iaani mpl ici tcalltot heno- ar gsconst r
uct orast hef i
rst
statement .
[Link] ev aluebecastt oaby te?
Yes, adoubl ev al uecanbecastt oaby te.
[Link] ryst atementdet ermi newhi chcat chcl auseshoul dbe
usedt ohandl eanexcept ion?
Whenanex cept i
oni st hrownwi thint hebodyofat ryst atement ,t he
catchcl ausesoft het r
yst atementar eexami nedi nt heor deri nwhi ch
theyappear .Thef i
rstcat chcl auset hati scapabl eofhandl ingt he
except ioni sex ecut [Link] emai ningcat chcl ausesar ei gnor ed.
[Link] llbet hedef aul tvaluesofal lt heel ement sofanar ray
definedasani nst ancev ar i
abl e?
Ifthear rayi sanar rayofpr imiti
v et y pes,t henal lt heel ement soft he
arraywi llbe i nitializ ed t ot he def aul tv alue cor respondi ng t ot hat
primitivet ype.
[Link] sJDBC?
JDBCst andsf orJav aDat abaseConnect ivi
ty,whi chi sast andar dJav a
API f or dat abase- independent connect ivity bet ween t he Jav a
programmi ngl anguageandawi der angeofdat abases.
[Link] ibeagener al JDBCAr chi tect ure?
Gener alJDBC Ar chit ect ur e consi st s oft wo l ay ers JDBC API( Thi s
prov i
dest heappl icat ion- to- JDBCManagerconnect ion)andJDBCDr i
ver
API( Thi ssuppor tst heJDBCManager -to-DriverConnect ion) .
[Link] et hecommonJDBCAPIcomponent s?
JDBCAPIconsi st soff ollowi ngi nter facesandcl assesDr i
verManager ,
Driver,Connect i
on, St atement ,Resul tSet ,SQLExcept i
on.
[Link] saJDBCDr i
v erManager ?
JDBCDr iverManageri sacl asst hatmanagesal istofdat abasedr i
ver s.
Itmat chesconnect ion r equest sf rom t hej av a appl icat i
on wi tht he
properdat abasedr iverusi ngcommuni cationsubpr ot ocol .
[Link] saJDBCDr i
v er?
JDBCdr iverisani nter faceenabl ingaJav aappl icat i
ont oi nteractwi tha
[Link] thi ndiv idualdat abases,JDBCr equi
resdr i
vers
foreachdat [Link] dr ivergi vesoutt heconnect i
ont ot he
databaseandi mplement st hepr otocolf ort ransf erringt hequer yand
resultbetweencl ientanddat abase.
[Link] saconnect i
on?
Connect ioni nterfaceconsi stsofmet hodsf orcont act ingadat abase.
Theconnect ionobj ectr epr esent scommuni cationcont ext .
[Link] sast atement ?
Statementencapsul atesan SQLst at ementwhi ch i spassed t ot he
databaset obepar sed, compi led, plannedandexecut ed.
[Link] saResul tSet?
Theseobj ect shol ddat aret ri
ev edf rom adat abaseaf tery ouexecutean
SQLquer yusi ngSt atementobj ect [Link] sasani teratort oall
owy out o
mov et hroughi tsdat [Link] av [Link] .
Resul tSeti nterfacer epr
esentst he
resultsetofadat abasequer y .
[Link] et ypesofResul t
Set ?
Therear et hreeconst antswhi chwhendef inedi nresul tsetcanmov e
cursori nresul tsetbackwar d, for war dandal soi napar ti
cul arrow.
 R esultSet .TYPE_ FORWARD_ ONLY− The cur sorcan onl y mov e
forwar di nther esul tset .
 R esultSet .TYPE_ SCROLL_ INSENSI TIVE− The cur sorcan scr ol
l
forwar dsandbackwar ds,andt her esultseti snotsensi ti
vet o
changesmadebyot her st ot hedat abaset hatoccuraf tert he
resultsetwascr eated.
 R esultSet .TYPE_ SCROLL_ SENSI TI VE− The cur sor can scr ol
l
forwar ds and backwar ds,and t he r esul tseti s sensitivet o
changesmadebyot her st ot hedat abaset hatoccuraf tert he
resultsetwascr eated.
[Link] et hebasi cst epst ocr eat eaJDBCappl icat i
on?
Foll
owi ngar et hebasi cst epst ocr eateaJDBCappl i
cat ion
 Impor t packages cont aining t he JDBC cl asses needed f or
databasepr ogrammi ng.
 R egistert heJDBCdr iver ,sot haty oucanopenacommuni cati
ons
channel wi t
ht hedat abase.
 Op en a connect i
on usi ng t he Dr i
v erManager .get Connection ()
met hod.
 E xecut eaquer yusi nganobj ectoft ypeSt atement .
 E xtr
act dat a f rom r esul t set usi ng t he appr opriate
Result Set .
getXXX( )met hod.
 Clean up t he env ir
onmentby cl osi ng al ldatabase r esour ces
rel yingont heJVM' sgar bagecol lect i
on.
[Link] eJDBCdr ivert ypes?
Ther ear ef ourt ypesofJDBCdr i
v ers
 J DBC- ODBC Br i
dgepl usODBC dr i
v er−al socal l
edTy pe1cal l
s
nat iv ecodeoft hel ocal lyav ailabl eODBCdr iver.
 Na tiv e-API ,partlyJav adr i
v er−al socal ledTy pe2cal lsdat abase
v endornat ivel i
brar yonacl ientsi [Link] scodet hent alkst o
dat abaseov ernet wor k.
 J DBC- Net ,pur eJav adr iv
er− al so cal ledTy pe3t hepur e-java
dr ivert hatt alkswi ththeser ver -
sidemi ddlewar ethatthent alkst o
dat abase.
 Na tiv e-protocol ,pureJav adr i
ver−al socal ledTy pe4t hepur e-java
dr ivert hatusesdat abasenat ivepr otocol .
[Link] deachoft heJDBCdr ivert ypebeused?
Followi ngi sal i
stast owhent hef ourt y pesofdr iverscanbeused
 Ify ouar eaccessi ngonet ypeofdat abase, suchasOr acle, Sy base,
orI BM, thepr eferreddr i
v ert ypei s4.
 Ify ourJav aappl i
cat i
oni saccessi ngmul tipletypesofdat abases
att hesamet i
me, type3i st hepr ef erreddr iver.
 T y pe2dr iversar eusef uli nsi tuat ionswher eat y
pe3ort y pe4
dr iveri snotav ailabley etf ory ourdat abase.
 T het ype1dr i
verisnotconsi der edadepl oy ment -
leveldri
v erandi s
ty pical l
yusedf ordev elopmentandt est i
ngpur posesonl y.
[Link] cht ypeofJDBCdr iveri st hef ast estone?
JDBC Netpur eJav adr i
ver(Ty pe4)i st hef astestdr i
verbecausei t
conv ert st he JDBC cal l
si nt ov endorspeci fic protocolcalls and i t
directlyi nter actswi tht hedat abase.
[Link] heJDBC- ODBCBr idgesuppor tmul ti
pl econcurrentopen
statement sperconnect ion?
[Link] yoneSt atementobj ectperconnect i
onwheny ou
areusi ngt heJDBC- ODBCBr idge.
[Link] et hest andar disol ationl evel sdef inedbyJDBC?
Thest andar di solationl evelsar e
 T RANSACTI ON_ NONE
 T RANSACTI ON_ READ_ COMMI TTED
 T RANSACTI ON_ READ_ UNCOMMI TTED
 T RANSACTI ON_ REPEATABLE_ READ
 T RANSACTI ON_ SERI ALI ZABLE
[Link] st hedesi gnpat t ernf oll
owedbyJDBC?
JDBCar chi tect uredecoupl esanabst ract i
onf rom i tsi mpl ement ati
on.
HenceJDBCf ollowsabr idgedesi gnpat t [Link] ovides
theabst ract ionandt heJDBCdr i
ver spr ovidet hei mpl ement [Link]
driv
erscanbepl ugged- i
nt ot heJDBCAPIwi thoutchangi ngt hecl i
ent
code.
[Link] et hedi ff erentt ypesofJDBCSt atement s?
Typesofst at ement sar e
 S tatement−r egul arSQLst atement .
 P repar edSt at ement−mor eef ficientt hanst atementduet opr e-
compi lationofSQL.
 Ca l
labl eSt atement−t ocal lst
or edpr ocedur esont hedat abase.
[Link] sdi ffer encebet weenst at ementandpr epar edst atement ?
Prepar ed st at ement s off erbet t
erper f
or mance,as t hey ar e pre-
compi [Link] epar ed st atement sr euse t he same execut ion pl an for
diff
erentar gument sr athert hancr eat inganew execut ionpl anev er y
ti
[Link] epar edst at ement susebi ndar gument s,whi char esentt ot he
databaseengi [Link] sallowsmappi ngdi fferentr equest swi thsame
prepared st atementbutdi fferentar gument st o execut et he same
execut ionpl [Link] epar edst atement sar emor esecur ebecauset heyuse
bindv ar i
abl es, whi chcanpr ev entSQLi nject i
onat tack.
Howdoy our egist eradr i
ver ?Ther ear e2appr oachesf orr egister i
ngt he
Dri
ver
 Cl ass. forName( )− Thi s met hod dy nami callyl oads t he dr i
ver's
cl ass f il
ei nt o memor y,whi ch aut omat i
cal l
yr egistersi [Link] s
met hodi spr ef erablebecausei tal lowsy out omaket hedr i
ver
r egi strationconf igurabl eandpor table.
 Dr iverManager .register Dr i
ver()− Thi s st at i
c met hod is used i n
casey ouar eusi nganon- JDKcompl iantJVM,suchast heone
pr ov i
dedbyMi crosof t.
[Link] et hebenef it
sofJDBC4. 0?
Herear ef ewadv ant agesofJDBC4. 0
 Au toloadi ngofJDBCdr iverclass.I nt heear l
ierv ersionswehadt o
manual lyr egi st erandl oaddr i
v ersusi ngcl [Link] Name.
 Co nnect i
onmanagementenhancement [Link] met hodsaddedt o
jav ax .[Link] edConnect i
on.
 Da taSetI mpl ement ationofSQLusi ngannot at i
ons.
 S QLXMLsuppor t.
[Link] oumeanbyf ast esttypeofJDBCdr iver?
JDBCdr i
v erper formanceorf ast nessdependsonanumberofi ssues
Qual i
tyoft hedr ivercode,si zeoft hedr i
v ercode,dat abaseser verand
it
sl oad,Net workt opol ogy ,Numberoft imesy ourrequesti stranslated
toadi fferentAPI .
[Link] timepr ojectwhi chdr iverdi dy ouuse?
Tellabouty ourr eal timeexper i
ence.
[Link] oucr eat eaconnect ionobj ect ?
Ther e are 3 ov er l
oaded Dr iver Manager .getConnect i
on( )met hods t o
createaconnect ionobj ect
getConnect i
on( St r
ingur l,St ringuser ,St r
ingpasswor d)Usingadat abase
URLwi t
hauser nameandpasswor [Link] e
Stri
ngURL=" j
dbcor aclet hi n@amr ood1521EMP" ;
Stri
ngUSER=" user name" ;
Stri
ngPASS=" passwor d"
Connect ionconn=Dr i
v er Manager .getConnect i
on(URL, USER, PASS) ;
getConnect ion(St ri
ngur l
) Usi ngonl yadat [Link] e
Stri
ngURL=" j
dbcor aclet hi nuser name/ passwor d@amr ood1521EMP" ;
Connect ionconn=Dr i
v er Manager .getConnect i
on(URL) ;
getConnect ion(St ri
ngur l
, Pr oper t i
espr op)Usi ngadat abaseURLanda
Properti
esobj [Link] ampl e
Stri
ngURL=" j
dbcor aclet hi n@amr ood1521EMP" ;
Properti
esi nf o=newPr oper ties() ;
i
[Link](" user ","user name") ;
i
[Link](" passwor d", "
passwor d") ;
[Link] ermi newhet heraSt atementandi t
sResul tSetwi l
lbe
cl
osedonacommi torr ol lback?
Use the Dat abaseMet aDat a methods
suppor t
sOpenSt atement sAcr ossCommi t() and
suppor tsOpenSt atement sAcr ossRol l
back( )tocheck.
[Link] eapr act i
cal li
mi tfort henumberofSQLst atement sthatcan
beaddedt oani nst anceofaSt atementobj ect?
The speci ficati
on makes no ment ion of any si ze l i
mitati
on f or
Statement .addBat ch( ),thi si sdependent ,ont hedr i
ver.
[Link] sorwor ksi nscr ollabl er esultset ?
Ther e are sev er almet hods i nt he Resul t
Seti nterface thati nvolve
mov ing t he cur sor ,l ike bef or eFirst
( ), af t
erLast(),f i
rst(
),l ast()
,
absolute( i
nt r ow) ,r elat ive(int r ow) , pr evious(), next(), getRow( )
,
mov eToI nser t
Row( ), mov eToCur r
ent Row( ).
[Link] ouv iewar esul tset ?
Resul t
Seti nterfacecont ainsgetmet hodsf oreachoft hepossibledat a
types, andeachgetmet hodhast wov ersions
 On ethatt akesinacol umnname.
 On ethatt akesinacol umni ndex.
Fore. [Link] I
nt(Stri
ngcol umnName) ,getInt(intcol umnI ndex)
[Link] ouupdat ear esul tset ?
Resul tSeti nterface cont ains a col lect i
on ofupdat e met hods f or
updat ingthedat aofar esul tset .Eachupdat emet hodhast wov ersions
foreachdat at ype
 On ethatt akesinacol umnname.
 On ethatt akesinacol umni ndex.
Thesemet hodschanget hecol umnsoft hecur r
entr owi nt heResul tSet
object,butnoti ntheunder lyingdat [Link] eyourchangest o
ther ow i nt hedat abase,y ou need t oi nv okeoneoft hef ollowing
met hods
updat eRow( ), del eteRow( )
, r efreshRow( ), cancel RowUpdat es(),
insertRow( )
[Link] et hedat aty pesofJav aanddat abase?
TheJDBCdr iverconv ertst heJav adat at ypet ot heappr opr iateJDBC
typebef oresendi ngi tt ot hedat abase.I tusesadef aultmappi ngf or
mostdat at [Link] e,a Jav ai nti sconv er
ted t o an SQL
INTEGER.
[Link]" Nosui tabledr iver "error ?
"No sui table dr iver" i s occur s dur i
ng a cal l t o t he
DriverManager .getConnect i
onmet hod,maybeofanyoft hef ollowing
reason
 Du etof aili
ngt ol oadt heappr opr iateJDBCdr i
versbef orecal li
ng
theget Connect ionmet hod.
 Itcan be speci fy i
ng an i nvalid JDBC URL,one t hati s not
recogniz edbyJDBCdr i
v er.
 T hiserrorcanoccuri foneormor et heshar edl i
brari
esneededby
thebr i
dgecannotbel oaded.
[Link] ouhandl eSQLNULLv aluesi nJav a?
SQL' suseofNULLv aluesandJav a'
suseofnul lar ediff
erentconcept s.
Ther ear ethreet acti
csy oucanuse
 Av oidusi ngget XXX()met hodst hatr et urnpr imi t
ivedat at ypes.
 Us e wr appercl asses f orpr i
mi ti
v e dat at ypes,and use t he
Resul t
Setobj ect '
swasNul l
()met hodt ot estwhet hert hewr apper
classv ar i
ablet hatr ecei vedt hev aluer eturnedbyt heget XXX()
met hodshoul dbesett onul l.
 Usepr imi tiv edat at ypesandt heResul tSetobj ect'swasNul l
()
met hodt ot estwhet hert hepr i
mi tivev ariablet hatr ecei vedt he
v aluer etur ned byt heget XXX()met hodshoul dbesett o an
accept abl ev al uet haty ou'vechosent or epr esentaNULL.
[Link] Aut oCommi tdo?
Whenaconnect ioni scr eat ed,iti sinaut o-commi [Link] smeans
thateachi ndi vidualSQLst atementi st reatedasat ransact ionandwi l
l
beaut omat ical l
ycommi ttedr ightaf t
eri ti sexecut [Link] t
ingaut o-
commi tt of al se no SQL st atement s wi llbe commi tted unt ily ou
explicitlycal l thecommi tmet hod.
[Link] ll yousetaut ocommi tmodet of alse?
Followi ngar et her easons
 T oi ncr easeper formance.
 T omai ntai nt hei ntegr ityofbusi nesspr ocesses.
 T ousedi str ibut edt ransact ions.
[Link] sSav ePoi nt ?Gi veanexampl e.
Asav epoi ntmar ksapoi ntt hatt hecur rentt ransact ioncanr ollbackt o.
Insteadofr olli
ngal lofi tschangesback, itcanchooset or ollbackonl y
someoft [Link] ampl e,supposey ou
 s tar tat ransact ion.
 inser t10r owsi nt oat able.
 s etasav epoi nt.
 inser tanot her5r ows.
 r ollbackt ot hesav epoi nt.
 c ommi tthet ransact ion.
Afterdoi ngt his, t het ablewi l
lcont ainthef i
rst10r owsy oui nser [Link]
other5r owswi llhav ebeendel etedbyt her [Link] epoi ntisj usta
mar kert hatt hecur rentt r
ansact i
oncanr ollbackt o.
[Link] eSQLwar nings?
SQLWar ni ngobj ect sar easubcl assofSQLExcept iont hatdealwi th
databaseaccesswar [Link] ni
ngsdonotst opt heexecut i
onofan
appl i
cat ion, asexcept i
[Link] mpl yaler tt heusert hatsomet hi
ng
didnothappenaspl [Link] ningcanber eportedonaConnect i
on
object , a St at ement obj ect ( i
ncludi ng Pr epar edStat ement and
CallableSt atementobj ect s),oraResul tSetobj ect .Eachoft hesecl asses
hasaget War ningsmet hod.
[Link] dy ouuseabat chpr ocess?
BatchPr ocessi ngal lowsy out ogr oupr elatedSQLst atement si nt oa
batchandsubmi tt hem wi t
honecal lt
ot hedat abase.
233. Whatar et hest epsf ollowedt ocr eateabat chpr ocess?
Ty picalsequencesofst epst ouseBat chPr ocessi
ngwi thSt atementor
Pr epar eSt atementObj ectar e
 In case ofBat ch pr ocessi ng usi ng Pr epar eSt atementobj ect,
creat eSQLst atement swi t
hpl acehol ders.
 Cr eat e a St atementorPr epar eStatementobj ectusi ng ei t
her
creat eStat ement ()orpr epar eSt atement ()methodsr espectivel
y.
 S etaut o-commi ttof al seusi ngset Aut oCommi t().
 Ad d as many as SQL st atement sy ou li
ke i nto bat ch using
addBat ch( )met hodoncr eat edst atementobj ect .
 E x ecuteal lt heSQLst atement susi ngexecut eBat ch( )methodon
creat edst at ementobj ect.
 F inally,commi tallthechangesusi ngcommi t
()met hod.
234. Whati saSt oredPr ocedur eandhowdoy oucalli tinJDBC?
Ast oredpr ocedur eisagr oupofSQLst atementst hatf orm alogi cal
uni tand per f
or m a par t
iculart [Link] e oper ations on an
empl oy eedat abase( hire,f i
re,pr omot e,l ookup)coul d becoded as
stor edpr ocedur esex ecut edbyappl icat i
[Link] or edpr ocedurescan
becal ledusi ngCal lableSt atementcl assi nJDBCAPI .Forexampl ethe
followi ngcodedemonst ratest hi
s
Cal l
abl eSt atementcs=con. prepar eCal l
("{
cal l
MY_ SAMPLE_ STORED_ PROC} ");
Resul tSetr s=cs. execut eQuer y()
;
235. Whati sJDBCSQLescapesy nt ax?
Theescapesy ntaxgi v esy out hef lexibilit
yt ousedat abasespeci fi
c
feat ures unav ail
abl et oy ou byusi ng st andar d JDBC met hods and
proper ties.
Thegener al SQLescapesy ntaxf or mati sasf oll
ows
{key wor d' paramet ers'
}.
JDBCdef i
nesescapesequencest hatcont ai
nthestandardsy ntaxfor
thefoll
owi nglanguagef eatures
 Date, t
ime,andt i
mest ampl i
teral
s(d,t,tsKeywords)
.
 Scalarfunctionssuchasnumer i
c,str
ing,anddatatypeconv ersi
on
functions(f
nKey word).
 Outerjoins(ojKeywor d)
 Escape char actersf orwildcards used in LI
KE clauses(escape
Key word).
 Procedur ecall
s(call
Key word).
236. Whati sat ransact ion?
At r
ansact ioni sal ogi caluni tofwor [Link] eteal ogicalunitof
wor k,sev er alact ions may need t o be taken agai nsta dat abase.
Transact i
onsar eused t o pr ov idedat aint egri
ty,cor r ectappl i
cation
semant ics, andaconsi st entv iewofdat adur ingconcur r entaccess.
237. Howwi lly oui nser tmul t
ipl er owsi ntoadat abasei nasi ngle
tr
ansact i
on?
Fol l
owst epsasbel ow
//t
ur nof fthei mpl icitcommi t
Connect i
on. set Aut oCommi t(
false) ;
//.
.youri nser t/updat e/ del etegoesher e
Connect i
on. Commi t
() ;
//anewt ransact i
oni si mpl icitl
yst ar ted.
238. Whenwi lly ougett hemessage" NoSui t
abl eDr iver "?
WhenaConnect ionr equesti si ssued,t heDr iverManageraskseach
loadeddr i
v eri fi tunder standst heURLsent .Whent heURLpassedi s
notpr oper lyconst ruct ed,t hen t he" No Sui tableDr iv er"messagei s
returned.
239. Whati st hedi ff
er encebet weenexecut e, execut eQuer y,
execut eUpdat e?
 b ool eanex ecut e( )-Execut est heanyki ndofSQLst atement .
 R esul tSetexecut eQuer y ()-Thi sisusedgener allyf orr eadingt he
cont entoft he dat [Link] out putwi llbe i nt he f orm of
Resul tSet .Gener al lySELECTst atementi sused.
 i ntex ecut eUpdat e()-Thi si s gener ally used f oral ter
ing t he
dat [Link] al l
yDROP TABLEorDATABASE,I NSERT i nto
TABLE,UPDATETABLE,DELETEf rom TABLEst at ement swi l
lbe
usedi nt [Link] putwi llbei nthef or
m ofi ntwhi chdenot es
thenumberofr owsaf fect edbyt hequer y.
240. Whydoy ouhav et ocl osedat abaseconnect ionsi nJav a?
Youneedt ocl oset her esul tset ,t hest atementandt heconnect i
[Link]
theconnect i
onhascomef rom apool ,closingi tact ual lysendsi tback
tot hepool forr [Link] hisi nthef inall
y {
}bl ock, sucht hatifan
except ioni st hr own, youst illgett hechancet ocl oset hi s.
241. Whati st heuseofbl ob,cl obdat atypesi nJDBC?
Thesear eusedt ost orel argeamountofdat ai ntodat abasel ikeimages,
mov ieet cwhi char eex tremel yl ar gei nsize.
242. Resul tseti sani nt er face, howdoesi tsuppor [Link] ()?
Ev eryv endorofDat abasepr ov idesi mpl ement at
ionofResul t
Set&ot her
interfaces, throught heDr iv er.
243. Whati sConnect i
onPool ing?
Connect i
on Pool ing i sat echni que used f or r euse of phy si
cal
connect ionsandr educedov erheadf ory ourappl icat [Link] ion
pool ingf unct ionalitymi ni mi zesexpensi v eoper ationsi nthecr eation
and cl osing ofsessi ons. Dat abase v endor 's hel p mul ti
ple cl i
ent st o
shar eacachedsetofconnect i
onobj ect st hatpr ov idesaccesst oa
dat [Link] i
ent s need notcr eate a new connect ion ev er yt
ime t o
interactwi tht hedat abase.
244. Howdoy oui mpl ementconnect i
onpool i
ng?
Ify ou use an appl i
cat ion ser verl ike WebLogi c,WebSpher e,j Boss,
Tomcat .,t hen y ourappl icat i
on ser verpr ovides t he faci li
ties t o
conf iguref orconnect ionpool ing.I fy ouar enotusi nganappl ication
ser vert hencomponent sl ikeApacheCommonsDBCPComponentcan
beused.
245. Outofby t
e[]oraj ava. sql .
Blob, whi chhasbestper formancewhen
usedt omani pulat edat af rom dat abase?
[Link] .
Bl obhasbet terper for manceasi tdoesnotext ractanydat a
from t hedat abaseunt i
l youexpl i
cit
lyaski tto.
246. OutofSt ringoraj av [Link] .Clob, whi chhasbestper for mancewhen
usedt omani pulat edat af rom dat abase?
[Link] .
Cl obhasbet terper for manceasi tdoesnotext ractanydat a
from t hedat abaseunt i
l youexpl i
cit
lyaski tto.
247. Supposet heSELECTr et urns1000r ows, thenhowt oretrievet he
fi
rst100r ows, thengobackandr etriev et henext100r ows?
Uset heSt atement .set Fet chSi zemet hodt oi ndicat et hesi zeofeach
dat abasef et ch.
248. Whatdoest heCl ass. forName( "My Class" )do?
Class. forName( "My Cl ass" )
 L oadst hecl assMy Cl ass.
 E xecut eanyst aticbl ockcodeofMy Class.
 R eturnsani nstanceofMy Class.
249. Wheny ousayCl ass. for Name( )loadst hedr i
v ercl ass, doesi tmean
i
timpor t
st hedr ivercl assusi ngi mpor tst atement ?
No,i tdoesn' [Link] mpor tst at ementt ell
st hecompi lerwhi chcl asst o
lookf [Link] ass. f
or Name( )i nst ructst heCl asscl asst of indacl ass-loader
andl oadt hatpar t
icularCl assobj ecti ntot hememor yusedbyt heJVM.
250. Whatwesett heat tr
ibut eConcur rencyi nResul tSet ?
TheResul tSetconcur rencydet ermi neswhet hert heResul t
Setcanbe
updat ed,oronl yr [Link] tSetcanhav eoneoft woconcur rency
levels
 R esul tSet .CONCUR_ READ_ ONLY−meanst hatt heResul tSetcan
onl yber ead.
 R esul tSet .CONCUR_ UPDATABLE−meanst hatt heResul tSetcan
bebot hr eadandupdat ed.
[Link] et hedi fferencesbet weenset MaxRows( i
nt)and
SetFet chSi ze( i
nt )?
Thedi ffer encebet weenset FetchSi ze( i
nt)andset MaxRow( i
nt)ar e
 s et Fet chSi z e(i
nt )def i
nest henumberofr owst hatwi l
lber ead
from t he dat abase when t he Resul tSet needs mor er ows.
set FetchSi ze(int)af f
ectshow t hedat abaser eturnstheResul tSet
dat a.
 s et Max Rows( i
nt )met hodoft heResul tSetspeci fi
eshow many
rowsaResul tSetcancont ainatat i
[Link] MaxRows( i
nt )af f
ect s
thecl i
entsi deJDBCobj ect .
[Link] saRowSet ?
AJDBCRowSetobj ecthol dst abul ardat ai nawayt hatmakesi tmor e
flexibleandeasi ert o uset hanar esul tset .A RowSetobj ectsar e
Jav aBeanscomponent s.
[Link] edi fferentt y pesofRowSetobj ect s?
Ther ear et wot ypesofRowSet
 Co nnect edAconnect edRowSetObj ecti sper manenti nnat ure.I t
doesn' tt erminat eunt i
l t
heappl icationi st erminated.
 Di sconnect edAdi sconnect edRowSetobj ectisad- hoci nnat ur e.
Whenev er i tr equi res r et ri
ev ing dat af rom t he dat abase,i t
est ablishes t he connect i
on and cl oses i tupon f i
nishi ng t he
requi redt [Link] athati smodi f
ieddur ingdisconnect edst ate
isupdat edaf tert heconnect i
oni sre-est ablished.
[Link] sa" dirtyr ead" ?
Int ypicaldat abase t ransact ions,say one t r
ansact i
on r eads and
changest hev aluewhi l
et hesecondt r
ansact ionr eadst hevaluebef ore
commi ttingorr olli
ngbackbyt hef irstt r
ansact [Link] sreadingpr ocess
iscal l
edas' di rt
yr ead' .Becauset her eisal way sachancet hatt hef i
rst
transact ion mi ghtr ollback t he change whi ch causes t he second
transact ionr eadsani nval i
dv alue.
[Link] chi sol ationl evelpr ev ent sdi rtyr eadi nJDBC, connect i
oncl ass?
TRANSACTI ON_ READ_ COMMI TTEDpr ev entsdi rtyreads.
[Link] sMet adat aandwhyshoul dy ouusei t?
JDBC API has t wo Met adat a i nterfaces Dat abaseMet aDat a &
Resul tSetMet aDat a. The met a dat a pr ovides compr ehensiv e
informat i
onaboutt hedat abaseasawhol [Link] mpl ementat ionf or
thesei nterfacesi si mpl ement edbydat abasedr i
verv endor stol etuser s
knowt hecapabi li
tiesofaDat abase.
257. Howt oConnectt oanExcelSpr eadsheetusingJDBCi nJav a?
Fol l
owt hest epsbel ow
Firstsetupt henewODBCdat [Link] nist
r ati
v eTools−>Dat a
Sour ces ( ODBC) −>Sy stem DSN t ab−>Add−>Dr iv
er do Mi crosoft
Ex cel(
* .
xls)−>Fi [Link] v
et heDat aSour ceName( Sampl eExcel )&
Descr ipti
[Link] t,clickSel ectWor kbookandpoi nttoy ourexcel sheet.
Int hecodemaket of ol
lowingcodeaddi ti
ons
[Link]( "[Link]. JdbcOdbcDr i
ver")
;
Connect ionconn=
DriverManager .get Connect i
on( "
jdbcodbcSampl eExcel",
"",
"");
stmt=conn. cr eat eSt atement ();
sql ="select*f r om [ Sheet 1$]"
;
rs=stmt .
ex ecut eQuer y(sql);
Wher eSheet 1ist heex celsheetname.
[Link] f
fer encebet weenJDBC, JNDIandHi ber nate?
 Hibernatei sanObj ect−Relat i
onalMappi ngt ool.I tmapsObj ects
torelational dat a.
 TheJav aNami ng and Di rectoryI nterface( JNDI )isanAPIt o
accessdi ffer entnami nganddi rectoryser v i
[Link] tto
accesssomet hi ngst oredinadi r
ect oryornami ngservicewi t
hout
haveingt ocodespeci f
icall
yt othatnami ngordi rector
yser v
ice.
 Java Dat aBase Connect i
vity( JDBC)APIi s an APIt o access
diff
erentr el ationaldat [Link] usei tt o accessr el
ati
onal
databases wi thoutembeddi ng a dependency on a speci fi
c
databaset ypei ny ourcode.
[Link] rectsy nt
axf ormai nmet hodofaj av aclass?
A-publ i
cst aticintmai n(Stri
ng[]args)
B-publ i
cintmai n( String[]args)
C-publ i
cst aticv oidmai n(String[]args)
D-Noneoft heabov e.
Answer: C
Explai
nati
on
Correctsyntaxi spubl i
cst ati
cv oidmai n(St r
ing[]args) .
[Link] hesi zeofshor tvariable?
A-8bi t
B-16bi t
C-32bi t
D-64bi t
Answer: C
Explaination
Theshor tdat at ypei sr epresentedby16- bitsignedtwo'scompl ement
integer .
Mi nimum v alue: -
32, 768
Maxi mum v al
ue: 32, 767
[Link] st hedef aultv al
ueofl ongv ari
able?
A-0
B-0. 0
C-0L
D-notdef i
ned
Answer: C
Explaination
longv ari
abl ehasdef aultvalueof0Li fdef i
nedasani nstance/st
ati
c
variable.
[Link] st hedef aultv al
ueofBool eanv ariable?
A-t rue
B-f alse
C-nul l
D-notdef i
ned
Answer: B
Explaination
bool ean v ariable has def aultv al
ue of f al
se if defined as an
instance/ staticv ariable.
[Link] assal way shasadef aultconst r
uctor.
A-Tr ue
B-Fal se
Answer: B
Explaination
Itisnotmandat oryt ohav eadef aultconstructorinaclass.
[Link] sst at
icbl ock?
A-I tisusedt ocr eatesy ncronizedcode.
B-Ther ei snosuchbl ock.
C-I ti susedt oi ni
t i
alizethest ati
cdat amember .,I
tisexcutedbef or
e
mai nmet hodatt het i
meofcl assloading.
D-Noneoft heabov e.
Answer: C
Explainat ion
staticbl ocki susedt oinit
ial
izethest aticdat amember .I
tisexecut ed
bef oremai nmet hodatt hetimeofl oadingofacl ass.
265. Whati sf unct ionov erri
ding?
A-I fasubcl assusesamet hodt hatisal readypr ovi
dedbyi t
spar ent
class, itisknownasMet hodOv err
iding.
B-I fasubcl asspr ov i
desaspeci ficimpl ement ationofamet hodt hatis
alreadypr ov idedbyi tsparentclass, i
tisknownasMet hodOv er
ri
ding.
C-Bot hoft heabov e.
D-Noneoft heabov e.
Answer: B
Explainat ion
Ifasubcl asspr ov i
desaspeci fi
ci mplement at i
onofamet hodt hatis
alreadypr ov idedbyi tsparentclass, i
tisknownasMet hodOv er
ri
ding.
266. Whati ssy nchr oni zati
on?
A-Sy nchr oni zat ioni sthecapabi li
tyt ocont rolt heaccessofmul tipl
e
threadst oshar edr esour ces.
B-Sy nchr oni zat i
oni st hepr ocessofwr i
ti
ngt hest at
eofanobj ectto
anot herobj ect .
C-Sy nchr oni zat i
oni sthepr ocessofwr i
ti
ngt hest at
eofanobj ectto
byt est ream.
D-Noneoft heabov e.
Answer: A
Explainat ion
Sy nchr oniz ation i st he capabili
tyt o cont r
olt he access ofmul tipl
e
threadst oshar edr [Link] nchronizedkey wor dinjavapr ov i
des
lockingwhi chensur esmut ualexclusiveaccessofshar edresourceand
prev entdat ar ace.
267. Cant ryst at ement sbenest ed?
A-Tr ue.
B-Fal se.
Answer: A
Explainat ion
Yes, tryst at ement sbenest ed.
268. Whi chmet hodmustbei mplement edbyal lthreads?
A-wai t
( )
B-st art()
C-st op()
D-r un()
Answer: D
Explai
nat i
on
Allthreadsmusti mpl ementt her un()met hod.
[Link] choft hef ollowi ngi scor r
ectaboutConnect i
oni nterfaceof
JDBC?
A-Connect ioni nter faceconsi st sofmet hodsf orcont actingadat abase.
B-Itr epresent scommuni cationcont ext .
C-Bot hoft heabov e.
D-noneoft heabov e.
Answer: C
Explanation
Connect ioni nterfaceconsi stsofmet hodsf orcont actingadat abase.
Theconnect ionobj ectr epr esent scommuni cati
oncont ext.
[Link] choft hef ollowi ngi snotav ali
dt y peofResul tSet ?
A-Resul tSet .
TYPE_ FORWARD_ ONLY
B-Resul tSet .
TYPE_ SCROLL_ INSENSI TIVE
C-Resul tSet .
TYPE_ SCROLL_ SENSI TIVE
D-Resul tSet .
TYPE_ BACKWARD_ ONLY
Answer: D
Explanation
ResultSet .TYPE_ BACKWARD_ ONLYi snotav ali
dtypeofResul tSet.
[Link] choft hef ollowi ngt y peofJDBCdr iv
er,usesdat abasenat ive
prot
ocol ?
A-JDBC- ODBCBr idgepl usODBCdr iver
B-Nat i
ve- API ,partlyJav adr i
ver
C-JDBC- Net ,pur eJav adr i
ver
D-Nat i
ve- protocol , pur eJav adr i
ver
Answer: D
Explanation
Native-prot ocol ,pur eJav adr iver,usesdat abasenat i
v epr ot
ocol.
[Link] choft hef ol lowingt y peofJDBC dr iverist ypicall
yusedf or
developmentandt est ingpur posesonl y?
A-Ty pe1
B-Ty pe2
C-Ty pe3
D-Ty pe4
[Link] choft hef oll
owi ngi scor rectaboutJDBC4. 0?
A-Aut ol oadingofJDBCdr i
v erclass.I ntheear lierv er
sionswehadt o
manual l
yr egisterandl oaddr i
v ersusingcl [Link].
B-Connect ionmanagementenhancement [Link] met hodsaddedt o
[Link] ion.
C-Bot hoft heabov e.
D-Noneoft heabov e.
Answer: C
Explanation
Bothoft heabov ear ecor rectaboutJDBC4. 0.
[Link] choft hef oll
owi ngi scor rectaboutbat chpr ocess?
A-Bat chPr ocessi ngal l
owsy out ogr oupr el
atedSQLst atement si
ntoa
batch.
B-Bat chPr ocessi ngal lowsy out osubmi tbatchofSQLst at
ements
withonecal ltot hedat abase.
C-Bot hoft heabov e.
D-Noneoft heabov e.
Answer: C
Explanation
BatchPr ocessi ngal lowsy out ogr oupr elatedSQLst atement sintoa
batchandsubmi tthem wi thonecal ltothedat abase.
[Link] choft hef oll
owi ngi scor rectaboutconnect ionpool i
ng?
A-Dat abasev endor '
shel pmul t
iplecl i
ent stoshar eacachedsetof
connect ionobj ectst hatpr ovidesaccesst oadat abase.
B-Cl ientsneednotcr eat eanewconnect ionev eryti
met ointeractwit
h
thedat abase.
C-Bot hoft heabov e.
D-Noneoft heabov e.
Answer: C
Explanation
Database v endor 's help mul tipl
e clientst o shar e a cached setof
connect ionobj ectst hatpr ov i
desaccesst oadat [Link] ientsneed
notcr eateanewconnect ionev erytimet ointeractwi ththedat abase.
[Link] choft hef oll
owi ngi scor rectaboutset MaxRows( int)
?
A-set MaxRows( i
nt)met hodoft heResul tSetspeci fieshowmanyr ows
aResul t
Setcancont ainatat ime.
B-set Max Rows( int)affect sthecl ientsideJDBCobj ect.
C-Bot hoft heabov e.
D-Noneoft heabov e.
Answer: C
Expl
anat i
on
setMaxRows( int)met hodoft heResul tSetspeci fi
eshow manyr owsa
Resul tSetcancont ainatat [Link] MaxRows( int)af f
ectst heclientside
JDBCobj ect .
278.A connect edRowSetObj ecti sper manenti nnat [Link]' t
ter
mi nat eunt iltheappl icat i
oni st ermi nated.
A-t rue
B-f alse
Answer: A
Expl
anat i
on
Aconnect edRowSetObj ecti sper manenti nnat ur [Link]'tterminate
unti
l theappl icat i
oni ster minat ed.
[Link] choft hef ol
lowingi st r
ueaboutJDBC?
A-TheJDBCAPIi sanAPIt oaccessdi f
ferentrel ati
onal databases.
B-Youusei tt oaccessr elati
onaldat abaseswi t
houtembeddi nga
dependencyonaspeci fi
cdat abaset ypei nyourcode.
C-JDBCst andsf orJav aDat aBaseConnect ivi
ty.
D-Al l oft heabov e.
Answer: D
Expl
anat i
on
JavaDat aBaseConnect ivi
ty( JDBC)APIi sanAPIt oaccessdi ff
erent
rel
ationaldat [Link] ttoaccessr elationaldat abaseswi thout
embeddi ngadependencyonaspeci f
icdat abaset ypeiny ourcode.
[Link] scor rectsy nt axf ormai nmet hodofaj avaclass?
A-publ icst atici ntmai n(St r
ing[]ar gs)
B-publ i
ci ntmai n(Stri
ng[ ]args)
C-publ icst aticv oidmai n(String[]args)
D-Noneoft heabov e.
[Link] choft hef ol
lowingi snotakey wor dinj av a?
A-st at i
c
B-Bool ean
C-v oid
C-pr ivate
[Link] sacl assi njav a?
A-Acl assi sabl uepr i
ntf rom whi chi ndivi
dualobj ectsar ecreated.A
classcancont ainf ieldsandmet hodst odescri
bet hebehaviorofan
object.
B-cl assisaspeci al dat atype.
C-cl assisusedt oal l
ocat ememor ytoadat at
ype.
D-noneoft heabov e.
[Link]
ivev ar
iabl esar estor edonSt ack.
A-Tr ue
B-Fal se
[Link] oredonSt ack.
A-Tr ue
B-Fal se
[Link]
cfunct i
onscanbeaccessedusi ngnullreference.
A-Tr ue
B-Fal se
[Link] eintv ari
abl ewi thabooleanv ari
able?
A-Tr ue
B-Fal se
[Link] hef ollowi ngist hedef aul
tvalueofal ocalvari
abl
e?
A-nul l
B-0
C-Dependsupont het ypeofv ariable
D-Notassi gned
[Link] hef ollowi ngist hedef aul
tvalueofani nstancevari
abl
e?
A-nul l
B-0
C-Dependsupont het ypeofv ariable
D-Notassi gned
[Link] sthesizeofby tev ariable?
A-8bi t
B-16bi t
C-32bi t
D-64bi t
[Link] sthesizeofshor tv ariable?
A-8bi t
B-16bi t
C-32bi t
D-64bi t
[Link] sthesizeofi ntvariable?
A-8bi t
B-16bi t
C-32bi t
D-64bi t
292.
Whati sthesi
zeofl ongv ariable?
A-8bi t
B-16bi t
C-32bi t
D-64bi t
293.
Whati sthesi
zeoff loatv ari
able?
A-8bi t
B-16bi t
C-32bi t
D-64bi t
294.
Whati sthesi
zeofdoubl ev ari
able?
A-8bi t
B-16bi t
C-32bi t
D-64bi t
295.
Whati sthesizeofcharv ari
able?
A-8bi t
B-16bi t
C-32bi t
D-64bi t
296.
Whati sthesi
zeofbool eanv ariabl
e?
A-8bi t
B-16bi t
C-32bi t
D-notpr eci
sel
ydefined
297.
Isanempt y.j
avaf i
leav alidsour cefi
le?
A-True
B-False
297.
Canwehav emul t
ipl
ecl assesi nsamej avaf
il
e?
A-True
B-False
298.
Canwehav etwopubl icclassesi nonejavafi
le?
A-True
B-False
[Link] st hedefaultvalueofby tevar i
able?
A-0
B-0.0
B-null
B-undef ined
[Link] sthedef aultval
ueofshor tvariable?
A-0. 0
B-0
B-null
B-undef ined
[Link] sthedef aultval
ueofby t
ev ariable?
A-0
B-0.0
C-nul l
D-notdef i
ned
[Link] sthedef aultval
ueofshor tvariable?
A-0. 0
B-0
C-nul l
D-notdef i
ned
[Link] sthedef aultval
ueofi ntv ariable?
A-0
B-0.0
C-nul l
D-notdef i
ned
[Link] andsf or?
A-Jav aDat abaseConnect i
v i
ty
B-Jav aDr iv
erf orBasicConnect ion
C-Joi ntDatabaseConnect ivi
ty
D-Joi ntDriverforBasicConnect i
on
[Link] sJDBC?
A-JDBCi saj avabasedpr ot ocol.
B-JDBCi sast andardJav aAPIf ordat abase-i
ndependentconnect
ivi
ty
between t he Jav a pr ogrammi ng l anguage and a wi de range of
databases.
C-JDBCi saspeci ficati
ont otell
howt oconnectt oadat abase.
D-Joi ntDriverforBasicConnect i
on
[Link] choft hefollowingist r
ueaboutJDBCar chi
tect
ure?
A- JDBC API l ayer pr ov ides t he appl icat i
on-t
o- JDBC Manager
connect ion.
B-JDBC Dr iver APIl ay er suppor t
st he JDBC Manager -
to-Dri
ver
Connect ion.
C-Bot hoft heabov e.
D-Noneoft heabov e.
[Link] choft hef ollowi ngi snotacomponent /classofJDBCAPI ?
A-Dr iverManager
B-Dr iv
er
C-Connect i
on
D-Tr ansact ion
[Link] choft hef ollowi ngi snotacomponent /classofJDBCAPI ?
A-St atement
B-Resul tSet
C-SQLEx cept i
on
D-Connect i
onPool
[Link] choft hef ol l
owi ngi scor rectaboutDr iver
Managercl assof
JDBC?
A-JDBC Dr iverManageri sacl asst hatmanagesal istofdat abase
dri
vers.
B-I tmat chesconnect ionr equest sf r
om t hej avaappl i
cati
onwi ththe
properdat abasedr iverusi ngcommuni cationsubpr ot
ocol .
C-Bot hoft heabov e.
D-noneoft heabov e.
[Link] choft hef ollowi ngi scor rectaboutdr i
v erint
er faceofJDBC?
A-JDBCdr iverisani nter faceenabl i
ngaJav aappl icationtoi nter
act
withadat abase.
B-TheJDBC dr i
vergi v esoutt heconnect i
ont othedat abaseand
implement st hepr otocolf ort ransferri
ngt hequer yandr esultbet ween
cli
entanddat abase.
C-Bot hoft heabov e.
D-noneoft heabov e.
[Link] choft hef ollowi ngi scor rectaboutConnect ioninterfaceof
JDBC?
A-Connect i
oni nterfaceconsi stsofmet hodsf orcont act i
ngadat abase.
B-Itrepr esent scommuni cat i
oncont ext.
C-Bot hoft heabov e.
D-noneoft heabov e.
[Link] choft hef ollowingi scorrectaboutSt atementcl assofJDBC?
A-St atementencapsul atesanSQLst atementwhi chispassedt othe
databaset obepar sedandcompi l
ed.
B-St atementencapsul atesanSQLst atementwhi chispassedt othe
databaset obepl annedandexecut ed.
C-Bot hoft heabov e.
D-noneoft heabov e.
313. Whi choft hef ollowi ngiscor r
ectaboutResul tSetclassofJDBC?
A-Resul t
Sethol dsdat ar etr
iev
edf rom adat abaseaf tery ouexecutean
SQLquer yusi ngSt at ementobj ects.
B-I tact sasani teratort oallowyout omov ethroughitsdat a.
C-The j [Link] .
Resul tSeti nter
face representst he resultsetofa
databasequer y .
D-Al l oft heabov e.
[Link] choft hef ollowingmanagesal istofdat abasedr i
ver
sinJDBC?
A-Dr i
v erManager
B-JDBCdr iver
C-Connect i
on
D-St at ement
[Link] choft hef ollowinggi vesoutt heconnect iont ot hedatabase
and impl ement st hepr otocolfort r
ansf erri
ng thequer yand resul
t
betweencl i
entanddat abase?
A-Dr i
v erManager
B-JDBCdr iver
C-Connect i
on
D-St at ement
316. Whi ch oft he f oll
owi ng consists ofmet hods f orcont acti
ng a
database?
A-Dr i
v erManager
B-JDBCdr iver
C-Connect i
on
D-St at ement
[Link] choft hef ollowi ngencapsul atesanSQLst at ementwhi chis
passedt ot hedat abaset obepar sed,compi l
ed,plannedandexecut ed?
A-Dr i
v erManager
B-JDBCdr iver
C-Connect i
on
D-St at ement
[Link] choft hef ollowi nghol dsdat aretr
iev
edf rom adatabaseaft
er
youexecut eanSQLquer yusi ngSt atementobjects?
A-Resul t
Set
B-JDBCdr i
ver
C-Connect i
on
D-St atement
[Link] choft hef ollowi ngisnotav alidtypeofResultSet?
A-Resul t
Set.TYPE_ FORWARD_ ONLY
B-Resul t
Set.TYPE_ SCROLL_ I
NSENSI TIVE
C-Resul t
Set.TYPE_ SCROLL_ SENSI TIVE
D-Resul t
Set.TYPE_ BACKWARD_ ONLY
320.I
nwhi choft hef ollowi ngt y
peofResul tSet,thecursorcanonly
mov efor wardi nther esul tset ?
A-Resul t
Set.TYPE_ FORWARD_ ONLY
B-Resul t
Set.TYPE_ SCROLL_ I
NSENSI TIVE
C-Resul t
Set.TYPE_ SCROLL_ SENSI TIVE
D-Noneoft heabov e.
[Link] choft hef ol lowingt ypeofResul t
Set,thecursorcanscrol
l
forwardsandbackwar ds, andt heresultsetisnotsensiti
vetochanges
madebyot her stot hedat abaset hatoccuraf tertheresultsetwas
created.?
A-Resul t
Set.TYPE_ FORWARD_ ONLY
B-Resul t
Set.TYPE_ SCROLL_ I
NSENSI TIVE
C-Resul t
Set.TYPE_ SCROLL_ SENSI TIVE
D-Noneoft heabov e.
[Link] choft hef ol lowingt ypeofResul t
Set,thecursorcanscrol
l
forwardsandbackwar ds,andt her esultsetissensi t
ivetochanges
madebyot her stot hedat abaset hatoccuraf tertheresultsetwas
created?
A-Resul t
Set.TYPE_ FORWARD_ ONLY
B-Resul t
Set.TYPE_ SCROLL_ I
NSENSI TIVE
C-Resul t
Set.TYPE_ SCROLL_ SENSI TIVE
D-Noneoft heabov e.
[Link] choft hef ollowi ngt ypeofJDBCdr i
ver,call
snativ
ecodeof
thelocal l
yav ailableODBCdr iver?
A-JDBC- ODBCBr idgepl usODBCdr iver
B-Nat ive-API, partl
yJav adr iver
C-JDBC- Net, pureJav adr iv
er
D-Nat ive-pr
otocol,pureJav adriv
er
[Link] choft hefoll
owi ngt ypeofJDBCdr i
ver,cal
lsdatabasevendor
nati
v elibrar
yonacl i
entsi [Link] al
kst odatabaseov er
network?
A-JDBC- ODBCBr idgepl usODBCdr i
ver
B-Nat i
v e-API
, par
tl
yJav adr iv
er
C-JDBC- Net,pureJav adr i
ver
D-Nat ive-pr
otocol,pureJav adriv
er
[Link] choft hef ol
lowingt ypeofJDBCdr iver,t
alkswiththeserver-
si
demi ddlewar et
hatt hent al
kstodatabase?
A-JDBC- ODBCBr idgepl usODBCdr i
ver
B-Nat i
v e-API
, par
tl
yJav adr iv
er
C-JDBC- Net,pureJav adr i
ver
D-Nat ive-pr
otocol,pureJav adriv
er
[Link] choft hefollowingt ypeofJDBCdr i
ver,usesdat abasenat
iv e
protocol?
A-JDBC- ODBCBr idgepl usODBCdr i
ver
B-Nat i
v e-API
, par
tl
yJav adr iv
er
C-JDBC- Net,pureJav adr i
ver
D-Nat ive-pr
otocol,pureJav adriv
er
[Link] choft hef ol
lowi ngtypeofJDBCdr iver,i
salsocal l
edType1
JDBCdr iv
er?
A-JDBC- ODBCBr idgepl usODBCdr i
ver
B-Nat i
v e-API
, par
tl
yJav adr iv
er
C-JDBC- Net,pureJav adr i
ver
D-Nat ive-pr
otocol,pureJav adriv
er
[Link] choft hef ol
lowi ngtypeofJDBCdr iver,i
salsocal l
edType2
JDBCdr iv
er?
A-JDBC- ODBCBr idgepl usODBCdr i
ver
B-Nat i
v e-API
, par
tl
yJav adr iv
er
C-JDBC- Net,pureJav adr i
ver
D-Nat ive-pr
otocol,pureJav adriv
er

You might also like