Java Assignment 1Q To 10Q

You might also like

Download as pdf
Download as pdf
You are on page 1of 21
ing Names M:Showath Kumar Palle: = 100921861013, Assignment | eee | 3)00Ps Concepts. Objed Oriented Progromnng (oor) 1 6 programming poracin bosed On the Concept of "objects", which con contain data ond code dofa in ithe form of elds, and Code ,in the form of procedures (often kro) 04 meltnods)* A Common feabuse of the objects ir that procedures or | methods Gre attacked to them and con aces and modity the | Object + | tObjed is On instonee of class | *Okjeutt Sometimes comespond to things found in the veal usord- + Sometines Objects repreeat more abitrot entitios, Like an object stot | pred: on open tle, or an object that provides -the serviee of tranlatig meourements fom U:3~ chitomasy le metre | | Object- Ovieated Programming © pasxadigm thed proidey m j concepts, such a4 ‘Tnbertante, Palyraghitm, Abstracken ,Encapndition, | Tohevitance > When one object acquires alll the properties and behavioun of a | posent objed, it is known o4 taheritane - Tt provides code vemabilty | Gu wsed to achieve rurdine polymorphitm. Tnheribance i the Preceding in which O%€ clays inherits the attributes and mmetheds of another da Palyneoxphiso The ability oF an abject te perf diPfeed actions bad on the contest 4y called polymonphism «There ore two Lupe of polyenes phi i tb Compile Tiene Polio yphisen- di) Ran Time Polerorphisen- ‘Scanned with CamScanner | «Compile Time his i Gmpile Time Polymorphiso ¢ / DE is abo known o solic po noyphisra. Thi tip of pelyerarphisn it achieved by fuadion overloading ov opereitor overloading: ) “Bun Time Balymouphizm L Tk & @ process to whith a function call 4» dhe overridden il, 8 yerlved of runtime: This bye of polymenphiem te achiwed by | rrethed overniieg. | Abstrackoo + | Absbodion i at process of hiding the fmplemerdatton detail fram the wer, only the fuochionalthy will” be provided to Ue wren | | Eocopsulation + i Ereaptulation it a methontem for vovepping the dola and code ; ocding on th doto. ogee oo single nite 2 Control Stalernents ete Toe Tava compiler eneciter the code from ‘ep Lo bottom the stodemech tn | the code are exeucted according to the order in whith they eppeny | Howeret, Tava, provide) statemedts frat can be wed te conbel the ous 0} Toxo code such staternerts one called conhol tow statemedts. Gy te one of the Rindamental feats at Jaye which provider a srneoth fa) of program: | Tana provider three Apes of conkol statemedts. | DP ecision Making Salemeds | iy TR statements | + Siomple if + id be cif abe tf ee tolerant. ‘Scanned with CamScanner I ate a ee @ ony rary i tor too Gs wohlle Loop FF) dlo-wahile Loop |@ kang Stotemnendts ) break 5 lh Continue | Gi vehiro, [Deckiton Making Stadernents : Decision making statereds deéde which stotement to enewih and | whan These stotemedt ewaluck the boolean eprerston and coatrol he program tow ckpending upon the reult of the condition prodded Thee ane tina tre of Detisign Making gtofements. if and garth j siege iF The iP statement debermines whether & tode should be eneuadted bared oo | a epedal condition: | Sydan | HE (condition) 1 staternerd ‘ | | |-tt Statement + Statement | i if statement te wed te evalust a condition-The coabol of the progmam i diverted depending upon the speutic condition: The condition of the 12 stutemerd ges a beolton volua Tey tue ov faye “There ave ty ype of if thoements. “citing if GE che Gils if cbse Pf Ga Need 8 ! HF che + Dp the Condition specttied ty tue | the che bloke & gneuued: rthe if block te executed Otheruie ‘Scanned with CamScanner if (conditon) stobernestt 5 ee Stottement 25 tt cheat Lt the condition specified ie tue, the if block sill be executed y otkutie 5 Ht will enters tle ee if unl the condition te trae -OF Fone condition fr tue , # will eveaded ebse part Ziq tui Hew will be | muuthigle ebe TE stadement. Syohox? | 12 (Condition!) | hana ee iF (Gadstiont) 4 statemest 2 } eho bent { stadtment on; ' | Noted of | Ty noted Hf stotemech dhe it stodervent can condoin a it ov it-ele Stodemend intide another if or eye if gdofemend - iylow i iP ( conat'Hons) i i f stademedt ys a: - 18 Ceonditenr) . A ttabemend 23 ‘Scanned with CamScanner Booram + IIA program a0 decision raking sadtnents it pot: clos THStob, {public siete void main (Shing og J) { ied % 10 y YEIDs If (x+y p20) Hstenple sé — and mya £ started haves 1 Systemeut-priddn(" my ie big; if (a >9) eae is big) dhe iF(y rm) IFIP edie vw { eysteooud -pricite (* ix big") y } ebe (he Wye ard id chest | { Syseenoud- putt (° Corey Detecked") 5 hh Stostecneet eign rcee eine alas wo to excenk a block of code Omong many alternatives Sydon suaitele ( enpr2rston) Licore voluet s Sake enend ¢ break; cost valu nt Stotemetn; ‘Scanned with CamScanner | defaut ¢ | fib of defoutt | boop statements + | Tn programming, someiror uie red ty eseurk th block of code: [repeatedly chile tone condition Oolustes te due, loop steseemerds o¥ ted ty exceate the seb of inelouchiou in o repeated order: En Jawa we have 3 Loop stotemedds- citer hoop diy while Loop cit; do- while Loop | dor loop = | Dt enobley us do initialize the Loop variable, checl the london wand tncrerned! Jocdecremesd in a ag lt or of codes tle oie for Lonp only whan wt enol “ferow tHe pumber of dimes we ward te enecubr dhe block of code. | Spd: | | | for(lothiabizaton 5 condition 5 incremend/deerement) | | |tabile Loop | “ticle loop t wed tn tHtwote the number of stotimedts multiple Atmes- TE | | aot don't know the number of Hevocions in adwance tt te wetommended | fo ure a while loop TH tr abs Keown ay the ~ enhy conhelled Loop". Syphon while (Condition) { Looping statemedd ii do-whtle Joop * do- while Loop chek the condition af the end of the loop ofter tree. the Lecp stotemerds: When the no of Herotions axe not known and we hawt exeeate te loop otleast once we con Use do while top 7 ls “et tonled Lap" ‘Scanned with CamScanner | Kamp Stotemerte > | Tamp shotemeds ave vied to chante the conbel of the pogarn to the Specifies stoctemedh - Gn other words, jump cholermends transfer the enctachion codhol to the other port of the prograrn: There axe 3 types of jump [teed fo Toxo. | cy toreah — Gt continue city vehurn. | breads ¢ [Dn Jono, break stotemendt is used to terminate the execution of the | neowsst looping stadement or cuiteh Hahement: The break stalemerch is widely ured with the stich tlatemedt, tov Loop, while loop, do-wbike top] | Syehow | break; | ondinut + | The corinue stotemedt doen'd break tte log unlike break statement | whusos ek skips tHe specie part of the loop and jumpr to dhe nek Herathion of the loop. ienenediatehy Continues rebure The vehivn stottement te mainly wed in methods ta order te ferminak © method in behveen and whire back te the caller method: ThE an! Ophonal stoitement pls yebun, : So Scalar: bila a eal ‘Scanned with CamScanner we 30 Dikfereoce Belween Bo th c | Cre TJovo. 1 baved C*4 language is beved Tove pogonng On Beer (Fe, Beste on the € Language: dorguage ix bared on | Combined Programming beth € ard Cit. | tonguog.): IL — Tia pocedaral | Gi an clject i © pure objed| dorguage Oriented Language oriented ea UE aes the tap Bases Ate albmap Tt alo wey che doen epee | approach jensen opprach, | Dynami or Hakte [Tt it a thee prod Gk abe a vote Dito yore | ring Loeguoge, \r pape lagen. peg oe Teode Exeeuthon. The code tr enecuted “The code % eneeuded The tode tt erect ee ay by Tavs, Vishal Hodkne (Ive). | Pla en Depend Tie platbin ded Ur ie platter Stic platbevm -end dependent - lndepended because | Bie | byle wode. TH user o compiler GY abc wes 0 comp Tora wer both the | only te tronclote de only to Hoarlate-e compiler ard tdtpet Code inta modine code info machine ard itit aby krawn language onguage: an indvpredecl | feet | Fle Germiailing 16 queues tty. se] OF g nent sere Te geocriles day | L. | ard bak Hey be Hes unter os epod “have ane 33 Hepwh Thor att 60 Kaysone Thee aie 51 fe 2 ap | | inh C lorguage. lin he Cat longuege tn tke ‘ova largusce.| ‘une Fie eden he source Ble hos hos fhe source Ae hor the toune file has (8-0 exdtntion. (@ -epp exdtation a jana havin | ‘Scanned with CamScanner ul Yor and Objet. Choas : +A clon it a geup of objects which howe common properties «Th is \ © template ox blue print thor which objeds ove created: ia Logi eatity which canndt be physical: | +A clos in Jove contains | 0) Fails Ch Methods © Conrbuconr Gs) Blocks | Wnleted claw and Dderface, Syctos | clans | { feiss; | methods: | $ | Objet + An object in Java i the pI ical 0 well or Logical entity + wheteas lo dai #0 Jogical enkty only. An entity thet hos 0 stale ond behovioural krown os an objec Gxs Pen, Table, Boole de +++ + Objed con be tongible or an intangible. | hn objed hos three characteristic, dy Stote = | Reprereds the data of an abject (value) | cli Behosiouy Reproned s Ihe bebawiowr of on abject (Lnchonality } [WS Sdendty Ay objec) ieledthy is tpically implemented vio 0 unique ID: th value of an Tp i: cot visible to th exdeanal wer: Tt ie ured inte nally by dhe JVM to dently Coch objed Uniquely. ‘Scanned with CamScanner “IA. program 42 demonchade class ond objet | clay Shdend | find ids | Btrlag nase 5 my > } Class Tent Shdend { public state veld main (Shey oC 1) T skelend sie naw Shedent () Sls fd = 101; ; Siemame = "Mego le ae Syten-out prictln( si «id a } } 5} Constnetor Ge ix ao Special type of malhod which i: wed te initialize the object. | We we Conchudoy fo inrtanNate an object | Charadevities or Heywordt of Consus 4 St. Maem) ; = Synitoctically © conchuctor looks Lhe a method. + Socne came 03 clossname oy cox [+ Garber rmt have no eypLat achntype | + Conehedor cannst be obrhod, Stoic, Anal and synchron red | s Conductor te called when on ‘utaree of 0 class t ereaded. nn tne Sime ob colling enstaator eerany for dhe object ie alloted tn the mmtemeny « Tf there ie m0 Consduchy available tn the clow.in such cose Java cornpiler provides © default conshneehor by debate: Cit aie host hes concructou in ‘Joa, ‘bey ane (ynlo eiguenest Coos trucdes “ii Posomelt ited Conetnathor - ‘Scanned with CamScanner | las | neo Shideak(r21 4 “pige) | Sediiplay(); | Ge dizptoge)y yt " ‘Scanned with CamScanner Covstettor Ovevtoadting to Jowo fa technique f howing move thon | one Contactor with dif forect poramety Bete. They ox orrerged ino | tang thet coh Conshudtor porfbrees a differed tasks -Thy are differaticed by ae compi bev, by the number of paromedta tn che Lt and iHelr ‘ypes | Program: Wa Program 26 Conchchor Overload ing class Sthidext Ting ‘d, ages + Caos Ove lnocting + | Shing name ; Studest( tat 1, String 9) fiosi; Mame =n; {id 27; Nome = 9; age sa; 5 void displays ) | 3 | | Student (int i, Strag 0 y int a) | | | | 4 Sie deen ouch priate (Id + * prame 4" "soge); public stahe vold main ( Striag ange) 1 Shdent $1 ne Shideah (at. Magu "ys Adet 82=nao Stided(asr,” PSN) 5 | Sr Aisploy () | : 4 | yea: ‘Scanned with CamScanner 4- Define on Array and iW type) demonshating one and tivo dimensisad ey & Array: «An ovvay is a data strudure which holds ae dalalypes “Anay 6 a user-defined dotalype which holds similox Lupe of data: An oroy ik a Collechon of simnitox Lupe of dlemealy which hos cordigenus meray Lo tation. “An in ava ts inden based, the frst elernend of the on stored of the of tnden, Second element it bajed on ond stored on ae index 4 and 80 on. Advacdogy + © Code Optimisation > Gt mahey the code optimised, w% con retrieve ov sort the dito efficiently * Random Accens ; We con get any dala located af an Tye of Avays : . Single Dimensional Avy = Muth Dimensional me inde x position. Single Dimensional Array ‘ Sydon t datatyp. CU Javy; (ov) databipe ow[ J: Initialization‘ databipe anayvarioble = new datatype [size]; i ‘ FOQvaM ; If program dy derrenstrale single dicnensionol orroy cloas SingleArioy 1 pubbic stodic wid main ( Shing oll) { int of J= {'9/90,30,, 40,60} 5 fov(ind i= 03 ica: length si) { Suotennauts prindtn (a7 ])§ j ‘uti Dimensional Ary: [Data is stored in crows and caumns tored on inden. | Sylow dota pe CIL J vesioble name: (or) dattaliape vorioblkename [ JC]; (ov) dalobape CJ vaxiahblenome UJ ; Deguan’ ITA progom to demonsbotle mult dimentional orroy © Clo MultiAna © { public stotte void main ( Sting orgs J) fie awl IC} = {11.9.3}. fous}, fuus} ps tov Unt fro; f<3; las) { tor Ciad J205 fea: jot) {Syetemauds prid (ons t9C3) » ); ytronl prio (); pe 8: Define Inheritance and dupes of inheritance with an enarnple program. = Caheri tance: Inheritonce in Jove i a mechanism in ushich one object acquive, all the Propevhes ond behaviours of a porert objtd The ideo behind taheritunce in Javo i: trod ux con creofi new does thod one built upon eulthing clos, The “erdends” keutusord indicates tha you ane rroking 0 nen cow that derives dom an Msheg class. Types of Inheritance Theve are three U of inheritance in Java. ') Single Inheritance 2) Multilevel Enheritaoce 3) Hevorchical Tnhevifance. Bogle Inheritane + When @ class inhevite another dan of it known as Sioale inherntonce ( : class B Program: Md Program on Single Unhevitance clos Animal t void eot ( J { Sustem-ouh prtatle (” eatirg*); Clore Dog extecd: Animal { void bak ¢) {Spe out ped tn (° Barking”): y clas ingle tohert {public static void main/ String orgs (J) | Dag d= nus Dog! \; ds borkt): \ \ d-tott); a Multilevel Cnhevitance When there te Q chain of inheritance tt & lenown ay multilevel inheritance where the child chor became, the porrend of the nest level. [clon ¢] Program : TA Program on Multilevel Inheritance class Animal { wid cate) { Systeenoud priddin (" Cating "); Clous Dog extends Animal {void bask } { Systeensoud-pyleddn (" Barking "); j Closr Baby Dog ercktndle ‘Dog { void weepl) { Systeen out pattie (* 1, it | clos Multinhey; | { public state void main(String ores J) { Baby Dog d= new BabsDaa 4 d-bak(); decode y+ drweep} i P leeping) ; | | | | | Wierorchical Lnhevitance > | When too ov more classes inhevit« oO single Urs ik is krown os hievorchiel inhevitonce + | clos A | clon © | Prog rae: | tA program on Hievavehical Tn heritonce | clon Anime | { wid eott) | , dyleine oud: paid In (“ Eating * } | clous Dog extends Antmed | § void oak () | { Speen out: priat to ( . Basking ") : 3 cloys Cot extends Animal { void dead) { Systemouth printla (* €oden by ‘Dag "); ,/ Choss Hevinhewt | { pubLie stodic void reain ( String os J) { Cat c= Nes Cot l); Dog d= nw Dag); €+ eatt); d. bouk¢ ) 5 c- deodl); Q. blhoal % overridling ? Cxplain with exom ple pegor: a& the same name, Same porameders or signature y And Sore ‘rehurry Lype any by which jouo. achiwe Rua Time Fotyenorphisre Oveviding % a. Peale dhat allows O subeloss ov child ULons to provide specifi ienpkenend ation of a. roethod thot ts dready provided i one of uf super ~ closer ov parent cla ues. Lihen © method in o subelan hos O O method tn a Super- clows, then the method to the subelors said | ts override the cocthad in the super choar. Method overriding ts one of He! Program : A Progrom on overridling the method. | Clow Porxent | 4 void disployt) { Syrteen ouch paintiln (" Parect Clos") ; } clans Child esclends Paront § void displaat 1 Surtern. cud. prio (” Chile) Clans”) } J tory Main { public stoke void Frain (Sahg arg J) Pp: iplay Cy3 Porent C= nu Child); C-displagty; b } (0. Super keytuerd and it: wey. 4 -super hegword in Tova is a reference variable which te wired to refer immedish | part clay obje oct | * Whenever You creale an instance of subclay, On instance m parent clous is created implictty which % veferted by Super veference vasiable . Use oF super heyuaord « Super’ con be wed to vefey immediate posond dloy Instone variable. We Con we “Super” Keord ‘te occays He date member or feilol oF posend Jo, tis wed if pod dou and child clos have the same ¢feilds Program: class Animal { String color = “white "s } cloys Dag extends Animal { String color =" blade” ; void. prinh Calor) { Surtten outs putda (color) s Syston. out: printiin (super. color) 3 [Toalting port Ov Supers dow 3 | chous Text super { public state vaid main ( String angst 1) { Dog d= new Dog (9; + paint Colort ); } *"Sape con be vaed fb inwhe ‘mmeddote parent clo method | The super heywotd can oho be used t) invoke potent clon method if | | , | should be used if subclors contains the fame method a4 poserd clors.Tn other woord! it & wed if the method ts overridden, | | i + | Froqrasn ‘= tA progr on super hegwod bo invoke posent Lao method. clos | { void eatt ) yee (* Costing "); } clos; ‘Dog eucttadks Ani ‘al {void ett) {Syskeroud «pride (" Eating Cod ‘); void barkt) { SysHton-oud prin (" Borking®) Void Work () { eott); Super-ead (); baxk(); 4 | clos Tertsuperd { public stohte void rrain( Shing ves J) { Dog d = new Dog (1; d- work (3 y) +” super)" con be wyed to invoke immediate pound don condudtor Super keyword Con alto be Wed te invoke the port thos; tonrfuddor| j ; | ! Program: We program on supey Kk exnord do invoke porst oars conshuctor clost Animal { Animal (J {Syston out. puto ("Animal is Created"); } } Cloas rg tutendy Anime { Doge {supert) ; Spstovoed patio ("Doo is Created"): } i Clos: Test super public State void! main( Hing orgs) { Dog d= new Dog( J; ds super) 5

You might also like