Docsity

JAVA AND J2EE SOLUTIONS, Exams of Computer Science

Toggle sidebar
bg1
EE2J dna avaJ SC01 357
TIBJS ,ESC fo .tpeD egaP 1
NOITULOS REPAP NOITSEUQ
1 TINU
NOITCUDORTNI TO AJVA
.1 ,avaJ ni detnemelpmi si ’erehwyna nur dna ecno elipmoc‘ woH E .nialpx )M4(
[ yluJ J ,4102 ylu 102 6]
erutcetihcrA - lartueN
.ytilibatrop dna ytivegnol edoc fo taht saw srengised avaJ eht rof eussi lartnec A enO fo
etirw uoy fi taht stsixe eetnaraug on taht si sremmargorp gnicaf smelborp niam eht a
worromot nur lliw ti ,yadot margorp — metsys gnitarepO .enihcam emas eht no neve
enibmoc lla nac secruoser metsys eroc ni segnahc dna ,sedargpu rossecorp ,sedargpu t o
eht ni snoisiced drah lareves edam srengised avaJ ehT .noitcnuflam margorp a ekam avaJ
riehT .noitautis siht retla ot tpmetta na ni enihcaM lautriV avaJ eht dna egaugnal saw laog
laog siht ,tnetxe taerg a oT ”.reverof ,emit yna ,erehwyna nur ;ecno etirw“ saw
.dehsilpmocca
.2 .sdrowzzub avaJ eht nialpxe dna tsiL )M6( [J ylu 102 yluJ ,4102 6]
yehT .setubirtta ro sdrow zzub fo tsil a htiw avaj sebircsed yllaiciffo metsys orcim nuS
- lufrewop & elpmiS
- efaS
- detneiro tcejbO
- tsuboR
- lartuen erutcetihcrA
- deterpretnI & delipmoC
- dedaerhtitluM
- nrael ot ysaE
:swollof sa era avaJ fo serutaef tneilas ehT
x :lufrewoP & elpmiS si avaj ,gnimmargorp gnitsixe eht ot railimaf egaugnal eht ekam oT
evah uoy aedi yreve sserpxe ot uoy srewopme avaJ .++C & C no deledom naelc a ni
.yaw detneiro tcejbo
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c

Partial preview of the text

Download JAVA AND J2EE SOLUTIONS and more Exams Computer Science in PDF only on Docsity!

QUESTIONPAPERSOLUTIO N

UNIT 1

IN TRODUCTIO NTO JA VA

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

  • Simple&powerful
  • Safe
  • Objectoriented
  • Robust
  • Architectureneutral
  • Compiled&Interpreted
  • Multithreaded
  • Easytolearn ThesalientfeaturesofJavaareasfollows : x Si mple&Powerful:Tomakethelanguagefamiliartotheexistingprogramming,javais mo deledonC&C++.Javaempowersyoutoexpresseveryidea youhav einaclean objectorientedway.

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. Declareavariabletoholdthearray.
  2. Cr eateanewarrayobjectandassignittothearrayvariable.
  3. Storethingsinthatarray. E.g. String[]names ; names=newString[ 10 ] ; na mes[ 1 ] = “n 1 ”; na mes[ 2 ] = ‘n 2 ’; 6. W hatisjumpstatement?( 4 M)[ Ju ly 2014 ,July 15 ] x T heifconditional,whichenablesyoutoexecutedifferentbitsofcodebased onasimpletestinJava,isnearlyidenticaltoifstatementsinC. x ifconditionalscontainthekeywordif,followedbyabooleantest,followed byastatement(oftenablockstatement)toexecuteifthetestistrue : x if(x Sy ntax:test?trueresult :falseresult T h e t est isanexpressionthatreturnstrueorfalse,justlikethetestintheifstatement.If t hetestistrue,theconditional operatorreturnsthevalueo f tr ueresult; ifit'sfalse,it re turnsthevalueo f fa lseresult. Fo rexample,thefollowingconditionalteststhevalues of xandy,returnsthesmallero fthetwo,andassignsthatvaluetothevariablesmaller: intsmaller=x

UNIT 2

C LASSE S, IN HERITANCE, EX CEPT IO NS, APPLETS

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

UNIT 3

MUL TI TH READED PR OGRAMMING, EV ENT HANDLING

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.

  1. ImplementingRunnableInterface:Theeasiestwaytocreateathreadistocreatea cl asst hatimplementstheRunnableinterface.ToimplementRunnable,aclassneed onlyimplementasinglemethodcalledrun(). TheFormatofthatfunctionispublicvoidrun().
  2. ExtendingThread:Thesecondwaytocreateathreadistocreateanewclassthat ex te ndstheThreadclassandthentocreateaninstanceofthisclass.Thisclassmust overridetherun()methodwhichistheentrypointforthenewthread. 5. Wh atismeantbythreadpriority?Howitisassigned( 6 M)[ Ju ly 2014 Jan 2015 ] Th e example in the n ext segment demonstrates the use of Runnable and its implementation.

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