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

Java Unit 3 @72

Uploaded by

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

Java Unit 3 @72

Uploaded by

Ganesh Yalla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 72
A ey An 4 fe a collection of Similan types | et data. | Example TE we want +o thye the manmeS af 100 people then we can create an annay of the giving type thak can Moye top names: sringt annoy = nel! Sring Lieo}, thy declene an ose dataTypet3 ommay mane; -» dataType mears Like int, chon, double and bye te A ommagname Means It is an fdentifien, Example doublerd dake ; Ta java we can dectene and allocate posnory an arnay in ane Single statement. doublecz data = new dowble Co; jaene ool cay, Steve 10 flements. IC Eeeee eee ee eae ae Ee Beg te tethaige oma J Th Fava We cad initielive ore Ae na aectomation jab ta aqge= Les sirt. 7 Mene we have cveated an annoy named Ue aad iiatlzed att the value inside the Cunrty packets x Tq TVA corey each memory Location i< asgoctated with a numben, The numbey ty Known ap annoy index, x we can algo intiolize coats In JAVA Using the index numben Example iar EQ age = New intts0y I] declare an array age bl = iL; age G1 = 4 /| mm bialze ay oma age Rds 5; ageGi= 2, age GI = 5; 7 ae proqva NY) 5 ; class Awe te public static. void main Cstingca ang,’ tak acjy= net tot ST) /! dectonotion B instantiats oy cued =e; [J initiabisetion QT] = 20; a BI 2 Toy ad = 4) ata) i So, tot (ine OF >} tea. lengthy ies) Sy Stem, ot: priatdn (acs); age) age) agewsr agel) ageQd PP tt EI & Axyoy Inderee always start from 0. be dye Piste Slemeak af ar arncy ys at index 0. we Se the Sige ef an ammay vet then the hast element ef edhe oon \ndex Spel x The Mein advantage at aoe at ig we can deprasere hage no of Values by ustag stagle variable <0 that oreadabiti ty of code ail} be im proved. & The main dicadvantage of ermay is fined In Size. be Ome Wwe create a omnay then thene f% no Chance incveote/ decvease ot si3e base on aur) Veg iivement Acessin Elements gf omay ke created you. can actesy ® Once the Wwe an emneny element by using the name of an index enclosed beteeen a paty of Squsne rackets. | an amnay flowed Py R The Index of a array indicakes The position ef an Element os aller areas, ® The index of fiver element in the V7 is alvoys ‘’ Geno) and the cecond Element hog en Padex | and So O- R The index of Yost Element ts hays des than the numben od Element in the covery The. sy ates Poy acres? fing an ommnay Elemele ts array Repvantinderd, progeny class Accesring re public Static votd tate (Stvfingie9 oA ) L Pat Num = new INtSI), num 61 =% num Gd = tS; nud = 2S) num BI = 29 Num OF = $?; Cestrern. out: poattn Claveoy elemest numa? numtod); Sepstem: out: print! away Element Num(iI a nurs 01); System. ou. printhn(" Array Elemedh numis 4 numba) Sy vtem, out: printte ("Away Element Num@a: nun @:); Lystem, out. printtn(" Brrvouy @lement nun Gags" + ue aa); i \ cout pote Avyay element num{oI: & Array Element num (ijiis Ava Slement rum G9:25 rsa Element num GI! 20 prep Element num (ys? So apenations on ora elements zy * Allocation of arene in gave &% dynanie Rasic openectiory Traverse Te prints al® the tlements in the ooo eg one be one Add an element at the giver Pandey 3: veletion delete Aan element of the given eu Seat Learchep an Element in the aviag wShng the given index ice wpdate update an glement at Class “Ravenel i public static void moln(Seing’s ony) L inte]. 4 = - into = $243, Soy 183,19} ; index the given indes, Sy steen. out prattn(” the ommay flements ane") | System: owt. printtn Cinrosotia .* "J; ouk pute The osmay elements one 23 5 Ay Ut 19 tncention Clas Tnsention i public Static void main(Shingc? ose) Ne ink nes, pos=x) int intancd = new Fat (+17 Ceannuy Seznen Scannen (System: in); System. out. priatln(" enten the oomay elemeats:"); A Cink iso, ian, \+)y y inkooo Ci Si ya ceo nextTnt 0; System. oust printstin Coron flement before Yntention:’) » Po Clae i=; 169; ie) i System. ot: printin Ciatoomcia +" "); q pos =3; X= RY; for Cint i= Oy d= (pet) 5 t=) L int ar (41) = iatAvti 5 3 int Ave [por-1) = % System: at priatn ("\yannay Elements atten iasention:") 5 Ay Cint (=07 (ens i++) G System: ot priatin Ciataycid+" "); } System. owt: printin Clacavy (99); s J onct pute Enten the smay Elements ase S ae UW Away flerienks betve inSention QgQzs-rau Avtay Elements atten in sention QB. ay Fan, Deletion program fm poyt geva.ati] *Geann en, class Deletion u public static void maty (ening 3 ones) L tnt nes, *=10, flag =), doc =0; Scannen $= new Scannen System: in), Pot intomnca = new far fy; Scannyy, se Snew Lcannen C97 Stem. iny System. oat: printin (* fohy anya Elements") > Poy Cink (S07 12; i+) Ne Prom th j = SoonextTakQ); System. ou priacin (" ora Elements befwe insertion.) tyy Cint f=o7 ten, i++) ab a - womye Sqstem. out- printin Cintamnt 3+ A J fox Cint {=0; jen; itt) ip Gntoncis ==%) iE Flag =', doc = y 5 else 5 1 Flag =o j 3 3 if Gag ==) foy Cint i= does i; ieny itt) U eset) = tated); 3 System at: pista (\n annay Elements Otten deleting: ); py Cint 0, jen-u, ied) & Sgstem. ot: print Cistomnci3+ " "y; yy System out: print’ Cintosn(A-23); 5 dose GE Sy stern: ont: printinc” Clem tnt: note found"), j 4 } out pute Enten the oro ements Slo 1S ab as ney clemente befve taseretondeletfon sc wow Is aval : } i AIO Pemeats atten deletlon C7, AS Ad ea, 3-7 ME ANTONIE] =necs ‘nt {nJ; 1 SC=new Smanen CS8y stemrin); System out print tn (* enten pormnad Element :") ; Aa Gat t=0; jen, 144) 5 i Suv Clot 7204 169; 14+) getren- ood pant (intosntia+ ' oy Fas a1, G i bterky & 5 te (flag == 1) L System our printtn C'\n Element Found" y 4 else L " System: out: printta C'\n clement not found’), 4 udeput” earn the ona Clements Wes Quest oe The osmay Elements me: (@ team Ger & Element not found, uuceelaod! fen port gava. util Scann n; Class Updation L public Static void main Cstvteg CI oy) WE Seamer eters 16) Ine NES, %) Neanyeay Se ree keane Sipshemt «fos ta fyvawyr p= ater fat lady Seanneyy fee vets Kearieven Coy sheen fay: QypaYronsant: prinkte @o la tater ovary. Hlemect 2"); pw Clat ts oy leg er) \ * . Tatoo = se next tab Oy + w Systeay out priakdnl! \y @atey ore) Pleeneak ones), fev (fat te oy beng ten) t Syston souk epvink Clateomctsn! ")j \ v 4 u Syavoon: oat pvinttn(! \n Faken new eeenks ); d me Ssernmextlak oy fey Cine feoy tes) Veer) L ” TP CImeooo) chy © = Seosie ty che) \ Inbornmtty © % Ivealss yste No ut prinkte (1 aooray Elemente atten aploding?); Ay Cine be ey fens pay t System owt priatty Gatoomelt a ak pre earm the oomnay tlemenh Fy Ts ae es ‘Wre ammey clemeats one ci jf By aS Erten +e new Element. aS asmay Elemeats aften cepdede nig) s 4 (9 Asetgntng’ armay te anothen snty ih cued in java can be copied + another comey using Following ways * using veritable asetg x create a NeW ommnag copy each element ebhod of omnay. clone method qment but is of the Same tength not betten cay and x use the Clone ™ create @ Ne asM1ay of game spe rn MALY COPY o> method. ormaycopy © d ty copy a Subset of an ovieg. stae. x we Sys can be use pro gran) class Copyarney L public static votd matin (stings? ang) i facta OMNsnee PEC T LUIS}; inte a oovla= new tat Carte Reng th) - uy Pay (int 1=o7 icarnt. Length; tet) £ annals = omncd; } System: out: print dn(s 4 pre nC Cements of ori gina) omnay"); PovCint (20; tcomnt-length) i++) § Systems out ’ } sparen rout: priatty © | print tn Comitiat "5 gypstern: otk: pvintitn C elements af new oma) ay Cink tao, ios: Lengthy i++) wn System: out. printty (omni itias” °)) } 5 t outprre pee ott Element of otginob ony, Va Sh 4 Gements of mew oon Ge Q 3b Gee S 0 r yacnic change of onvay size ee in gava means citha grow oY gtae of the Vieg depending ats. * Dyaamic oeatan Shyante the upon * cuhile an Element is cnemoved -fyom an size must be veduce and usen veg tre mre oon art the oma 1B an element ge added ty aney then the era. size become stretth. @v) Fe? dleclonation af dynamic annay A\n osnay can be dectaned in three Vays, I: Arad c) Example tnt Pray ld HE 120} 5 a. TI Arey example fneca Avay= Lay, an Es a i | exomple int CT Avvay = Fug ayp- t | : ste Vs patty Ares +o use. to indices but at preset we append fon items to 0) agnamic ornay, —— Thene-fre h d ‘ nn the ‘i Ratatat ct the Mamie oonay site te foun and its capactty is ‘Io? Claes qe. € end fader capacthy slo Delete an Element chile deleting an €lemect from en array the nemoved) memove an element from dre end and automat ely stoves Eero ab the lash index. | Ge oe 8 of eet a! Aiae FAY MA BIL Mige Zz00 04 3R08 Bi Bt Remove (V) See Of. 6 py RR3L BISA = G2 RR NN TSM 3-0 Resize an osm cohen oserays have no dado ot the vight side af anergy which than take vanece sang MNMOY the method SrinksizeO -frecs Extra memory “FyaaBeee p Bab BAR Ray 22F Bao Woy ss08 231 Sink Sizeu \ 2 —» fndex values ss = 4 Element $ waa ——y addvess 3204 330k aan Bzoo Add cement can be create a fined Site onnay ae +o add Some Move elements usally iE tveates a new Thene ae nequered tn the oomey . oomey of double ste. Prog yan) class Array, private far ont dy prfvate fat count, public Ava Cink Leng h) L : a ann =ned intl Lengthy 5 o public votd print Away 0 L for Cint (20; ie Count ; i++) As Sysrem: out print Comeiae" "I, 3 5 public vetd fasentCiat elemenbh) t we Car: length== coun’) i fat nea aryl By Ciat (=o; iecounty i++) = neu int (2% county y new ay CiJ= ants; 3 ayy = ae ANY, axr Ccpuat+ aj= ¢lem ent, 3 / j SAE SN i ee stm Class cr& Sty v public Static vold mata ESringcs 0344) i Asvay number = 100 aay @, Numbens « insert Oo) ; num beng + fn Sert@r,; Aumbey + ia Sent 9; Aunbey + tn Sere G07; Num bey. pat Povag oO; outprt- to 30 Yo So. a of Arron 4 # Sorting i a way to anmnange Elements of a Dist fn cortafn orden “The orden May be ta ascending or descending orden at d Ascendteg oT The ascending orden amnanger the elernents ia the lowest highest oyden | we can pen-form gor Ling in dhe Prltostag unye I uitng sort oO method Q withoul Ustag met hoe. 3 usiag Pov Lovp 9 westng vsen de-PPned method. ustag sovF) cede we gavas ett] package provides sorkt) method + fh an ancy in ascend ing orden. xe TE accepts an covey +ype int, Ploat, double, loag chs hte program) Pom pore gavocut | - Arrays 5 class — Cortoomay L public grate vol L inecd ame = me Actors: sore (ornayty Systeo owt printtn U! elements of anvay ented to ascend ing orden. D5 d main Cstving C9 oy) poy Ce ba. auy w iatcd ganas! fox Ciat t= Oy Leonnay length; tet) { System: out: priartnCommayt va); Away € ts ray Elemeats tn astending ovden: © wm ag 2B Be 6F Yo 14, Class Sovk fat u public cratic void cnain( Sty es yw) BB} eh e ssdy oeking 9); Patra ams Ne tate agree! Cystem- oud: pratan ciara elements atten § Lt Cine t=97 jeomn-tengthy ir) L 4ei(jar 3217 jeave lengthy, a+) L ink Emp =97 ib (areli3 > ev(3I) v tmp = artidy otiy = avy(sa; ayveij = tere, 4 ] 4 Syatcem + out: print tn Carrtis); 3 } ooipese try V3.6, 8484, SS 70, FD. ustag user defined Method we have defined method Name ls Sort Arvag O class SordusendePined L public static void enain Cetringcs ong) ‘ int ty tot oxmaycd = f 1bS,-1,1 4; Systems Dut. prt arn ey oot flementi Ketre sorting’); tov Cizo; Teommay-lenath ; i++) Og stem: vu priathy (oowrg cia), SovtAnray Carnay pareve} fengthy » BAS System: ont. printty Clotten elements Sov Hag s\n") , for Ciao} icoomay length; itt) ie Sy ster sout> j ] ' private static void Sout Away Cink ore, tok n) priatin Caray cin); 2 foy Cink fel ien; ite) i. int Jey iat a = ave ao; ahile (¢3>0) $94 cornay C=) aun = oomay(y-10 5 4-7) 5 amay (IJ= 0% J J 5 awk pt oomay Clement betive Sov Haq (QPS Stee awry Clement atten aovting, pal eer abt ol 1, Ore tne elements 9 higher 1. ge CON Pperfrien Sorting tlbeuing ayy ovdent) method vides tne cre venseorden © method in Yevese ovden. ult]. Aas Collections» Impotk gave foo per gavae uti]: elas Corrdbevese fs public sratic vord ain (Sevingea ngs) e Integent omMay = [23 TE LOA GDI, U.4, 100,205} 7 fe Areeorgs sort Caray, Collections-revenseOrden 5 Sostern. ont prnta Cc cowie Elements tm detendivg sy 4 Are Sha if % “pet tring Comey); gs out put- ego ceae destending? a5 19,1018 28.1178 G10 program (‘etving) ten porh gave. util. Avrags, fonporr gava: uti}: Collections; clast sortdesestving i public Static vid main L ane. omy =Y many be “apnle", Grapes’, "ganann’! + y Arrays. Sort (stony , Collectivry srevenseOvden 69) 5 System: oct: priatte @) aeey Clements in de seen ling orders Avags toSing Cstomnead yy 5 C8tringl3 a4) 4 \ out pul nla, aaali dertegting ae te mango Gropey Banana Aprile ' | Seanch fav value in AWays arenas a aQaven coed ane task i te check Whethen a centain element 14 present in this annay of Mot In gave Example Tapuk— oncI= LS, WIA bi) keg ae output — true Topetis OMCs E -l 1,5. eh key = este ovtpet — tole. There ale veri ory ways ty Sanch v Rome ef Those oe. y. Linear teach onary te +ravensed sequentially and aluy in OT 4 Tn this List of evony element *s checked Pragrany ten pore gava- util. Areas 5 fo port java. util: sheam: TatSteam, class Lines & private ciatieveid check C! L akcd or, int teChecleNalue) boolean tesr= tobe, fy Cin tlements oy) L if Celement = = teCheckVelue) t tesh = hue; AAG brvecile 5 } 3 System: out prints C'Te 4 te Check Va bie " preent ia the amnay:" + beth); 4 public static void orain( String oo) £ int anc = L Sit a Ub lo}; int +CheckValue =; Cystem. ps : gSbem: 00d - printa(" Breage Arrag a: toString tox) ) - checkCaw, trCheck'Value), 3 owt prt Ava + £5, 11,9 Arr, 6 bo} Te 1 present tn tne omnes: true. 2. Binany search method Seach sorted ommary by nepertedly Ty +hes div? ding the Seanch Interval ty half. pegin Lait, an interval coven ina tne whole amneny af Soro Reg Ho teae Than dhe Ren TfL the value Wo fake dawn in the middle of the Interval dhe alg ofhmatse I tal OPED half, Repeastesl by check until the value 4 found ov the iatenval es empty. program) Import savae atl) Ayes) im povE — gavas abil: stream» SabSream} class Bingny seanch fe private. static vold cheek Cinta prvy tat tChecbvalu) i Away S + SovF (arr) ; fat ves= preveugt-binanggoncls Corn, toC heck\Valve); boolean fest = ves70 9 true: false) System. out priatin C To" Cheek Vale +" praseat in the ames s"atesh yy 4 public Static vord mata CString a anys ) c in’ areca = { Silay, rb, (OF; cal tat wCheekMalue = 75 Qe prem. out: printtn CS Avey: “a Avvagss te inter Check Cam tCheek Value); 3 j Out prt Arvo: 51.907, Vids to re 7 present ta the ame’ 3 aoe class Avay. $ AThe gava- util. Aways class Contoing vasrtous State methods for sorting and &eanching oooh y com poring OOMay , aad Hilttag orice tlements, ye These method overloaded for all prin ste typep | public static need [ot binanryesrch olgeet S24, object bey seanch He Speetfied amet of. obpeok Ryte tok, double etc. forthe specitiedl verliue using the bineny seach algorithm, Q- public static boolean cpteals Long 3a, Song C702 TE neteoms true if the too SpectPied may of Longs oe equol +e one another. 2 public Static _votd ill int CIA jntval. Astyn the spect fied tat value tr each element af the spect fied annoy of int , same method could be cused by all primitive data type ue public Statice void Sort object C14 got. the spect Hed aay of objects int fe natal evdertng could bp astead?ns oveley aocorvelt , of its elements. same method seal by all oth primitive data type. Tio —dimensional Aeros biabieslabg iL yn Toso dimensional ommay is the Simplest’ Fern of mrubked ¢men sie nal aovray x fp Wr dimensional ore cary be seen arwney 04 one dimenstorel ormray frreasien understanding fa Declaration Syntax dotatypec3t 3 aomaynane = new dedatype &I 9; Bovnple int CIC avs ndisgink E10 CRD, Toit tisetion Syatar avery name [row index) Ceolumnfadex’] = value, Example © aryCotCod= \y Aen LS ow dotatype-c9 cd aay nme = [value Qc, value Re aly {value RAC), value Petry} x00 ple. in-oaca ars L'a} Bott) coo) QD Avey Aecesring Elements of SP Aes an € DBmmor 5 in 90 diwensienal ern ty in & Plememen® oe ee cnreftened bg *07 3] whe 5 le mum BE} ead 3} fs the co um9q soe x frou idee] (Column fader) Exampl & int CBC arv= new iat (2G °0; Rope xntation ef raodimensional anay column © caluma | column Q Row O x (03) X00) xBIe) Row | xCO09 xP v0 6) bow Q x B13 x D009 x GI0I. pro gvam 2D aes! Rac eee scene {en pork gare util. Qaanen; class Taodimensional te public state void main CSringea ana4 ) i. fat vow, col, 7,55 int eNcICI= New intCiwI C10, Scannn ee = nen Ceannen (Sustem-in)y Sysrem: out printty C" Enten ao of v8 tay ene, Cmax to): y You =Se-nextlat 0; System: ont printtn (8 enter ne of Column fr omey (max oy"); Col = Se. net Tat OF System: out: priatto Ci eaten" Crier col) +! Prag Elements:") E Ay (eo lave, j++) t ; es dee C iso, Jccels i++) fe om cii(i1= ee next Tater; 5 } System: bod. peiattn( The aneg len’): doy Ciso) leven) 344) A te Clea; Jecol; y+) As Sy Stem: out poohlaCanfiitiae "); Sg rem. Dut. printlnO; J 5 3 out prt Eaten number af you fe VINA (may in) 3 3 Eaten qumben sf ca] Ay armnag (orax to)? 3 Enien 9 sora Elements wep Pp eynoww — The ayray tie \ a 3 Gas ¢ 7 et 4 3-20 Three dimensional Arad mension ASE x Thee demen Sioa! arma ig commplen Porm ef multi dimen Siv nal aAY x A Tree dimensional ommay Can be Seen ay oovneey, of too dimensional osray Ay eastyy vad er stendivng, peclanatio 9 Syatar datortype C3207 avrayname = new detatype Qa bGT; Sample jattacIed ays new intlw7 GIB oy Eniti Lizection Syatar c ayvagname fanay inded) (vow index] (Columa index} =vilue; Example ary ICI GI= 1; actestirg Elements at Elements iq tree dimensional ood one. Comma nefermed ‘4 xcta(5ITk) whe ‘i it the oma num be) ey J 4% the vou numben “Betis the clumn umben Example tak oae3ac3 avranew ink Qo) Ged (9; avy PIGII=A1; ntatioo ef 8p Axray column Ci Creare Aad. 1 ay 0 Row) Rows | Row 2 a3? pees piu's 213 Avag? progyam fry 3D aro _§ import gava* uti) Zanaen class Threed imensione} t public Static void maln CStrfngc oad ) ie ink awit 3c3c)d =new in¢ C27 CuI; tots tah ey qumdes ly tor Ciro; feds i449 t dor Geo; 5e4; 144) i tee er0, KE2j K++) L ari G9 ITE) = mG NUM 4) a 7 is Fy Cisco; ict; 144) t Ae C420; gon; att) L dy (k=0; Yer; le-v4) rE Sysrem: oud paiatla( ois f°) Cie TD 04 kas" arvliacia (ey 4" we) t i Sysrem- out: priatte os) 3 Sy stem: out. priattn or oud pale ud pole : forays NS votes Resize nan : The length ed an oma fe Bixed ome th Soaks whee cg vectoy & vesnable Synchronizakion # veebr & synchwoted Chere sy eu) armas not Synchye nized. {2 pen BymMante Both annays and Wehr: fake constant Hme 3 : me Aor retrieval and O%Gnment operations Siva 4 e An erly dog nh Tete eng adaitioast crevage while veebsy mesmve OF) addittonc! arwvege cubes gove. ona can Heald both primitive dedatyry iat, cher , Long rte. Wheat veotry CAN hole d only yew object, size toy, We oO) call its Te dand Se af tthe Vee whee ammo hap w-tength Sfaeo methrd , propenty thot otovieg ibe clengsth DimenSiory Avaty fq Jona Supports Single clime neionah armeg os well af multidimensional arnay 4. A vectoy hee no convept ef dimension buds we @n easily conthucl oveeby of veetove, Suppor fy geneviy Oe es Vectoy Supports generics te eqaune type satty tohile an array dots not Seapperl Senorien “2 a a Enport tance Tohenitancte in gave is & Weep Attucy ie tuiehe one! obyecl acqutnes all the propentkqy and behaviors of a ponent object: why use Inhenitane i a x FoY Method ovewrld ing *% Foy code Yeusebility Tenms uted ia inheritance ge class pa class ig & grorp ef abseet cahich have Common pro porkep x Subclass) child class The class that taholts from anothn class a Sapor class/paneot The class being inhertbed frond zw Reuse bili : you > ene Pietds aod method of evsittng class chen your create a new class. i Types of fohentiaate |. Stagle Iobenitaate a. multiple tahrthane & multilevel tahenttance ue Hrenanchical iahoritaace in Hybrid in henttance sin le tahent tance ea: strg le Iahenttaace one poate | class Erlends anathar east In T etase 8 a class A. claus A te Seupery clastR Extends ont clas and clas BH progr class Ani maf u void eat) Subclan, t wt A ‘a System: outs pratloc cating ); ry j ds Animal L class OF Boke Leysren ont priattn(" banking" AS Class Testinhou tance u public Static void mata fi acs 7 O44) Dog d= need boy ga ede Hy dv bank © } a wtb} % Ss 4 j ortspute bankin eating. a. multiple inherttance sequhen one cass inherits mvceLtiple clones tle tr Ranma oy multiple inheatkante ae el iy gave x multiple inheritance tH nok aupporhe din gev [clase 8 } 3. multi level inhovitaate a chaln af tne kano) yt bene UK ntheo 4hore ' as cauttitevel tahoritante progvam) class Antenol noid catC) { system: out: priatta Cs coding "y; +E Class be eutends Animol £ oid bank O { syste oneuhpriotdnC bork ig "4 j class bovby dos extend bog Noid Weep O { Sy Stern ot printinC weeping”); + } Class Tesh public Static void onan Shing 9 ory) y Babsbeg dane Baby bg 0; d- weep; d- bonk (0; d- eat C5, 4. Hicnanchicel inher’ tante, pre clasies inhenity & Single chen too oF ™ nchitel inhenttance class it i taoun af Hiore class A pregrvan) class “intimal Lt void eater Lsystem: out: pria tle (eating “v4 3 class Deg catends Animal L void benkt a System out priate C ban Ring “); 1 clay Car fatends Aart O void meow CI £ system ont puttin meowing © ey 3 Class Testinhsuitane C public static wid main Cfhingcs ongt) Cat c= new Cato; Cc. Meowl); i IN er Ren c.eatov $ i oukp whe meouing Se a inherit bante In Java paltple aad hy brid through inter fare on ky, [esse] ame) lene] Lig brid inhitance ig & Gmbi ig Stepported notion af both Single and multiple inhenitante Re ae eect Tohibitin inhouttante of clos asia Maal =p = d ia gov Used cfoy vestvicting ¥ Paal is & Fey cxovd can declone variable , aretha Some Panctioneliticr 0° and clasje with Pinot keg inheritane %° ie yd’ to fal lov dhe 3a d classy, word. uch dee tome methods x purty coithie ficiad Beeo? dhrughtont alt the x The main intention of content of the method fhrw by ang out sfden prograra class Bike L ined void yuol) L system out: priattn «" canning"); 4 wy ‘onpleanenteiny derive onatleing a method fiacl thal lo nok be changed 1 clast Hhada extends Bile { public Static void moun Caring CI oy ) bE pew Hondate- rund) Application af reycaord X pr) a The SUPE? pegevord is mefforence variable chicl, ( te used t ne fon immeclate paneat class, x Supe, 9 tuted ety favoke ionmediate — poment clast met lod *® CuporO iy Agel t> iavobe immediate ponea} Class Canstyuetoy: pre 4 yay) class Anfmal /! super class Cpanat) { void animal sound 69 System out print Utne animal maleey sound’); 3 } « class Dog extends Arterol |} Subclass (child i Noid animalsuad oO £ Supn: ant molsound(; /l cold anporclacsmethed Sy stem, oud printin CU The dog 7s! bows"): J f “23 Ww public class mMiain L public static void main ( Sting 094) r Lu A\nimal my dog = nee Beg 07 mydtog- caine sound ©, 5 j output I oweat]e peg objec The animel make a Sound The deg Saye: bow. Oca c Met burl clispottoly ) Runtiine rely Joc Kopote h, 1 the mechants py ne rnte rye: hoe ig cegelved os abt ‘te an overridden method aug time insleod of useg The principle af variable can 2efer te a Subclass overridden method stirne - Cocapi ave. Sup enclass mePfenence object sh me solve. cody to ey oun time Advantage x Pe allows gava + support overoislig ert obtour & Clag + define methods Ane be shamed bt ath tts derived clang cohile aLlocing dere Sub clagis te detine $hetv Opecttte program) class “Apple o£ metheds oll cho ts noid altsp lay ¢ ) de Sy Stem.ouct printiin C*anside Apples"); 3 j lage Ranand Giends ‘ we . “yotd dtaplay OH ovororidieg clisplagy d ; uw Systems aut pratt C' gaside Renan De v ’ 9 i class Cheny Btends A pple G el adi display O void \s ploy © u ovoid iy isp t t Systteoy but: pratt C fatide choy 5%) 5 a3 J class Fruitsdispatehy 1 public stotic void caain( Sringes ont) g Apple a= ned Apples /| obsect of Apple Ranang b= new Banana; {/ obpect of Bainang Choo ce new chemy 0; uy obyast oof chery Apple vey 1 tabing Dedperece af Apele ref = gy veP. dis poy Oy vef = i) ves plisiy oO; yep =o) vefe dis play oy 4 biceps Tnside Apple Inside Banant T™ side mie A 3 Choy > ) THIS regres creates one supenclay Apple’ cind toe subchasyer af it Chanana and Choy). dubetay barané and chesmy owoide the clisplay ¢3 decbme in Apple OKO 324 posed A class ohich & decried with the abstrack abstract class | key cord te Enon Of Absrvastiss Absrvacttor ding ne ienplemecttem ig a precess of hi 9) ony hunetionatity + Tne USO, | (oe) ewenticl ning dy the WOT details and show Tr Shows onty and hides the iatennal, detoils . Example pe the text and stad Sending Ems cohme gou ty ono the qaten nal dne emesage - you don't delivery, ob the me Mage prove esting sane one too WHT to achieve aba tation in Tava 1 Aba ratt clas 2: paten Face fF be. declmed ath obstrack beytond 5 Ab abstrach clays mut t can ot be instantiated. tb can have aastratk and non abstract have constyuctrys and dtadic methods ake 4 Tt ee metho dy =p tte On > tt can have Bnal methods prog ran) abstvactclas Bike L abstrack void van; 4 clas Handa extends Ri ke a wold yur t A System oud padtcts (" yuontng safely iy } publis static veid mata Cottage ongd) L Ripe objenews thadat; pbj» run; J 5 owtprt yunning aapely, ehantim ach feve. Thkerface va ig & MEM The tatendese in we abstvactton- cthyvee ve: Theme Ore mot br te t& ted to achieve abstractton. pack He ml ple 2. using iarorfare t> implem in henibant] tn gave. 2. ct wy Wed to aubieve loose coupting peclanction ef intnface gonss te USE intorfeat & Santee fatenface — intenfase name L } Pelationship bet between Class Closes and iatorfates Wines srrends anodien class , 07 intergate extends anothen taten fare but a class eenplemects an intenfate class Tatenfare “exten \ ienplements Extends, Wogan) interfere printable Ae void print; t Clast A fmplements printable public Void pink is Sgstem out priatln C" Hello’), q public static void main(String C9 orgy) L A obj = new AO; Obj + prinh OD; j ouctpwe Hello a 3-31 le. faten Part ep why ¢xtend one ponant Multi AY gava clay cm ° ss net abhoucd Totenfares oe chars Ltyple ant Cloorry inhori tance one. howeven yalerPace Ca Fy be pormant Intenfate Exarople. if the hockey intenPace implement beth — Sports and event. ad move Ahan ‘he program) Inten-face Fiva binten face i public void ongmet hod 24 [Jinten face omethod 3 tator fate Cecond inten fate L public void mg ethenenet ed ©) Jlintorface method 4 class Demo implements Bistinten face, Second intertare ie public void mymethed oO ig ‘ (8 Some deer" Qystem- owt prot anl Gine de} y public Noid cag othenmetind ; Mo): & stem: och priatis ("dome othe fexh 77 3 } Class Main - . rag la Od public Static roid roa Cig t Demo my abje mymctrnd 4 my abj = TEV Demo (>; my obj - ony otheymetned Q; ontp-e Some text Some oth text- mR rn aera 3-32 % AV} intenfare dechrne {£ Known of nested Eaten fate d cithin anothen intenfece *% “The nested intenfate mest be mnePinned by the outen interfate % chen sy bug Canim Be atte wed dinectly, Syntat fatenface tatndanenane ie LntenPete Nestedintenfacenane I ae Nested intr fete Ome decked static tmplecitely (9 default a Nested intufere declned within an intorfare mut be public. | pro grad) | clase Animal Interface Activity ¢ void movel); } 3 class Dog. implements Animal - Ack vty ft public void move 0)! System cub puntn C" Degg can walk and yun"); $ 3 pecbiee clas Terten ts public stotcvoid mofo (String L Dog cle ones: Dog Oj dea sme; ca oy) 3 I oobput- Dor, ean wedk and run Defeattmethods 69 totorfare 222 & gava provider a factity +b treate de-fawl- Methods ingide ‘the latorPece. KMethods which Me defined fault are bnoen os gagide. the interface and lagged with ded deqandtk methods: ; & These Methods oe on- abstract methods. eee token Peeve. Sagable c defantl wotd sey) I default method i Sy avem: out: priatlin ("Hebe dite ts detail mend) } Void SaymneC owing 89); |] Abstraet metined } peeblic class Defeatmethock Fonplements Layable e public void aymnare (‘String msg) & System occ print ta Coreg) t peeblic. Static void main Sing e4 arg) i. De-fautltmethods dm=new De lawttmethodad ; dm.cay © i celLing defer method dro dayruve C" gover p> leah Ring abghact med hyd 3 3 out pte Hello this & default method coor ESTE p. ~ = camee— 584 Skatic methods ia iokevdate 7 hods inside *% te can atte dePine static ME the interfare ® Static methods ore used to define ect ti key method. a ke we Trey Oe decked casing dqatic recy oe a to the memory along coith coil) be lottdledd fn Prog yay) fn benfate mygintorfare L public void demots; public Static void display O) L Syrvem. out: priatlnC* Thi is Static methed "); 4 t public clact Tatenfarere E public void demote) fe ay C Inplemeats desromethnd"); Systear ach priat 3 pucbiic Sabieveid main CSHFOGLI HD C Taterfacees obj sarees iatovfaceexor; Obs - demo; My iat A . ny atenfare splay Oo; R 5 i out pk” Toplements demo method “this ig the static method. The diffenene behaeen State and defaclh we can Cell the dtatic method methed & - fate while br call defant tustag name of the faten methody eating abject of Torplementiag clay “SRY | a eT ea 3°35 \ tactktonal tortercace % é\r tatenface that contetns Groetly one Abstract’ method (& Enown of cPunetronal interfate x» TH can have any num ben of defaat , Matic methods but cen contain ont. one abawack method: & Punctional tatenteace te also Known % Stngle abstract Method intenfale ww TER a new featme fn Java aohich helps to achieve functional preg vanming appoah: pregyan| faverface Sayable i vold fay CSbtog mig); ; | } peblic class Functional taterfare implements Soy able public void ay Conta mas) t Sys fern. owt printty Cmsq) ; 4 public. Static votd main CShFrg ca oy) L Funettonel inter ate Pe = new Hynchorelintrnfote 0; Re. soy" Weblo the’); 3 § outp wk Hello theme. Annotakcong Annotation in gava ome used to proitde addi tines fn Pormatton “Thene one theo ty pep 1 RufLE in Annotation. 3. custom Annotation Gy) user defin vorel bull in annotottors in J9”4 ed Anaoie4org Thine ane de a» @ownide +e Supprese wiroining « @ Depy i @ override This annotation assorey The the Zubelass method t& evovrding method #0 Compile Hme ovr ocoeo 1k @ suppennennings Te ty used tp supprers the ampilen. b wecated ere @vepeated annotation mcke Hat method fs depreated 4 Eanpllen’ pints: vonniny ne pment class coerun nay imesed by Custom aAnaotattorg shine ane dhree typep tection 1 nesrteenn Annales Ue An annotetton that hag nb markou annptottons Ex @ inter fare mg anne a. Single value naotet? AN aAnaotectirn dhat hal 0 SPni value aA nastadion axe fatenrfece ragoncetetion {i tadvalue 0; i 3. Mab value Anneleton on annotatron that has ame than one methed ts called mulbttvalue Annototion. a @intenface mgar on int valuetO5 Crving values LY, Peving values tay } methad fg cabled tattion F y ne method | talted

You might also like