0% found this document useful (0 votes)
139 views62 pages

Unit 2-5 Java Quantum

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

Unit 2-5 Java Quantum

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
eto rom ag | import static pork CassNama = i a no] ARS Ran sesame wit the] members without the i portage re ‘ame prefix, primp reli java” import CONTENTS java lng Math» + Bxeeption Handing: The 1ea QoeBa | Wat are naming conventions for Java packages? Tower | t J Nong evan gre Page lp maintain » coins namie atractueorjurdara pret. Adhering to theae eotvettaas ‘Siac dep tart nrg Pur fd Ell Troe oung Sagtteniurbe dens etaomae 1 Lowmaetaes Pca une sl lowe tars 2 Palgbiigetigcngr etude igh yur pega prod netgear iar or ete, Revere doula ane ng reed nme a he pei Sty pca anes het gene I usual fl he ‘rman age nt 4 Avoiding pwede: Date rake a epee tdine Tue Patae Shert sa devine manent Keep package names abort Int Seer Feng pclae in se fr ‘tpn anaesame cde, $ Areldundecrs: Ard wing ners (in pacha ane Ne sec hrs: Page sane shoud esa opel Behind Exception, Exception and rors, Types of Exception Control Flow in Exeeptons, JVM. 3-BP to 2-6F Reaction to Exceptions, Use of Try, Catch, Finally, TOW, AF to 2-07 ‘Throws ia Exception Handling Ie Bait sd Une Delle —————— ‘Exceptions, Checked Exceptions sarcanset "tty oe I [ranr-1] tin eng el bn. tae | __---e BERT] wa you nen by exertion in 8 7 What ag fundamental ides behind exception handling in Java ? How q,., ‘Tava handle exceptions? = of (A. Exception Jor: f 1. ndeva,ancaceptons an eventthat disrupts the normal fy gp ron ON pect oerped nore" hat ecurs runtine sree 2 eeptn cn rile Wari esos, such ain Serie ae 'B. Fundamental ideg behind exception handling: ‘ 1 Tofino debi pin baling ap it ‘a mechanism for dealing with runtime errors in a rad ‘gracefal manner structured and 2 Exception handling allows you to anticipate and! a are ia a pert ©, Exceptionhandling in Java; { 1° Devt exept finally blocks. ‘through & combination of try, catch, and es ithns te aagt wat to monitor fr exceptions are contained threw ‘an exception oocurs within the try block, itis 2 Object Oriented Programming with Java 23F (COT Sem4) 10 Code that always executes, regardless of whether an ‘exception occurred ’ Gaeda | What do you mean by errors in Java? ‘Answer 1. Indava, errors represent serious, unrecoverable problems tht occur during the execution of program, 2. Unlikeenceptions, which ean be aught and handled programmatically, tecrorn generally are beyond the control of the appligatioga» 4, Teunually requires intervention at abigher level, suchas the JVMor the operating system. 4. BrvorsinJavn are instances fclassesthatextendtbe Jara lang Error’ la 7 {5 Some common errors include 1" OutOtMemeryError: This tror otis when the Java Virtual Machine (JVM) runs out of memory and is unable to allocate more ‘memory tothe application. i. StackOverflowError:Ths efit occurs when the execution stack grows beyond te masimmum size. f lui, VirtualMachiaerrer: Thi isthe soperias of eller thrown by the JVM 7 ve LinkogeBerde : Thit error ocurs whea! there igatprotler with the clastloading mechanism i ¥,/ AmeertionBrror: This error oeurs wbell un timertion made by the aser statement fils ~~ 7 TRE [tattered eren Jove, f ‘Exceptions 1, _ [Parent cass [jeralang Bscepion 3 [Cause [Generally caused by | Typically caused by ‘theappcations loge or | external factor such at fevironment. ‘he JVM or hardware, “t[Hanaing [Cam be caught and | Usually aot enught or unde ned using try cate blacks ileNotFoundException. | OutOfMemeryError Exception Harding Objet Oriented Programming with Java 25F (CST Sem) Object Oriented Programningeithiws _ 5 Example: public class Main | publ nati od naiStrngl ar fot are 1, 2,3 wot {1 asep acces an index ou of bounds intvabe «ri cory Me cane, ath ArraylndexO wedi | eae etd wing he rows class, Handle the exception y ea inclade TOException, Syren at case Srp, sod Che lBoond Exc: t "I e ry aeteindtios tat a wel-bhaveg ; ‘out printla(*Array index out of-bounds: * + PART-2 port va to oman: nara Cour Fo in epi Retna. pbk iia ailing arg ) 7 7 > Ate ‘GoeHRs | Degerbe the contrat flow in exception hindi when Wasewprooeessle an exception occurs a AY ey How does Java manage control flow when an exeeption occurs ? ate Not owdacepions |, — : 7 and te extn ‘Anewor |. f Senne al ge ern copier a ir Ho cheetah iene » af Toe finaly Hock executor evenifan exception isthrown and oght, 1 allowingforgoeatial cleanup actions.» 4. Thesymiaris Ck fiaally| é 1 Code that alwayP executes, regardles of whether an exeeptonoecured 99" ’ 5 ‘Thefinaly lock optional, butif wed, t mast ello the at ete lock (any) GaP] What is the role of the throw keyword in exception bbandling 7 Provide an example. ‘Answer {L- In Java, the throw keyword is used to explicitly throw an exeepion ‘within a method, 22 allows developers to crest and throw their own exeptons weer throw exceptions that were caught earlier, q y eat etd hat thoes mee dey ler 2 each AcithneticEseeri@ae)| | aad th excrion y ‘Spent prtle Bacepio cant" + eget Message), 1 ~»* a pte a wht rie | set overd 6 é } cdr, Nae © taser, tzom un ArithtieBaception throw ew Arithmetic seepion(*Canget divide by zero", Steer / f 1 Otherwise, perform the ion tnt rena « vend / divin, ‘Syste ut print" Rel of vision" + rena ' TET] tow dows the throws keyword Maas contribute to exception. nwwer 3. Indra the throm hwnd i sed ‘heen eins fenton dang tacacecn ee he ay fur ia eecution Oriented Programming with Java 20 (CHIT Sem-4) SSS ee Iti prt of the mathod signature and provides information tothe caller thei the type eae tat be mtd ht SW ‘This help in informing the caller about the potential exceptions that eed to be handed. f Here's bow the throws keyword contributes to exception handling i ae about the potential LL Informing callers: It informs the caller about ceptions that might ccr during the methods execution: This Slows the caller to be amare ofthe exceptions that need to be banded. f ii Propagation of exceptions : If « method enevunters 4 ‘aceptieal condition that annot handle tell can choose to propagate the exception, This allows the exemption to be propagated farther upthecalltack fil, Compiletime checking The tions kafirord enables compile- time checking of exception handling "Tis lps in ensuring that ‘exexptions are handled approprimtely at comple tim. In Built ond User Defined Exceptions, Checked and ‘Unchecked Exceptions. FeTI] Wht arent exceptions Give an een. Baower |] . OY 2 a Ie dara inbll exception rer to the exceptions that are provided by theJevastandard brary. , ‘These exceptions are predefibed and are av programs. ar Inbal exceptions are typically orhized into a hierarchy of exception ‘imac, with the base clas being Java lang Exception Exampie of mbuil exception nude: ._NullPointerEaception Ths exception isthrown when & program ‘attempt score or manipulate aneyect reference that hasan, value String str = nll System .out prntnit length) Throws NullPointer Exception ii ArithmeticE xception t This exception is thrown when an iuithmeticeperation suchas division by aero occurs. int result = 10/0; /Tarows ArthmeticException lable for use in Java ‘BESTA wnt ar wor defined exceptions? Exception Handling Tarver cptn pita th ete Fem penton ntl mein 2 Tiassa mnie ting allows | mrepte at are relevant to their ¢ Rees eerrennt ant ot Meo ~ | REE eematemrete roenntonsimpovngcte dai nd aaa. ¢ tact Sect cutee ‘Define acuntom encepton by extending Razepton cl recent nc ante teeter pa Sicha eee Sd tin et tema 2 cones 1 6 HERR our rman / a rs a gs 1. | Definition Exceptions provided by | Exceptions defined by | scat Weestees | steers eo ed 2 [al aaaianat | oa a toelale | atarpaes | Sant ne ea Fag) mm epg (ar Bae | eel “‘Basekxceptoon’ fet on” or its eee Times] trp a ain [handling across ann ote ieee leone Object Oriented Programming with Java TEBE ene ceed chee epee? Taewer | Te ape Checked Tacheckod exceptions ceptions 1, [Definition | Mutt be caught or | Nowd aot be explicit declared handled or declared 2 |eample | 10Rception Nilesat ‘& |Compiatiod Checked ty the Not choked by the compiler. * | compile. [ending | otost be handled with Can be handled Ury-eateh ap troma_ | opal witht atch dla. * | oecessry 5 |Purpone | Typically fimertetal [Typically for factorat@g, UO)» | programming errors a ° reeptinal ase, 6 [Inheritance] endBxsption’daae | tend nas q ‘Runtime Exception ey ‘Goo 1G] Waatis byte stream in Jars? Give example ct commonly ‘wned byte stream classes in Java. © ‘Answer | ‘Byte stream in Java: 1. Indava, abyte stream i stream of raw byte. 2 tinued perform /O operations oo binary data, ach as images, studio vide, or any othe typeof on-ertoa data Byte streme ar itable fr reading and writing rates making ‘hem efficient for handling binary data. Shs ceed Promennesiaiere SS & BufferedWriter : This clas writes ext to a charseter output seam, buffering characters to provide efficient writing of Characters, rays and lines, ‘GeHIE] Ditterentiate between byte streams and character streams in Java VO. read data froma file asa Jawwer cn This classi used 10 srrvanofbytet. awed tet dla oa Blean a Byte sireame | Character streams “4. FileQutputStream : Ts clas ‘Used for banding binary | Used for handling | fener nw ted aed data fom dha tela ed, staat ts, uch 4 ByteArariaputsren TS ‘ideo, te Tehinge fcharaccers ee Thin claaaiiptsed to write data to a. Handle raw binary data |iandle characters, . neg: od iy email coco pei i tod decd bem epee? el GeeTI] what do you meni charaeer seam a ‘Dead Way | Del with characters : indore " ya een carconty wed eharecie tram aes Nengetipesening | Avronatic neti m=z > a | ‘WMeetins | cat senat eaee Character sre i aR: | - crate Seapuaer ce eerste tara WO cpefation for v eae ay % OR, Up slate tor nandlog | Bie for banding 1 Cpe a east carcino yn "aolpoemed SS cheer sams re dei al Used charatere © [cen Lae ein tor WA | ME tit a ficently. based operations. “| based operutions (che xan pls psn mea for renting and Seta tnate olga Sot ens 1, Comeny usd chars rg clase PARTS 1 eoder + Tavs lat the operas fall lassen camara ; Moromelag ening orean cura hed e renting pacaaatieiee! sec hceee Pipes tataae eles oa ‘QavRITY]elan the proce of ending and writing en esing Sree paps sbaraies Niwnl eal tr seat soiree = 4. FleReader: Thins is sed trend data froma le ava stream ee reper A inte ing tram: Wg ing eva Teatohive beef dunes rhe PcduipaSircer Peerage 4 Flac scan welinwedata ones areal sSiveree of he prom eee 1 CrenteaFleOutptStream + ‘ ButeredRender Thi te rast fm charsctringut " Pe eereiiaen et eae {tas Fete he ying te Sal Banc ecparae ‘se parineee Exception ae ouput stream Fr Writing, 1 (edlaxfleOupuStream ce Argucitpustream outputStream ew 5 AW FieOutpatStream output Wien tothe le j Y fsaoganas at, wel’ “Styl yen = data getiytent) Convert string to byte array > ate wrist Cove testa) utpatSream lod atch Exception) print StukTrac, 1 ' 1 B. Reading Her sing ibaa ream: Rag Sewing yt ei oes eh PeloputSrem Fale 1 Create a Fletapisiream * FRRRIME! Pdopsran bjt, passing the eps Object Oriented Programming with, This as represents an np stream fr reading ram mis oe a 2 Readdata {i Usethe rea metodo the ilelnptStream'torendbrtes from the fle 4 Youcanread byte arrays or individual bytes Choe the stream: i After reading the data, it's essential to close the ‘FlelpotStream' uring the clot method ‘Thinrleass any pte remurcenapoined A 4. Example of reading files with byte #tzeams i)” ingot jeraioPleapustram; AQ.“ impor jevainOBseeption, publi cae ByteStreamfendBiam pel | lista vid maitre) ee @, Od SO rane Menu GS Wed ote ‘String data =H, world" aerate witty Coe ease bulleted) rite dona, Heath dORseptin Prince, Object Or LiTF (CONT Sem) ed Programming with Java ftreame in Java involves the use of clases such a# ‘BufferedReader: Here are the steps involved in the procent 1. Greate aPileReader: i. Inatantate a FuleReder’ object, passing the file path ot 8 parameter ‘This clas represents an input streamfOrreading characters adi) methad of ithe ‘PileReader’ (or ‘BufferedReader’ to read charters from the Ble i Youcan red atrings, characters, or portions of strings. Close the stream: ‘ {After reading that, (08 asential to close the FilReader and BulferedReadee if ued) using the ‘ose! method. i This releases anyayutem resources assornted witht 4. Example ofreading files with character streasss:) ‘Create a BufferedReader for efficent reading (optional) BufferedReader bufferedReader = Rew BulferedReaderireader) 17 Read data fro te fle String line hile (ine = buferedReader. readline) te al ( ‘Sytem .ou prithlline)/ Print each tine ’ Chose the streams ‘ufferedRender close; Exception ’ 1 Woe tan] what are the a for file vO operations? oo! cover byte streams for Af “aaswer Using ebaracter streams ort {slowing erantaget & aracter streams autor 1. Character eocoing banding ne han hares ecg ad ei Po ge eed ae ‘manu ecalngscodig vin Testun data handling Charter reams are specifically designe reat tran dat taking tem mere convenient 0 reading Seringtr Beg 2. treated Re: Curae sang 9A Uday ‘haractera ling dara ota for handinginteraatinalized tex, 4k eyfr text operation; Character steams, pecially when snd hulle. er improved prfrance fox text-based UO oe ok aA? |S Pltform independence: Charatr trams abteact sway platform. ‘ecifie dotula elated to chatter eteoing, making Java code more petal ners dieret liom. © Ease of ae: Character stredina provide higher Level abstractions for working with diferent tent proceting tasks. This makes them easier to [BREERE] oe de yuhende eptone drag 0 operations pn enygg Mace sal ‘Fe VO operation Jette UO ception) Object Oriented Programming with Java 219 F (CSMT-Sem-4) ‘Handle Exception ceprinStackT race) ’ 2 Handle specific exceptions Catch specific exceptions that might be ns uch as IOException, to provide more thrown during fle UO operat specific eror handling tl File WO operations a J eatch COEsceptione){ iY ‘Mande LOEseption ce printStackTracl ~Y ' AY Propagate exceptions : Propagate ekéaptions tothe calling method if {hoya be Rendle lel. Hallo higher level code to handle ‘the exception appropriately. public wid ede) thrones ( Feeder reder lh “| Ay reader sow Fader ‘7h VOoperstons - pho 6 (OWigeadecte nat aw reid slow, ‘ MF trot BESTT] wt i thread in Ju concurrent programming, al A Thread: semua 1 ie aes ia al ie Tee teint train see) maAY Lifecycle of thread: L 2 Thad a ro nents se nal se coreren programming: ore nn il on der ra ora oPerfirm may A sos can np esa thay Reeensietcerneen pear so vl smtp tasks proses. a/ Aercchronous programma Tet aciitate ayn a Aap operas ee nerdy Renrmeesti (Resource sharing! Thesis tin share resources such a Bitlet iin the ame proce Hew td Hsu: A nv tad iii yc nti Coase feist ga oh pein cere el “Epis bera iy Aral he uae tal Sea eign conti tin bi ‘esbieteeis sir spre tse A thmadatntattnene sol chen sot ad sate onan ‘attra ect trl ene, onan ‘cannot use processor, even if one Se - Blocked Sate: Arana head Blocked ‘whenitattempa ta perm task that cannot be eel 1 salto ant cape (net dcramet rine ‘sro tnt cel compton on epi tane)n 221 F CST Sent) ‘Object Oriented Programming with Java interopt oe 5” ig, 2.221, Tred iteyl UML sate dagen ‘Wee | How do you create tends in Java ? Provide examplen using both Thread class and Runnable interface. newer ey a, x2) Indavaa thread ca begat intwo main waye® Oe" A Extending thn Trend claw ee 1” Yoeaaeren cls that ertends the Tend ll and overrides {era meth a 2the rurb tod centsinnsbe ce it wile excetd inthe powered 0” Ned 4 Heret anexample: (nsf) laa MyThread extends Thread | public void rund ( YS ‘System out printn(‘Tisisw new thread" " public las Main public state void main(String args | MyThreed myThread = new MyTBesd; smyThread stat); n 1B, Implementing the Runnable interface: 1. Youcancreatea clas that implements the Runnable interfec and overrides the run) method, Exception H eas wentet sored ton * Remon a Ms eae i ot pari a Tnsisonew thre) clase Maia re ase ‘ived ted sae Threadine MyRmnable(), hed GTI] teens betnnen Thread sve and Runnabig interae. | / ‘SNe [Aspect Thread class Rannableinieria] 1 [Inbentance [Extends the Thread |Does not extend w ase im Na 1 [mplemeotang [Dict implements the [Provides angle ra y, |r eto. lmethod to be| E implemented. A [Resour | Convunes mory tye [Consumes less mystem omatvem [resouren “dae” tolresources asi aa Pe iahertance 7 interface 4 [staring [Cann be phared [Can be shared among song mga thread, multiple threads. ‘5 |Eneapeulation |Encapsulates both |Encapsulates read ge ted trecoge essen ui mine th in___ Se ‘Gee BaE | What is thread prtority and why fs it important in = multithreaded environment ? Anewer A. Thread Priority: 1. Every Java thread has thread priority from MIN PRIORITY to MAX PRIORITY) that helps the operating system determine the ‘order in which threads are scheduled Ri represented a integer value ranging from 11020, 3. By daft, every thread is given priority NORM_PRIORITY (a constant ofS) Baeh now thread inherit the prioiy of the threed that ereated it. 4 44 The bot an operating system's read Seder isto determine whichthread ringnext. ‘5. Whenabigher priority Urea eaters te ready tae, the operating system gunerallypreemplathe currently runaing read. 16. _Depending on the oporating system, higher-priority threads could pontpune the exegutionflower-prionty threads. 1B. Importance of thread priority : In multi-threaded environment thread priority i important because i helps the operating ystems thread scheduler daide which thread ta execute wheo thergare more ‘threada readyto ronan there are avaable CPU area. ‘Goekae] Rxplain how thread priorities influence thre scheduling. : oy a AW,” ‘Anewer f é InJava, thread priorities nluence thfed eheduling by providing hints to the thread scheduler about the importance fone thread relative to other. ore's how thread priorities influence thera scheduling 1. Thread scheduler: The underlying operating ystems thread scheduler la responibe for acheduling threads for execution onthe CPU. 2 Priority-based scheduling : When multiple threads are competing for CPU time, the thread scheduler uses thread priorities te determine tmbich thread to execute next. Threads with higher prieiie are more Tikely tobe echeduled for execution A. Preemptive scheduling : In preemptive scheduling, the thread ‘Scheduler may preempt slower ont thread o allow ahigher- priority thread torus. This ensures that more important tasks are given CPU time when meade, Objet Oriented Programs ce esate) neds ay Tian tewen rds dui cede tee oat ee erat tad, ‘rend based tr priority threads are gi, ee ten ae et or ey nae res by at rcornee the a comet ones naar BEET] rn tt tenting reed tr Tawwer A Thread nation a ace nan enti ciation of muti cero nd orderly atceveto shared 2 tn nmabithraded enagenty bere multiple threads ayy ma ymin semen prven cg nite “ 4 Tread petri nelly achieved wing eynchroniatiog otra ach a Tc meses, emaphores, od motion, 4. These contro peor thet only one thread ead abu g shared urea ie A 5. Thread yicliwitioin crucial llhreale sppatonata teint data esieney, prevent rae eenditions, nd enmure ‘ome Praga eho B. Key concepts relted to thread synchronization : 4, Critic setions; Thee are sega of code that aces shared ‘master walsh ate sexe hat oly one thread ‘xecie cra ection tineto resinain data consistency, 2 Maton! exclusion: Mute! exon (or mutex) ensures that nly ne thread a ces rel section at any given tie. 4 Syuchronied methods and blocks Methods o blocks of ade marked as 'eychrnie can only be excel Tinea a arm eneued yan thread 4 Locke and monitors: Jaen enetructa rch at Lack and (Object Oriented Programing with Java 225F (CSOT Sem-4) ‘newer In a multi-threaded environment the ned for eynchronizng threads arises {dv following reasone 1. Prevent data corruption: Synchronization preventa multiple threads from concurrently modifying shared data, avoiding data corroption. ‘2 Avoid race conditions :Synchrornation ensures thatthe onteome of the program isnot allected by the unpredictable interleaving of treed A. Maintain data consistency: Syachronization ensuresthat changes tmade by one thread are vile to other threads, maintaining data consistency. y 4A. Bawure thread exfety : Syachronizatio prevents concurrent acess to critical section of cede or resource, enturng correct behavior & multithreaded environment. = = Prevent deadlocks and velo: Proper synchronization hes roid Aledlock and velockaby ening that reads can eafely acquire and release resources é 4 Enforce ordering constraints: Synchronization alowadevelopers torenforce ordering contraints on the exection of thread ensuring Certain operations out inaipeciie sequence. 1. Optimize performance : Athough synch overhead, ifs erie for maintaining correctneas andirelisblity, ‘lumately optimising the performance of multithreaded appiations. ‘Gas BBB, | Describe various mechanismsor synchronizing threads in Jawa, g a Answer |" ‘ Following are sos of the most commonly peed mechanisms : ‘A. Synchronized methods and bigcks + “Jeva provides tbe ‘eyachronized keyword to synchronise methods blocks of code 2. When amethad or ck s marked as eyochranized, ony one thread canexecuteitatatine. ‘3 Thinensuresthred safety and preventsconcurrentaccasto critical section of code or sared resources a 1 Reeatast rmethadeand OS gol ver ekg and unlocking, Ve ut, abd eondiget 2 Tarte wench ees and condicing vanabien a Bangle ack k= ee tl ; eke Acre , wl { ‘1c mtn sod aly Teele dele the ) a ra Neca ae rarer ‘seen 2 enue onthe weapon ag aie ty ae Repl Mite matting nl ret arr ‘ie etn ote ‘fly w semaphore sles Reet th port 1 SSEESE] rtrd omental nit acieed Tanver hea commun the proce of coordinating and ‘chang formation beeen maps thread ina stoped Objet O 227 P (CSATSem-0) ted Programming with Java allows treads to eyacheonie thie activin, hare dat, and coordinate their execution ina conraled manne. Thisis essential fr bulking concurrent prog work topther e aceonpish aa echt In Java, interthrend communication atypically achieved using three fundamental methods provided by the Otc cla: wait) otf, and ofA, ‘Trece methods enable threads te wait fr tnd tosgnal other threads when those conditions ar ‘Gor 237] Provide examples illustrating the use of waltO, notify, and motity ‘Answer Example: Using watt and petty fo single-thread comatunicaton elas SharedObjct | ‘methods (or interthread communication. eolean Nag = false; y ‘ synchronized void watforPlagChange | while tag) ¢ ss wi ® & drat) Wait atl Mog changes ‘eit literuptedException 6) | ‘Tard gurrentThrend).nterrupt 1 \ ) ed f $ System out print Pageanged™, ' Nef synchronized vid changePlag(| fag = tre; notify Notify waiting thread thot fag has changed 1 1 Public las InorThreadCommunicationExample public wate void main(String) arg ‘SharedOtject sharedObject = new SharedObject(, Thread thread! «= new Thread(() => shared beet. waitForFlagChanged)) ‘Taread thread new Trea) sharedOhject waitFor ‘Thread thread = new Thread) ->sharedObjectchangeFlag() {hreadl start Thead | wats for fag change head start Tread 2 wafer ag. ‘Object Oriented Programming with Java 2:29 (CSNT-Gem-4) ‘thread3 start) Thread 3 changes the ag , 1 {nthis example, both Thread 1 and Thread 2wsit until Thread changes tg flag, Once the flag changes, both Thread 1 and Thread 2 are notified and continue their execution, UNIT Java New Featurey CONTENTS Part + Pooctonl fetes Part: Lambda Expression Method References Parts: Part + Stream APL Part 1 Dealt Moho, Satie Metbod oon Part : Bast Sree and Decede Pact? 5 Forkach Meth. ‘Teyvith-esources Part. + Jove Module Sten Part10+ Diamond Synias with toer. Part-11 + Local Varihle Te inference Partt2 + Switch Expestions Parti8 Weld Keyword. Part14 Text Backs. ee ParetS + Records cea a Parei¢: Seed Claes MIF (CSTTSem.4) S-2F (C8IT-Sem-4) Java New Features PART-1 unctional Interfaces. Give some ‘GeeST | What are functional interfaces in Jav predefined function: al A. Funetional interfaces 1, Punctioaal interfaces in Jave are interfaces that eantain only one abstract ete 2 Punetionlinterfae ie also known st Slagle Abstract Method (SAND) interface. 8. They area key feature introduced {a Java to support funetional programming paradigm: 4. Theos interfaces arg oten ied to represent funetions or actions ‘owing ther ton ated around a parameters or rested fom ‘methods. Predefined functional interfaces in Java: ¢ j 1 Some predefined fictional interfaces dara inode? 1 jvmtangannabe Repeal abe etd caneurretly SL java.util Comparator : Defines a Gompirison function for ordering element Iii. java.atiLfunetion Predicate : Represents (boclean-valued function) of one argument. jayautiLfunction Punetign : Represents a function that ‘scep one argument and produces a result vy. javasiti function Supplier : Represents a supplier of interfaces. redicate rent 2. ‘These predefined functional interfaces provide common fuetional They areeatensvely ued in conjunction with lamba expressions tnd the Stream APL PART-2 Lambda Bxpression. Ln en a isl ve eet interface wt ‘has fanetional interface. ‘ ara ewe Yu ed bebsvioe (code) as an argument to & met ns Moore aa nee Eon fe eT aes iL Angumentelist:itcan be empty or non-empty as well Ae cal ae fii, Body lt comains expr at a LY foarte at dentate ila slags 9” 10> Syne out pri Hel Ta = numbers stream() Silternurn > num % 2 -llet(Callactors tobi sarcarrsen) dra Fete GueSST | How functional interfaces in Java relate to lambda expressions ? ‘Answer 1. Functional interfaces in Java are closely related to lambda expressions ‘ects labo expressions ean only be used with anctonal interfaces 2, Lamba expressions enable the eration of instances of functional interfaces without having to explicitly define anew class 4 Tnstead, they allow you to specity the implementation ofthe single abstract method diretl inline. Y 4. Thir makes eade more concise and readable! 5, Following example ilutrate bow functional interfaces and lamba promos ered A 1 Detention interfaith ng abstract method interface MyFunction | . void perforin Sigma): f e% ublieclaseain (|, y ' public static vod maining!) args) ( fe 1) Using a ainbda expression to create ad instanes of MyPunction ‘wie, Wy SS ‘pFunclbn yPncton «(String mene) a ‘Systemout printnMessage:" + messaeh. i Je wok? ie ‘bite meno efied in union intrtace myFunetion performAstion Hell, Lamba; ’ 1 6. In this example, MyPunction is « functional interface with a single abtract method performactan. 1. We then use « lambda expression “String message) -> { Syatom.out printin(Message: " + message); I to provide the implementation ofthe performAction’ method direc A. This demonstrates how lambde expressions enable concise {implementation of funtion interfaces in Java. PART-3. Method. 3-5 F (CSIT-Sem.4) saning ih Objet Orested POE Goad [epaia metho newer op ‘A. Method references nT oie shoriand aya or writing, seni tc ata enpresions oder costrurtors without invoking ce oe ix and readable alternative to lambda 2 Rapier etd ele a 2 pnt a eae oe a i Syntax: ClasName static MethodName ate eet ce hdl prices Me See ene arr A a aan ei ota ate Peep ert i matters penn in nomad i Symtax? ChassNane:new Sooper eet types aces in Java wit ‘numbers forEachinunber-> "Method reference umber forEach Syste out: pra, System out priatlnoumber) SOF (CSIT-Sem-4) 1B. Elimination of redundant code: Java New Features |. Methed references help eliminate redundancy by allowing you to directly reference existing methods instead of rewriting sala ‘dein lambda expressions. 2, Baample ‘Mamba expression ListeString> upperCase Strings = strings stream\) anapttring > string tUpperCast)) -oletallectors obit) 1 Nethed reference List upperCaseStrings = stringsstreaml) snup(String:teUpperCase) collet Callctors tls) Improved maintainability: 1. Using method refereaces on ke pode carer maintain becuse ‘they explicitly indicate the method being invoked, making it easier for other developers to understand and modify the code, 2 Example _mplnumber 5 Bath srtinumber) forBpehi System out:print), Method reference » te ‘numbers stream) x (7 4? ranpMathert) s forBach Sytem out: print): D._ Simplified constructor invocation : 1. Method references can simplify the instantiation of sbjects by referencing constructors direct, eliminating the need for larabda expressions tocalleonstructrs. 2 Bample: ‘Mambéa expression SuppliercList> lat Supplcr=()-> new ArrayList 1 Methed reference ‘SuppliercLit String> lit Supplier» ArrayList: SSF (CSITSem-4) Java New Features ana _SIFUCSTI Sem he Orcs Smear aaa =a sm APL Write down the features of stream aw = ; a enh: eis Pp ae we den eas Bester Beane Se ane aa B. Fencures cf Stream API: Footage te bey features of the Stream 5 Te mt Rane AP crn 8 eee 2 epee grea = eng Se cceears Spageeeeee 1 eaten as A cpa nino Bi grec, ccs reggae pm a = ’ A a area yrin Bir Dire ng SaaS 1 Prag Ss dei We eter tne Se eee one eeermacns 4 me © ee Oren at pve wi go Sree eterna eprint da prcening @eeR7. ] Discus the parpove and usage of the Stream API in Jere Jareer A. Purpose of Stream API. 1 Data procesting : Tae prinary Papo ofthe Stream APT iste ea ie presi ol aia ach asta, area, or cet ee 2 Functional programming: Siam API 1 Stream API promote functional Broan ding mae nc td eile Concurrency : Stream API all am APL supports parallel execution of operations, enablngoncurectproting of data ‘Intermediate and terminal operations Stream API provides Aawiderange ofistermetiate and terminal operations er omen data processing tasks. = B._ Usage of Stream API | Greating streams : Streams can be crested from various data sources sing factory methods provided bythe Stam interface. Totermediate operations: Intermediate operations transform or fier the elements ofa stream and teturswisew srvam as ¢ sede sean & Terminal operations : Terminallperstions consume the clement ofa stream and prodcea final rent, ach ae «value, 3 collection, or an action ‘4 Chaining operations Stryaxldpratcns canbe chained together toformapipalin, where the output of ene operation seven the ‘input forthe net.” PARTS, Default Methods, Sttie Method. ‘@aeSH | What are default methods inJavelintertacea? Give key features of defaait methods. fy” f 2 Thi means that any new method added to an interface would ‘equi all implementing classes to provide an implementation for that method 44 Default methods adress his imitation by allowing interac to ‘provide defalt implementations for methods. B, Key features of default methods: Key features of default methods inJavaintefacesinlude PCS Sem) cae and emeigsandere Pa he fault met ried gas Adc wi Mae ie thee an ae a Bein compa «Dt mate soya ; reife: Ct % Grrl ner i ete 4 Matte inberitane : Deo meted wnteshshrrin dra ete RE tec ner an x We inert Siete tnd ara | tow do detaaltmethods enablebackward compatibility? ‘Aaewer 1 Dealt methods enable backrard compatibility by allowing existing Interfaces to evolve without beabrigeting implementations ‘2 sain canes that implemen th jterface willastoratcally inherit the def implementation for Ube ew method 4 This means that clases inpleentng the interice do aot need to ‘rovde an implementation fer the new meted wnlet they choose to verde ‘Gaara concept atic mthe iJ interfaces What re the fontares of static method ‘Answer, ( A. State metiode: 1S ae afte Olein fav toll traces ‘Sema at mtd 2 rir Jara irae ll dcare instance methods 4 Any meta declared in an interface wan sre ead iat Withtheitradctno ate metic, ‘sained the ability to declare static methods. a ae Thee sate maths cab led dine on the interface te a. Tit eguring an intaneo the impementinglane 4 rel, atic ethos in daa iseries enhanc the ety, ty. and expressiveness af Java interfaces. d 1 They payer cole race tiring cde ranization and promting tod i defined sing the hed signature and, otementing he interface re need custom behavior, able mult $10 (CSIT-Sem-4) lava New Features Features ofsatle meth methods 1. Belongtothe class inwhich they are det tds: Following are the key features of static Stic method te ted with inn sed rater han nh nan of ede 2 Nose a nun varie: Stu eth ct ses inte varies ay bese they topes oe ap particular instance of the class. ie 4. Geertbvcettil gee ene ant even ana ie tai tha 4. Coreen ote ott mer: uli at sen orm neers 2 instance reference, ares re Memory Mit ag MDa wry Sertitecradines Sa Ohi tm mes of the class are created. *% eteeng PART-6 ‘Bose6¢ Encode and Decode. wean Pein Battin denen i. inaglAY a 2 a ane wong and decoding are tacts ved conver binary data into ASCI characters and vo : Taicenverion commonly amin eater nr data eee Uoberepreentedasters Base6t encoding: 1. Base encoding is a meted inary data int atert format using a et of 2 The process involves dividing the input nary data int groups of Feae eae hen mpd oe fe piu ACH carats Bach group o 6 ite correspunds one character inthe Base lade 4. The Bavebt alphabet consi of 64 charactor, tpielly the folowing i AZ(6characters) Sie & w2(Q5 charactor) onan fi o9(ocharacer) S11 F(CSAT-Sem-4) fn “¥(ghan ie) ye tMforwart sash) vie Aldona.» peding {hate inp inary at cm hats se my be wed to ensure ne aly vied ito oUF ‘eary representation f Tae tow can you perform Based enc Java? Taawer f ‘A. Basee4 encoding in Java; Tot aston b 1 Divide the input inary twp ofits 2 Convert each i reap info decimal ale 43 Map ech decal ysl the corresponding charkctin the Panta a 4 taacenarpd the ecoed data with areata itis inulileefteharecersintength. Har a nape Base ened 0 fioporr ot ase a? public dhanBascitiample( (“P))” ~ bl static od iinet ‘opt onary data byt binaryData= "lel, Worl” geet); ‘cote tbe bnay dant Base Sing base6tBncoded » Bas64 getter ene ToStringbinaryData; Sytem at pritin Bass Encoded” base 64Encoded); , jand decoding in aap encoding in Java are 1B. Base64 decoding in Java: ‘Based decoding in Java; The steps for Base dcrding in Java are 17 Gave ae one tern te Raced tert back tts : the nary value inte roupe ois, pi FICSTSem4) lava New Java New estrea ‘2 Conver ach group of isto abe Repeat step 1a each character inthe Bate-encoded Remove any ie 5. Ramee ny pang characters fm the ed of the decoded (6 Heres an example of Bas64 decoding in Java: import rai Baw pubiclas BaseExample| Publ static void mai(Strng an) | Baseb4 encoded text mm String base4Encoed = "SGV bef Pemak RE" ‘Decode the Base-encaded tet” Ite decndedBytes= Based geDede( ficode(baebtBceded) String decodedStrng iw Str decodes, Sytem ou prin coded Brg enti 1 PART-7 PorBach Method,Trywith resource, Woe BiR] Deere the trtach man eed tiene sacclaaeptiomne * ed = e A forBach method in Jere: of Jr ttc etn rina operation proved See . action for exch element in & 2 Male ngs beeen nly The forkach method scrpts fintionalintarfag as an anrmest, “Thich defines the action s be performed om enh element of the 4 Here's the general ayn ofthe frac mito stream forBaehtion where, a Sivas S19F COT Sem.4) ove (cSt Sem-4 apc an sigan a sist Oetreeng Java New Pentre Obie ements ovr wich he operation wil by ae ad stream Team cee eras Ay and enhances the ribusnen of at itectce rprsetig tH #cti00 Lo by exception handling in Java programe, avinge tin A fe ra a ee rend oven a B._ Significance of frkach method © method provides 1 Conce and date dealer cements of acallectin Type Annotations, Repeating Annotations se dere a carcem The forBach met 2 Fonction proganing “<_ GeeI5.] Explain type annotations and their role ia Java. prometesfnctel st thn brah li 70 exren, 3 ee ered ean craig am ‘a addition 1 Wequential execution, the. allow developers teapply annotations to + ea cpa pnt emt en dwt pra arouses nadia ut erat 2 Te anton vie ima tad shat ich 5 Stream integration : Te forathtnethod seamlessly integrates canbe une by tok ad ileal Siar Seam PLease 2 Top enna cng toa wile rane of pram “GeeBTa | Wat ine tprthrevurces statement in Java? How Role of type annotations in Juv dove it simplify resouted eiBagement? =f / |. Providing additional type information : Type annotations AY > rodent tna peck can ey oe Tower | » {el raver to prirm ai tk 7 A tepwideoires statement in Jere, 2 Caatom annotation : Developers ea dine canton pe 1° Theron tet are wet simplify the erotatnsto exis dam pectin eee “management of resources that roquire cloting or releasing after, 3 Improved code quality and safety : Type annotations help sewed ~ vy improve eae quality, sly, abt maintain by proving 1 Weilows yout decide anno an resources within the sina completing srt che areata of ey sate i Sane os oer etna tana tt ‘Woe ] What are repeating ennotations and how ae they wed soft tyHck, pews wheter an exception cursor in Java? ww 4 Following s the general syntax of the try-with-resources statement aan ‘yr iation | A Repeating annotations: ‘Code that uses the resource 1. Repeating annotations, introduced in Java SE 6, allow multiple ech apy {itancnofthebame estan be apie ge program ‘teptin slenent ' Se 2. Prior toJava SE8,eoch anstation could ony be applied one tom ‘Gvencloment, which inited thee lexbiity in certain eenarion, 4 Repeating annotations address this limitation by allowing agony aetna singin rere oan y soe the pecs ‘anaotations be eee ereore aka enn Tmeees and 4 Aepeing mn ear nt cr 315 F (CSIT-Sem.4) ving with art ins wit pani in sit¥atonswhery yo 5 Rimprors cole reniaily wpe ae ‘wap nna of Here's how repeating BL Repeating annot ee "antatins To declare repeating Declaring reesig r toncation pe see SO asin ton: Oxce repeating smttiog 2 Arig eet py een lees Uy crtaer sma PART-9 ova Module Systm. eee TEGSTT] Discuss the Java Medule'System and its advantages, aa : a =a ; Se acd a rege atin ae iy ~. *. ca, Sek CC iecae ect eee ea hi. 5. ger aes gery eee OS at sa caeae eae team ns as tee ste eee Jo eee pees eae eating mn av Serna aces Improved performance : The Java Module System improves tp Saar eh re eee re os oe ‘ances ecb rveing entered abl meta-annetation along, het a Diamond Syntax with Taner Anonymous Clas eee ——EE Gee S18.| What is diamond syntax in Java? Toorer_| 1 Diamond tlw the mend oper ia fentre Ieallows you toinstantate peices whut ip pec hetype arguments eee. ‘Thediamondsytasis used when hatype gums to generic ase + [a bvinfered frm ha contin pia ton nig Sees 4 Here's an example oilstrate these ofiamond eytax IrBetere Seva? LstStrng> it =e ArreyLitetrng: {With omen syan (Javad Iter) ListSting» etd ngs tite, wh 5. The diamond epmtax is particularly useful insituations where the type pire or ebviou om the cata. 6 Diamond eytan cin ony be usd wth angymowinner cles and freer clam intciatin. } 1 (gcaaet lead with ctr lib pment. Adduunally, diamond syns de ono ny oe type ference coaiee 7 ‘Que. | What do you mean by inner ancoymous classes in Java? Tarver 1. Taner anonymous clase in Jars are wana clases defied and intantated ln, pel ith he borate cla meted 2 They are ued fr proving on-f mplementatins of inarfe ot trtceding clases without the need define separate named canes 8 These later ar imiedin scope andhave cen tending eth Teel varalef thy are effectively fal or explicitly dered Bia 4 Tne anonymous clases ar band for resting qk implemen ttloterfaces or extending Gees ntbout ong extraaed elie. 5 However, they shoul be wed arf to evi atiering cle ad compromising readability od mania. Ri LATFCSIT Sem. ect Oriented Programming FET] tw tn ne seed nae i=l Peer th pone wad [igen arta umes So mertriet 7 ‘haner anonymous ase with initializer Book, 10 inne tamond sata can be used With ing sarHele"e War ’ k , 12 Inthe example webe resting pinta of ArrayList using the dian ertan (© ethos peng the type arpument A aside the curly trae, we fine an inner anonymous lil that extends Arraist. 4 Thsclascontaga inl ck where wed elements fo the lit. 5. Theompilerinfrt hat the type anument for ArrayList should be String. onthe type ofthe variable ist drlared as List String>. PART-11 Local Variable Type Inference. 7 ‘Que $21, | What is local variable t3pe inference, and how does it improve code readability? ‘Kaswer A. Local variable type inference: 1. Leal arabe type inference isa feature in Java 10 that allows the ‘compiler to infer the data typeof a ttignd toi 178 ofa variable based on the valve 1 Reactor Mikey "7" *8P te ye dcaratin asacited piaF (CST Sem) Java Now Feature 3 Sxinsea oferty ating te the vr keyword nde thea nthe contest Pe of variable, can spy ler Bure ut the peta 4 Porexample,in Joa, inated of wrt ListcString>nameas new ArrayList String Wecanvrite 0% ArapistString>) {The compiler willinfer that ‘ame ino type‘ArrayietString> taned onthe assignment. mi eat Improving code readability: Local varatedSpeinerice improves Code readabltyin alowing ayes an 1, Coneiseness : By reducing boietplate fede related to type declarations, lal variable type iafereae sakes code sorter and 2 Focus onintent: It allows deelopet to focus more on the inteat oftheir code rather thasithe deta of type Reduced redundaticy : Wi type inference, you dat need to repeat typename, which can reduce redundancy 4. Improved maintainability: As code becomes mare ncse and fsa on net fend tacos eae oa PART-12 y —— | ‘Wae8 | Explain switch expres in Java and how they differ {rom traditional awitch statements 1] ¥ L 2 ‘Switch expressions wre introduced Java iZasa preview featur and ‘became a permanent feature starting fom Java 4, ‘They provide a more concise and expressive way to write witch atements compared traditional witch statement see snes 19F (CSMT.Sem4) Ore Oriented opening 8 a aca Uses emitch Keyword, > [1 forms | Ue ere Fach cv mon provide auetoreur. fate hare 3 [eee [eat eta ed rb pres © [Detar | Optio ease | ented. [ere | Each se may stain | * [tee _| atemen. Madatory rst be present, ith avalue to return, ‘Gee BE] What i the yl eyword in Java ? Provide exampleg ofits usage. $ 8 ‘haswer 1 The yl hepword in Jvais ued within swith expressions to apecify the value tobe returned fom sass. 2 Mindat thereulofeahatngparucuar ase and terminates the section othe rich expression. ‘3 Fil can aly be ued within gic expressions, and ino permitted ‘ether conertsin Java 4. especially designed to work wth witch expressions to provide a ‘oot ay tortura ale 5 Fllowing van example demonstrating the usage of Yield keyword: int dayNumber «3 String dayName» witch day umber ‘ate 1> "Monday case 2-5 “Tueday ‘ase 3>"Wedoesdey"; ase 4» Thurday mse 5> "Friday, eta >| 20 (CST Sem) ‘Handle vali dy numbers yield “Invalid day; ) h ‘System out prntnThe days dayName), 6h cram yer edwin te at xt The ich expreiontermiaste atthe il ttement and ev ? ‘is aaigned to the variable ‘dayName’ “ ator PART-14) Text Blocks, ‘GieHIE Dlscne ent block nad thee benef strng galtion ry A. Textblocks: § / yy we 1, Text blocks wer ireduzed in Java 17 «preview feature and ‘made a permanent feature starting from Jara 15. 2 TetRohapoie meres nay tami sing a ‘8, Instead of conctenating putin sting Hira or wing eacape character for line bres, you eas use ext blocks to represent ‘multiline string directly in your ene. 4. Here's simple exampleata teat block: String html ==" wv chim body <
    5 Inthiseuample, te tiple bl guna ine th at nd td ofthe et lek 6 The content writin the text Yok, nding the indetton ie preserved a5. mn F(cSAT-Sem-4) } tmplil finality: By dian, ap Splicitly final. This ennurey hat rene record are ina re that instances of the record Se 4. Compact initialization; to initialize the records component Tha oem etictor od formating are preserved. a enets, This allows instances ofthe record using ace rete ns etal 8 Acancie syotae ne eel a Tea bcks dc the aru ofilerplate PART-16. cece. This eas to ean, more concise coe ‘Sealed Classes 2 Thepprotie seco seta fr declaring dases tha! are primarily ‘aed to rodal dat rusher thas teharan |X _ Ther premce best practices for modeling data. making code more smumghable and casertoanderdand Reed wer crored at a renew hatir in Java 1 and became a permanect fare earang fom Jara 16. 5 Hewes stan example ofa reorddeclration adie record Pasbint x int 919 This angle ne of code declares a record named Point’ with two jwanersa yan) Behind the scenes, the Java compiler automatically senerates sereral standard methods, sachs equals), hashCode(?, and ‘wString as well asa constructor to iniialie the record's mopar ‘Simplifying the creation of immutable data: Record simplify creation of mamtabledtain following wayne 7 ‘L Concise avatax: Records provide «concise syntax for declaring : . for dec ‘cases that are prinariy ued to bold data ‘Geass | Explain sealed classes in Java and their role in ceutrling inberitance hierarchies,“ = / Sealed classes: 1 Sealed clases provid Any W retrict which cases canbe subelasss of parted claorintrface oe 2 They allow youtodetne fit set oases tht ardprted o txtendor implement sealed classorntrfey= 41 Sealed clauesin Java provide a pomerulimechasin etsog tnbentace hierarchies, eabancng eeaplog aad proing APIs. al The promote stronger ype salty, et nde pian end ‘nerimaintenance of comple cla 1 Fetish map dese pe sealed clas Shape permite CBB, Rectang, Trang Class defition j ' " 6 In this example, Shape’ is declared eho ny Sr Rc err aces : ee 3 Cotroling inherent doers vg mm de ntl te eae predeied stole singe 2 Enhanced encapsulation: By renga encapeatie Ca even selec, Jou can fd contol ovr the desi of yout ——— Java Collections Framework CONTENTS Calton in Jere, Catton — ‘Framework in Java care Hierarchy of Collective Framework... 49F to 43% ‘erator Interface, Collection AAP to 4-88 terface, List Tnterace ‘ArrayList, LinkedList, Veto, Stack. AGP to 4-88 Queue Inter nnn HB 80 4 Set Inte, bse, AF to +10F “PCT sem) ~ 1 Oriented Programming with Jog ava Collections Framewory nies! wl F (CST Sem-4) Reusable implementations The fran, = Consistency : I collections in the framework follow common set of Ficerr sem) * implementations of commen data raraett ide ready tose | esata catmaon dr Oe Java? Also give| FER vaca mente Cnet —_ feacures of Collections A Galeton Ser a pid dere APT ig SSS Sc weno tame steed Sem te 2 Ths are commen er tae we tReet ing aaa en it 4. Teallows developers to easily ans’ rettieve, manipulat — mortew cen fears of Calectonts 1 United arcitecare les tamer rie ied Sate rca editing elections, 2 Generic Sapper st er sd iter inthe Coltiong framework support geaeries allowing developers to specify the type of coos ogee Dymus sty Sy ction cate stately resan Sagi tga to acommetae th lin 6 omeral af waa 4 Hiern: The Cetin ramema laude various atity Iethods td lpr for wot arching, and maniplating ‘icine 5 eater rosie wn tmnt elements ofa clacton seen cain eay tera oeecon semen GEA] wa nthe Java Catlestions framework 7 Give ita vantages ‘Anower ‘A. Java Collections framework: 1 The Ja Collection framework i tf lasses and interface that Tria "Henentatons fcommany reuable colon dats racine 2 Theda strctrscane ty, provide id, in chi Sls, maps, queues ee. ect for manipulating and storing groupe of ‘Avantage othe Jere Collection tramework a eee {interfaces and conventions, Eificieney : The framework offers siracures optimine fer varius ese ‘Type safety : Java generics are extensively used in the elections framework, providing compile tine type rate Séalability ‘Tae feamevorkspprts al fata srcture, eb developers to handle lrg datasets efficenly - Hierarchy of Collection Framework. efficent implementations of data SS ee ‘GeedS | Explain the hierarchy the Collection framework in dave. $ Tawwer | y ‘The utility package, java util) contans al the classes and terface that are required by the Eallecton framework, ; a) The collection framewark contains an interface nai an Wefable Interface which provides the iterator to iterate through alle gletons ‘Thiainteriae i extended by the main collection nteeface which acts as «afoot forthe collection framework. ‘& 2 Al the collections extend this collection ntertcthery extending the properties ofthe terator and the methods hintnterface. ‘The following figure illustrates x of the collect = framework va Collections Framewor TRIG wasn aete ntartce? What the Perponn of the ramet erator itertace in Java Collection Tarwer Iterator interface: ‘Thin iste rot terface forthe entire colletnn famework ‘Teter urn ised teaver tog clement of colection, Te proves ifr way to aces elements of Yaris celetion type seo exposing te underivng memento ets Perpose ofthe Iterator intertae’ The perpose ofthe Ierator istracecan be sumaraed flr 1 Teaver: aw: seqeatilaceimto he elements of collection, ‘Tas cebls iterating verte Aapents of acallectin without needing toto ty tera cae 22 Uniformity: erie provide common ay titrate over diffrent types of eaectiens. Tg enferaty implies the proves of trating through cola ad pretend rewsabibty , 4 Safe remoral: feraor wupyorts sale removal of elements from a ‘clei Gurtg eration. Tis preveata concortent modification excep 2 | Rohanced fr lop support :The ere ateriors tlized implicitly ihe echaned Yor op vat. Tia aia provides u concise and ‘ead terete nertlsca ait py dealing with (ere » Gee] what is Collection interface? ‘Aaower |] 1 The Collection ntrtce a the rot face terface inthe Java Collections 2 It represents a group of objects, known as. * Saryccertl th atm tre iat eae mtn ra eer elements does not specify any particular o tering of ‘The Calection nets lows duplicate ems Oriented Programming with Jara owe +8F cst Sem) Overall the Collectionintertc sens fe working with collections tetera a a uamental uling Bock It provides a common se of operations ‘fos different types of cllecions Gee | Diteretinte between Cleon an Colectonsin ure Tomer | 1 (No | Aspect | Collection Collections re amar ees] nace, | scar aa yee rane ei calleetoe manipulation. | Genericty [Can be parameleied Rot _parameterised witha type, | (operates on cllections 2 | genera. % | tnwtancer [Coliectiontican be | Collections clas iaelt implemented by | cannot instantiated, various asses. ox | Examples | Lint Set Quvue,ete. | Methods Tike 20rt0, ? v seers ete] characteristics Weed | What inList interface? ofthe Lit interface? (FZ ‘aawver | ’ A Unt inertace: 1 Thins a chidintrace of bean ita 2. Thin interface is dedicate to the data ofthe lit type in which we cam ore al the ordered collection ofthe objets. sotertace {Teas alors dupa dat te prema in Thi iirc Ilomerted by suis dase ik Arai te “Since all the subelases implement th Ht ea nants +t ject with any af these cases, B. Keycharacteristics: ava Clletions Prag HOF CHTHem-4) won rowtie) rene Uhey are inserted 2 Indexed access: Elements in lint canbe accessed by their index, List are resizable, ming they C2" BOW OF wig 4 Movable : Lists implement the lterable interface, which mean they egy be traversed using itertor Search operations: List support search operations o find the inde fa specited element PART-4 ArrayList, LinhedLit, Vetor, Stack (ue 43 | Which lames implement link interface ? on Explain ArrayList, LinkedLint, Vector, Stack in reference to link interface. ‘Answer . ‘The cases that implement thelist interface are A ArrayList: - 1 Implementation ‘ArrayList ia dynamic arraytmaedimplementation ofthe Lit interface [Peta structure 1 iternally ses an arty store Clements, which ‘Alo for fm raeornaccoss and retrieval clement by inden. 2 Pestormaes? ArrayList poids Oiitime fomplerity for adding or retrieving elements by idea. However ieting or deleting elements ‘in the middle fhe list can bower be tothe ned a shift clement ‘4 Use cases: ArrayList i mitable forcenarion where random sccese 2 snd retrieval of elements are feet, andthe lt vise is expected to ‘ena relatively stable, B § + LinkedList is « doubly linked list-baned implementation of the List interface 2 ate structure: It consis of «sequence of elements, where each element ia red inde tha, . Serres uatainsa reference athe previous and A. Performance: Licked provides 1) time, for aiding ot ‘aevigcenest she ging wren oti Ha —— a es Oriented PoRTaMing wi yy, Vector is «synch implementation ofthe Lit inert Deva structure : Similar to Array # squore elements, itty nary cu ots method, sichena yercrag ‘environments, impact performance mult -threaded PaY, case: Vector i ital ip «Ue ir tra concern ad multiple thresde Bed tage oo Hq concurrently Rn madre i Back: f Implementation Stach tic cer, [pti Out LIPO) gachanapeee " 2 DaastracturesIt porte ming li pop) 4 Performance : Stack inherits its performance eharie droves a from ‘Vector; with the additional overhead of ope operations, 4 Uae cases Stack is suitable for ‘gorithms and ‘sppliations that require IFO bavi alton, backtracking, end unde mechanism WeeAS | Compare and LinkedList, Vector, and Stack classes in Java, ee] “

    You might also like