




















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





















































1. Ho w‘compileonceandrunanywhere’isimplementedinJava,E xp lain.( 4 M) [ Ju ly 20 14 ,Jul y 20 16 ] Ar chitectur e- Neutral A centralissuefortheJavadesignerswasthatofcodelongevityandportability .On eof th e mainproblemsfacingprogrammersisthatnoguarantee existsthatif youwrit ea pr ogram today, it will run tomorro w— even onthe same machine.Operating system up grades,processorupgrades,andchangesincoresystemresourcescanallcombin eto ma keaprogrammalfunction.TheJavadesignersmadeseveralharddecisionsinth eJava la nguageandtheJavaVirtualMachineinanattempttoalterthissituation.Thei rgoalwas “w rite once; run anywhere, any time, forever.” To a great extent, this goa l was accomplished. 2. Li standexplaintheJavabuzzwords.( 6 M)[J ul y 20 14 ,July 2016 ] Sunmicrosystemofficiallydescribesjavawithalistofbuzzwordsorattributes.The y
x Sa fe:Threatofvirusesandabuseofresourcesare everywhere,javasystem notonly verifythememoryresourcesbutalsoensuresthatnovirusesarecommunicatedwithth e ap plet. The absence of pointersinjava ensurestha t program cannot gain accessto memorylocation. x Ob ject- or iented:Ja vaisanobject- orientedlanguage.Almosteverythinginjavaisobject. Alltheprogramcodes&dataresidewithinobject&classes. x Ro bust:Ja vaisastrictlytypedlanguage,becausethetypesmustmatchexactly.Itchecks yourcodeatcompiletimeaswellasatruntime.Javaisagarbagecollectedlanguage , relieving the programmers all memory management problems ( i.e., deallocation i s completelyautomatic). x Ja vaincorporatesexceptionhandlingwhichcapturesseriesoferrorsandeliminatesany riskofcrashingthesystem. x Ar chitectureneutral:Javaisthelanguagethatisnottiedtoanyparticularhardwareor op eratingsystem.Programdevelopedinjavacanbeexecutedanywhereonan ysystem. Youcan“writeonce,runanywhere,anytimeforever”.Changes&upgradesinoperatin g system,processorswillnotforceanychangesinjavaprogram.ItworksonMacintos h PC,UNIX&whateverthefutureplatformscanoffer. x In terpreted:Ja vaaccomplishesarchitectureneutralitybycompilingthejavasourcecode intoanintermediatecodecalled“bytecodes”,whichcanbeinterpretedonanysyste m th at has a proper java runtime on it. Mu ltithreaded: Java supports multithreaded pr ogrammingwhichallows youtowriteprogramsthatdomanythingssimultaneously. x Ea sytolearn:Thelanguagefeaturesfeellikethenaturalwaytodothings&encourage goodprogramming style. Since object model isboth mandatory & simple, youwil l qu icklybecomeacquaintedwit hobjectorientedstyleofprogramming. 3. Ex plain:i)>>>ii)shortcircuitlogicaloperatorsiii)foreach.( 6 M)[J ul y 20 14 ] i)intnum,den ; if(denI= 0 &&num|den> 2 ) { }
A rray s a re a way to store a list of items. Each slot of the array holds an i ndividua lelement,andyoucanplaceelementsintoorchangethecontentsorthose sl otsasyo uneedto. Threestepstocreateanarray :
1. De scribe the significance offinalandsuper,withexamples.( 6 M) [Jan 2014 , Jan 2 01 5 ,J an 2016 ] Wh en Sun wasdesigning Java, it omitted multiple inheritanc e - or more precisely mu ltipleimplementationinheritanc e- onpurpose.Yetmultipleinheritancecanbeuseful, pa rticularlywhenthepotentialancestorsofaclasshaveorthogonal concerns.Thisarticle presentsautilityclassthatnotonlyallowsmultipleinheritancetobesimulated,butalsoha s ot herfa r- reachingapplications. Here, Personisa concrete class that represents a person, while Employment isanothe r co ncreteclasst hatrepresentsthedetailsofapersonwhoisemployed.Ifyoucouldonlyput themtogether,youwouldhaveeverythingnecessarytodefineandimplementanEmploye e cl ass.ExceptinJav a- yo ucan't.Inheritingimplementationfrommorethanonesuperclass- mu ltipleimplementationinheritanc e- isnotafeatureofthelanguage.Javaallowsaclassto haveasinglesuperclassandnomore. 2. Whatisanexception?Explainthedifferentexceptionhandlingmechanisms,with an example ,( 8 M)[ Ja n 2014 ,July 2015 ] Th isisthegeneralformofanexceptio n- handlingblock: tr y { //blockofcodetobemonitoredforerror s } catch(ExceptionType 1 exOb ) { //exceptionhandlerforExceptionType 1 } catch(ExceptionType 2 exOb ) {
//exceptionhandlerforExceptionType 2 } // ... finall y { //blockofcodetobeexecutedbeforetryblockend s } DI VID E- BY - ZEROEXCEPTION Th issmallprogramhasanexpressionthatcausesadivid e- b y- zeroerror. classDivideByZer o { publicstaticvoidmain(Stringargs[] ) { intd= 0 ; inta= 42 /d ; } } Th eJavaru n- timesystemconstructsanewexceptionobjectwhenitdetectsanattemptto di vid e- by - zero.Itthenthrowsthisexception.Intheaboveexample,thereisnoexceptional ha ndlertocatchtheexception.ThedefaulthandlerprovidedbytheJ ava run- timesystemwill processanyexceptionthatisnotcaughtbyaprogram.Theoutputoftheabove progra m wh e nexecutedbythestandardJavaJDKruntimeinterpreter: java.lang.ArithemeticException:/byzer o atDivideByZero.main(DivideByZero.java: 4 ) A l th oughthedefaultexceptionhandlerisprovidedbyJavarun- timesystem,youwillusually liketohandleexceptionyourself. Thefollowingprogramincludesatryblockandacatchclause,whichprocessesth e Ar ithmeticExceptiongeneratedbythedivisio n-by- zero: classDivideByZer o {
import java.applet. * ; importjava.awt.* ; public class DrawStringApplet extends Applet { pr ivate String defaul tMessage = "Hello!"; public voidpaint(Graphicsg) { String inputFromPage = this .getParameter("Me s sage") ; if (inputFromPage == null) inputFromPage = defaultMessage ; g.drawString(inputFromPage, 50 , 25 ) ; } } HTMLfilethatreferencestheaboveapplet.
DrawString
Thisistheapplet:
Thispagewillbe veryboringi f you r browserdoesn'tunderstandJava.
**4. W hyoverridi ngme thodsareusedinjava?Example( 8 M)[ Ju ly 2016 ,July 2015 ] OverridingMethod s** x Whenamethodiscalledonanobject,Javalooksforthatmethoddefinitionintheclassof th atobject,andifitdoesn'tfindone,itp assesthemethodcalluptheclasshierarchyuntil amethoddefinitionisfound.x Method inheritance enables you to define and use methods repeatedly in subclasses withouthavingtoduplicatethecodeitself. x Ho wever,theremaybetimeswhenyouwantanobjecttorespondtothesamemethods buthavedifferentbehaviorwhenthatmethodiscalled.Inthiscase,youcanoverridetha t method.Overridingamethodinvolvesdefiningamethodinasubclassthathasthesam e si gnatureasamethodinasuperclass.The n,whenthatmethodiscalled,themethodinthe subclassisfoundandexecutedinsteadoftheoneinthesuperclass. 5. Whatismeantbyinstancevariablehiding?Howtoovercomeit? pu blicstaticvoidmain(Stringargs[]){Motorcyclem=newMotorcycle ();m.make= "Y amahaRZ 350 " ;( 4 M)[ Ju ly 20 14 ,J an 2016 ] m.color="yellow" ; Sy stem.out.println("CallingshowAtts...");m.showAtts();System.out.println( "——— — ");System.out.println("Starting engine...");m.startEngine() ; Sy stem.out.println( "—— ——"); Sy stem.ou t.p rintln("CallingshowAtts...");m.showAtts();System.out.println("——— — ");System.out.println("Starting engine...");m.startEngine() ; } Withthemain()method,theMotorcycleclassisnowanapplication,andyoucancompil e it againandthistimeit'llru n.Here'showtheoutputshouldlook: CallingshowAtts... ThismotorcycleisayellowYamahaRZ 350 Theengineisoff. Startingengine...Theengineisnowon. CallingshowAtts... ThismotorcycleisayellowYamahaRZ 350 Theengineison. Startingengine... Theengineisalreadyon.
Ap ple t: Basically,therearefourmethodsintheAppletclassonwhichanyappletisbuilt. init:Thismethodisintendedforwhateverinitializationisneededforyourapplet. Itiscalledaftertheparamattributesoftheapplettag. · start:Thismethodisautomaticallycalledafte rinitmethod.Itisalsocalled wheneveruserreturnstothepagecontainingtheappletaftervisitingotherpage s ·stop:Thismethodisautomaticallycalledwhenevertheusermovesawayfromth e pa gecontainingapplets.Youcanusethismethodtostopa nanimation. ·destroy:Thismethodisonlycalledwhenthebrowsershutsdownnormall y 8. Di fferencebetweenmethodoverloading&overriding( 6 M) [J ul y 20 15 ] OverridingMethod s x Wh enamethodiscalledonanobject,Javalooksforthatmethoddefinitionintheclassof thatobject,andifitdoesn'tfindone,itpassesthemethodcalluptheclasshierarchyunti l amethoddefinitionisfound. x Method inheritance enables you to define and use methods repeatedly in subclasses wi thouthavingtoduplicatetheco deitself. overridin g However,theremaybetimeswhenyouwantanobjecttorespondtothesamemethodsbuthav e different behaviorwhen that methodiscalled.In this case, you can override that method. Ov erridingamethodinvolvesdefiningamethodi nasubclassthathasthesamesignatureasa methodinasuperclass.Then,whenthatmethodiscalled,themethodinthesubclassisfoun d andexecutedinsteadoftheoneinthesuperclas s
1. Wh at is synchronization? Explain with an example, how synchronization is im plementedinJava .( 6 M)[ Ja n 2014 ,Ju ly 2016 , Jan 2015 ] Onefurtherareaofconcernwithinthreadsisknownas"busywaiting."Thisisthesituatio n wh ereathreadisconceptuallyidle,p erhapswaitingforsomeothersynchronousprocessing to complete,butyetitisstilloccupyingtheCPU.Toillustrate,consideraspel l- checking thread. Itreadsatextfileandsearchesforeachwordinitsdatabase.Ifawordisnotfound,th e th readco mposesalistofsuggestedcorrectionsandnotifiesthecallingprocess.Thecalling processdisplaysalistofthewhilethethreadwaits.Eventuallytheusermakesaselectio n an dthecallingprocessallowsthethreadtocontinue.Thethreadeventuallyt erminates,once thewholefilehasbeenprocessed. Wemightwritesuchcodebyusingapublicbooleanvariable,'paused,'likeso : paused=true ; parent.processWordList(aListOfWords) ; //loopuntilparentprocessclears'paused ' wh ile(paused&&!terminat ed){} //Continu e Thethreadsimplyloopscontinuallyuntilthepausedvariableissettofalse.Althoughthi s seemsintuitive,theramificationsarethattheCPUwillcontinuetospendsignificanttim e pr ocessing the loopingtime that couldbest be spent servicingotherthreads. Indeed, any attempttomovewindowsaroundonthescreenwillbenoticeablyjerky. voidsleep(longmilliseconds ) voidsleep(longmilliseconds,intnanoseconds ) Th ese methodsmake the thread pause for the specified number of milli seconds and/or nanoseconds.WhatisimportanthereisthatthethreadreallydoespauseandtakesnoCP U time.Notalloperatingsystemssupport timeresolutionsassmallasnanoseconds,andi n
sleepmethod,youhavetocatchtheexceptionthatcouldberaised(orjavacwillcomplain) , butyoudon'tneedtospecifyanycodeinthebodyoftheexceptionhandler. 2. Wh at is producer – co nsumer problem? Explain the solution for producer – co nsumerproblemwithaprogram .( 8 M)[ Ja n 2014 , Ju ly 2016 ,Jan 2015 ] ProblemDescription : In computersciencetheproduce r- co nsumerproblem(alsoknownasthe bo unded- buffer pr oblem ) is aclassicalexampleofamulti- pr ocesssynchronizationproblem.Theproblem describestwoprocesses,theproducerandtheconsumer,whoshare a co mmon,fixe d- sizebuffer. Theproducer'sjobistogenerateapieceofdata,putitintothebufferandstartagain.Atth e sa metimetheconsumerisconsumingthedata(i.e.r emovingitfromthebuffer)onepieceat atime.Theproblemistomakesurethattheproducerwon'ttrytoadddataintothebufferi f it'sfullandthattheconsumerwon'ttrytoremovedatafromanemptybuffer.Thisisthecod e fo rsolvingtheabovest ated: classBufferItem { pu blicvolatiledoublevalue= 0 ; //multiplethreadsaccesspublicvolatilebooleanoccupied =false;//somakethese`volatile' } classBoundedBuffer{// designedforasingleproducerthreadand//a single consume r threa d pr i vateintnumSlots= 0 ; privateBufferItem[]buffer=null ; privateintputIn= 0 ,takeOut= 0 ; //privateintcount= 0 ; publicBoundedBuffer(intnumSlots) { if(numSlots<= 0 )thrownewIllegalArgumentException("numSlots<= 0 ");this.numSlots = numSlots ; bu ffer=newBufferItem[numSlots]; for(inti= 0 ;i // count++ ;//racecondition!!!} publicdoublefetch() { doublevalue ; wh ile(!buffer[takeOut].occupied)//busywaitThread .currentThread().yield(); va lue=buffer[takeOut].value ; //C bu ffer[takeOut].occupied=false ; //DtakeOut=(takeOut+ 1 )%numSlots; / / co unt-- ; //racecondition!!!returnvalue; } } 3. Wh atisdelegationeventmodel?Describethesignificanceofadapterclass,withan ex ample .( 6 M)[ Ja n 2014 ,Ja n 2016 ,Ju ly 2016 ] InJava,eventsrepresentallactivitythatgoesonbetweentheuserandtheapplication. Twoeventhandlingmechanisms : De legationeventmodel:Itdefinesstandardandconsistentmechanis mstogenerateand processevents.Herethesourcegeneratesaneventandsendsittoonormorelisteners. Thelistenersimplywaitsuntilitreceivesanevent.Onceitisobtained,Itprocessesthi s ev entandreturns.Listenersshouldregisterthemselve swithasourceinordertoreceive anevennotification.Notificationsaresentonlytolistenersthatwanttoreceivethem. Event s In thedelegationmodel,a n ev ent isanobjectthatdescribesastatechangeinasource.It ca n be generated as a consequen ce of a person interacting with the elements in a graphicaluserinterface.Someoftheactivitiesthatcause eventstobegeneratedare : pressingabutton,enteringacharacterviathekeyboard,selectinganiteminalist,an d cl ickingthemouse.Event smayalsooccurthatarenotdirectlycausedbyinteractions withauserinterface.Forexample,aneventmaybegeneratedwhenatimerexpires, a counter exceeds a value, a software or hardware failure occurs, or an operation i s completed. EventClasse s T h eclassesthat representeventsareatthe coreofJava’sevent handlingmechanism. Ev entObject : It isattherootoftheJavaeventclasshierarchyin ja va.util. Itisthe
x Th eMouseEventClass Thereareeighttypesofmouseevents x Th e MouseWheelEvent Class Th e Mo useWheelEvent class encapsulates a mouse w h eelevent. x Th eTextEventClass Instancesofthisclassdescribetextevents.Thesearegeneratedby textfieldsandtextareaswhencharactersareenteredbyauserorprogram. x Th eWindowEventClass Th erearetentypesofwindowevents.The WindowEvent cl assdefinesintegerconstantsthatcanbeusedtoidentifythem. 4. What is meant by multithreaded programming? Explain with an example in terthreadcommunication( 10 M )[ Ju ly 2014 , Jan 2014 ,J an 2016 ] A threadisasinglepathofexecutionofcodeinapr ogram. x AMultithreadedprogramcontainstwoormorepartsthatcanrunconcurrently. x EachpartofsuchaprogramiscalledaThread. x Eachthreaddefinesaseparatepathofexecution.Multithreadingisaspecialized formofMultitasking. to maketheclasse sthreadable Aclasscanbemadethreadableinoneofthefollowingway s ( 1 )implementtheRunnableInterfaceandapplyitsrun()method. ( 2 )extendtheThreadclassitself.
Synchronizatio n Twoormorethreadsaccessingthesamedatasimultaneouslymayleadtolossofdat a in tegrity.Inordertoavoidthisjavausestheconceptofmonitor.Amonitorisanobj ect usedasamutuallyexclusivelock. Ata timeonlyonethreadcanaccessthe Monitor. Asecondthreadcannotenterth e monitoruntilthefirstcomesout.Tillsuchtimetheotherthreadissaidtobewaiting. Th ekeywordSynchronizedisuseinthecode toenablesynchronizationanditcanbe usedalongwithamethod. Changingthestateofthrea d Theremightbetimeswhenyouneedtotemporarilystopathreadfromprocessingan d th enresumeprocessing,suchaswhenyouwant toletanotherthreadusethec urrent resource.You can achieve thisobjective by definingyour ownsuspend and resum e methods,asshowninthefollowingexample.ThisexampledefinesaMyThreadclass. The MyThread class defines three methods: the run() method, the suspendThread( ) me tho d,andtheresumeThread()method.Inaddition,theMyThreadclassdeclaresthe instancevariablesuspended,whosevalueisusedtoindicatewhetherornotthethreadi s suspended. classMyThreadimplementsRunnable { Stringname ; Threadt ; bo oleansuspende d; MyThread() { t=newThread(this,"Thread") ; suspended=false;t.start() ; } publicvoidrun() { try { for(inti = 0 ; i < 10 ; i++){ System.out.println("Thread: "+ i); Thread.sleep( 200 ) ; synchronized(this) { while(suspended) {