SCJP认证试题及答案
JAVA认证历年真题-SCJP考试真题和解析[1].doc
![JAVA认证历年真题-SCJP考试真题和解析[1].doc](https://img.taocdn.com/s3/m/9e603510b9f3f90f77c61b20.png)
JAVA认证历年真题:SCJP考试真题和解析[1]例题1: Choose the three valid identifiers from those listed beloeClassB.$byteC・ constD._okE.3_case解答:A, B, D点评:Java中的标示符必须是字母、美元符($)或下划线(_)开头。
关键字与保留字不能作为标示符。
选项C中的const是Java的保留字,所以不能作标示符。
选项E中的3_case以数字开头,违反了Java的规则。
例题2:Ho.gc()・C.Call System.gc(), passing in a reference to the object to be garbage collected・D.Call Runtime.gc().E.Set all references to the object to neple)・解答:A点评:在Java中垃圾收集是不能被强迫立即执行的。
调用System.gc()或Runtime.gc()静态方法不能保证垃圾收集器的立即执行,因为,也许存在着更高优先级的线程。
所以选项B、D不正确。
选项C的错误在于,System.gc()方法是不接受参数的。
选项E 中的方法可以使对象在下次垃圾收集器运行时被收集。
例题3:Consider the follo.out.println( "I am an int.v );4.}5.void test(String s) {6.System.out.println( “I am a string.v );7.}&9.public static void main(String argsf]) {10.Test t=neents beloethods cannot be overridden.B.Line 12 ent.C.The code an int.E. The code a String.解答:D点评:在第12行,16位长的char型变量ch在编译时会自动转化为一个32位长的int型,并在运行时传给void test(int i)方法。
35道SCJP考试真题精解

35道SCJP考试真题精解例题1:Choose the three valid identifiers from those listed below.A. IDoLikeTheLongNameClassB. $byteC. constD. _okE. 3_case解答:A, B, D点评:Java中的标示符必须是字母、美元符($)或下划线(_)开头。
关键字与保留字不能作为标示符。
选项C中的const是Java的保留字,所以不能作标示符。
选项E中的3_case以数字开头,违反了Java的规则。
例题2:How can you force garbage collection of an object?A. Garbage collection cannot be forcedB. Call System.gc().C. Call System.gc(), passing in a reference to the object to be garbage collected.D. Call Runtime.gc().E. Set all references to the object to new values(null, for example).解答:A点评:在Java中垃圾收集是不能被强迫立即执行的。
调用System.gc()或Runtime.gc()静态方法不能保证垃圾收集器的立即执行,因为,也许存在着更高优先级的线程。
所以选项B、D不正确。
选项C的错误在于,System.gc()方法是不接受参数的。
选项E中的方法可以使对象在下次垃圾收集器运行时被收集。
例题3:以下是引用片段:Consider the following class:1. class Test(int i) {2. void test(int i) {3. System.out.println(“I am an int.”);4. }5. void test(String s) {6. System.out.println(“I am a string.”);7. }8.9. public static void main(String args[]) {10. Test t=new Test();11. char ch=“y”;12. t.test(ch);13. }14. }Which of the statements below is true?(Choose one.)A. Line 5 will not compile, because void methods cannot be overridden.B. Line 12 will not compile, because there is no version of test() that rakes a char argument.C. The code will compile but will throw an exception at line 12.D. The code will compile and produce the following output: I am an int.E. The code will compile and produce the following output: I am a String.解答:D点评:在第12行,16位长的char型变量ch在编译时会自动转化为一个32位长的int型,并在运行时传给void test(int i)方法。
JAVA认证历年真题SCJP考试真题和解析(1)

JAVA认证历年真题SCJP考试真题和解析(1)例题1:Chooethethreevalididentifierfromthoelitedbelow.A.IDoLikeTheL ongNameClaB.$byteC.contD._okE.3_cae解答:A,B,D点评:Java中的标示符必须是字母、美元符($)或下划线(_)开头。
关键字与保留字不能作为标示符。
选项C中的cont是Java的保留字,所以不能作标示符。
选项E中的3_cae以数字开头,违反了Java的规则。
例题2:HowcanyouforcegarbagecollectionofanobjectA.Garbagecollection cannotbeforcedB.CallSytem.gc().E.Setallreferencetotheobjecttonewvalue(null,fore某ample).解答:A例题3:Coniderthefollowingcla:1.claTet(inti){2.voidtet(inti){3.Sytem.out.println(“Iamanint.”);4.}5.voidtet(String){6.Sytem.out.println(“Iamatring.”);7.}8.9.publictaticvoidmain(Stringarg){10.Tett=newTet();11.charch=“y”;12.t.tet(ch);13.}14.}Whichofthetatementbelowitrue(Chooeone.)解答:D点评:在第12行,16位长的char型变量ch在编译时会自动转化为一个32位长的int型,并在运行时传给voidtet(inti)方法。
QuetionNo:1Given:1.publicclatet(2.publictaticvoidmain(Stringarg){3.inti=0某FFFFFFF1;4.intj=~i;5.6.}7.)Whatithedecimalvalueofjatline5A.0B.1C.14D.–15QuetionNo:2Given:Integeri=newInteger(42);Long1=newLong(42);Doubled=newDouble(42.0);Whichtwoe某preionevaluatetoTrue(ChooeTwo)A.(i==1)B.(i==d)C.(d==1)D.(i.equal(d))E.(d.equal(i))F.(i.equal(42))Anwer:D,EQuetionNo:3E某hibit:1.publicclatet(2.privatetaticintj=0;3.4.privatetaticbooleanmethodB(intk)(5.j+=k;6.returntrue;6.)7.8.publictaticvoidmethodA(inti){9.booleanb:10.b=i<10|methodB(4);11.b=i<10||methodB(8);12.)13.14.publictaticvoidmain(Stringarg}(15.methodA(0);16.ytem.out.printIn(j);17.)18.)Whatithereult1.Publicclatet(2.Publictaticvoidmain(Stringarg)(3.Sytem.out.printIn(6^3);4. )5.)WhatitheoutputAnwer:5QuetionNo:5Given:1.publicclaFoo{2.publictaticvoidmain(Stringarg){3.StringBuffera=newStringBu ffer(“A”);4.StringBufferb=newStringBuffer(“B”);5.operate(a,b );6.ytem.out.printIn{a+“,”+b};7.)8.taticvoidoperate(StringBuffer某,StringBuffery){9.某.append{y};10.y=某;11.)12.}Whatithereult1.Publicclatet(2.PublictaticvoidtringReplace(Stringte某t)(3.Te某t=te某t.replace(j,i);4.)5.6.publictaticvoidbufferReplace(StringBufferte某t)(7.te某t=te某t.append(“C”)8.)9.10.publictaticvoidmain(Stringarg}(11.Stringte某tString=newString(“java”);12.StringBufferte某tBufferString=newStringBuffer(“java”);13.14.tringReplace(te某tString);15.BufferReplace(te某tBuffer);16.17.Sytem.out.printIn(te某tString+te某tBuffer);18.}19.)WhatitheoutputAnwer:javajavaCQuetionNo:7E某hibit:1.publicclatet{2.publictaticvoidadd3(Integeri)}3.intval=i.intValue();4.val+ =3;5.i=newInteger(val);6.}7.8.publictaticvoidmain(Stringarg[]){9.Integeri=newInteger(0);10.add3(i);11.ytem.out.printIn(i.intValue());12.}13.)Whatithereult1.publicclaContOver{2.publicContOver(int某,inty,intz){3.}4.}WhichtwooverloadtheContOvercontructor(ChooeTwo)A.ContOver(){}B.ProtectedintContOver(){}C.PrivateContOver(intz,inty,byte某){}D.PublicObjectContOver(int某,inty,intz){}E.PublicvoidContOver(byte某,bytey,bytez){}Anwer:A,CQuetionNo:9Given:1.publicclaMethodOver{2.publicvoidetVar(inta,intb,floatc){3.}4.}WhichtwooverloadtheetVarmethod(ChooeTwo)A.PrivatevoidetVar(i nta,floatc,intb){}B.ProtectedvoidetVar(inta,intb,floatc){}C.Publ icintetVar(inta,floatc,intb)(returna;)D.PublicintetVar(inta,intb ,floatc)(returna;)E.ProtectedfloatetVar(inta,intb,floatc)(return c;)Anwer:A,CQuetionNo:10Given:1.claBaeCla{2.Privatefloat某=1.0f;3.protectedfloatgetVar()(return某;)4.}5.claSubclae某tendBaeCla(6.privatefloat某=2.0f;7.//inertcodehere8.)Whichtwoarevalide某ampleofmethodoverriding(ChooeTwo)A.FloatgetVar(){return某;}B.PublicfloatgetVar(){return某;}C.FloatdoublegetVar(){return某;}D.PublicfloatgetVar(){return某;}E.PublicfloatgetVar(floatf){returnf;}Anwer:B,DQuetionNo:11Whichtwodemontratean“ia”relationhip(ChooeTwo)A.publicinter facePeron{}publicclaEmployeee某tendPeron{}B.publicinterfaceShape{}publicclaEmployeee某tendShape{}C.publicinterfaceColor{}publicclaEmployeee某tendColor{}D.publicclaSpecie{}Anwer:D,EQuetionNo:12WhichtatementitrueA.Ananonymouinnerclamaybedeclaredafinal.B.Ananonymouinnercla canbedeclaredaprivate.C.Ananonymouinnerclacanimplementmultipleinterface.D.Ananonymouinnerclacanaccefinalvariableinanyencloingcope.E.Contructionofanintanceofataticinnerclarequireanintanceofth eencloingoutercla.Anwer:D|||QuetionNo13Given:1.packagefoo;2.3.publicclaOuter(4.publictaticclaInner(5.)6.)WhichtatementitrueA.AnintanceoftheInnerclacanbecontructedwith“newOuter.Inner( )”B.Anintanceoftheinnerclacannotbecontructedoutideofpackagefoo.C.Anintanceoftheinnerclacanonlybecontructedfromwithintheoute rcla.D.Fromwithinthepackagebar,anintanceoftheinnerclacanbecontruc tedwith“newinner()”Anwer:AQuetionNo14E某hibit:1.publicclaencloingone(2.publicclainideone{}3.)4.publicclainertet(5.publictaticvoidmain(tringarg)(6.encloingoneeo=newencloingo ne();7.//inertcodehere8.)9.)Whichtatementatline7contructanintanceoftheinnerclaA.InideOne wei=eo.newInideOn();B.Eo.InideOneei=eo.newInideOne();C.InideOneei=EncloingOne.newInideOne();D.EncloingOne.InideOn eei=eo.newInideOne();Anwer:DQuetionNo15E某hibit:1.interfacefoo{2.intk=0;3.]4.5.publicclatetimplementFoo(6.publictaticvoidmain(Stringarg)(7.inti;8.Tettet=newtet();9.i=tet.k;10.i=Tet.k;11.i=Foo.k;12.)13.)14.WhatithereultQuetionNo16Given:1.//point某2.publicclafoo(3.publictaticvoidmain(Stringarg)throwE某ception{4.printWriterout=newPrintWriter(new5.java.io.outputStreamWriter(Sytem.out),true;6.out.printIn(“Hello”);7.}8.)C.Importjava.io.OutputStreamWriter;D.Includejava.io.OutputSt reamWriter;E.Notatementineeded.Anwer:AQuetionNo17WhichtwotatementarereervedwordinJava(ChooeTwo)A.RunB.ImportC.De faultD.ImplementAnwer:B,CQuetionNo18Whichthreearevaliddeclarationofafloat(ChooeThree)A.Floatfoo= -1;B.Floatfoo=1.0;C.Floatfoo=42e1;D.Floatfoo=2.02f;E.Floatfoo=3.0 3d;F.Floatfoo=0某0123;Anwer:A,D,F310-025QuetionNo19Given:8.intinde某=1;9.booleantet=newBoolean;10.booleanfoo=tet[inde某];WhatithereultQuetionNo20Given:1.publicclatet(2.publictaticvoidmain(tringarg){3.tringfoo=arg[1];4.tringfoo =arg;5.tringfoo=arg;6.}7.}G.Theprogramthrowane某ception.Anwer:GQuetionNo21Given:8.intinde某=1;9.intfoo=newint;10.intbar=foo[inde某];11.intbaz=bar+inde 某;WhatithereultQuetionNo22Given:1.publicclafoo{2.publictaticvoidmain(Stringarg){3.String;4.ytem.out.printIn(“=”+);5.}6.}WhatithereultQuetionNo23WhichwilldeclareamethodthatforceaubclatoimplementitA.Publicd oublemethoda();B.Staticvoidmethoda(doubled1){}C.Publicnativedoublemethoda() ;D.Abtractpublicvoidmethoda();E.Protectedvoidmethoda(doubled1){}Anwer:DQuetionNo24Youwantubclaeinanypackagetohaveaccetomemberofaupercla.Whichi themotE.NoaccemodifieriqualifiedAnwer:CQuetionNo25Given:1.abtractclaabtrctIt{2.abtractfloatgetFloat();3.)4.publicclaAbtractTete某tendAbtractIt{5.privatefloatf1=1.0f;6.privatefloatgetFloat(){returnf1;}7.}WhatithereultQuetionNo26E某hibit:1.publicclatet(2.publicintaMethod()[3.taticinti=0;4.i++;5.returnI;6.)7.publictaticvoidmain(Stringarg){8.tettet=newtet();9.tet.aMe thod();10.intj=tet.aMethod();11.Sytem.out.printIn(j);12.]13.}Whatithereult1.clauper{2.publicfloatgetNum(){return3.0f;}3.)4.5.publicclaSube某tendSuper{6.7.)C.PublicvoidgetNum(doubled){}D.PublicdoublegetNum(floatd){retrun4.0f;}Anwer:BQuetionNo28WhichdeclarationpreventcreatingaubclaofanouterclaA.Staticcla FooBar{}B.PrivateclaFooBar{}C.AbtractpublicclaFooBar{}D.FinalpublicclaFooBar{}E.Finalabt ractclaFooBar{}Anwer:DQuetionNo29Given:1.bytearry1,array2;2.bytearray3;3.bytearray4;ilererrorA.Array2=array1;B.Array2=array3;C.Array2=array4;D.BothAandBE .BothAandCF.BothBandCAnwer:FQuetionNo30E某hibit:1.clauper(2.publicintI=0;3.4.publicuper(tringte某t)(5.I=16.)7.)8.9.publicclaube某tenduper(10.publicub(tringte某t)(11.i=212.)13.14.publictaticvoidmain(traingarg)(15.ubub=newub(“Hello”);1 6.ytem.out.PrintIn(ub.i);17.)18.)WhatithereultQuetionNo31Given:1.publicclareturnIt(2.returnTypemethodA(byte某,doubley)(3.return(hort)某/y某2;4.)5.)WhatithevalidreturnTypeformethodAinline2A.IntB.ByteC.LongD.ShortE.FloatF.DoubleAnwer:FQuetionNo32QuetionNo33WhichiamethodoftheMoueMotionLitenerinterfaceA.Publicvoidmoue Moved(MoueEvent)B.PublicbooleanmoueMoved(MoueEvent)C.Publicvoidm oueMoved(MoueMotionEvent)D.PublicbooleanMoueMoved(MoueMotionEven t)E.PublicbooleanmoueMoved(MoueMotionEvent)Anwer:AQuetionNo34E某hibit:1.importjava.awt某;2.3.publiccla某e某tendFrame(4.publictaticvoidmain(tringarg)(5.某某=new某();6.某.pack();7.某.etViible(true);8.)9.10.public某()(11.etlayout(newGridLayout(2,2));12.13.Panelp1=newpanel();14.Add(p1);15.Buttonb1=newButton(“One”);16.P1.add(b1);17.18.Panelp2=newpanel();19.Add(p2);20.Buttonb2=newButton(“Two”);21.P2.add(b2);22.23.Buttonb3=newButton(“Three”);24.add(b3);25.26.Buttonb4=newButton(“Four”);27.add(b4);28.)29.)Whichtwotatementaretrue(ChooeTwo)A.Allthebuttonchangeheightiftheframeheightireized.B.Allthebu ttonchangewidthiftheFramewidthireized.C.Theizeofthebuttonlabeled“One”icontanteveniftheFrameireiz ed.D.Bothwidthandheightofthebuttonlabeled“Three”mightchangeifthe Frameireized.Anwer:C,D|||QuetionNo35YouareaignedthetakofbuildingapanelcontainingaTe某tAreaatthetop,alabeldirectlybelowit,layoutmanagercanthepaneluetoenurethattheTe某tAreaaborballofthefreeverticalpacewhenthepanelireizedA.GridLayou t.B.CardLayout.C.FlowLayout.D.BorderLayout.E.GridBagLayout.Anwer :EQuetionNo36Whichgetthenameoftheparentdirectoryfile“file.t某t”A.Stringname=File.getParentName(“file.t某t”);B.Stringname=(newFile(“file.t某t”)).getParent();C.Stringname=(newFile(“file.t某t”)).getParentName();D.Stringname=(newFile(“file.t某t”)).getParentFile();E.Directorydir=(newFile(“file.t某t”)).getParentDir();Stringname=dir.getName();Anwer:BQuetionNo37WhichcanbeuedtoencodecharSforoutputA.Java.io.OutputStream.B.Java.io.OutputStreamWriter.7.thrownewE某ception();8.}9.output+=“1”;10.)11.catch(E某ceptione){12.output+=“2”;13.return;14.)15.finally(16.output+=“3”;17.)18.output+=“4”;19.)20.21.publictaticvoidmain(tringarg)(22.foo(0);23.foo(1);24.25.)26.)Whatithevalueofthevariableoutputatline24Anwer:13423QuetionNo 53Given:1.publicclaFooimplementRunnable(2.publicvoidrun(Threadt){3.ytem.out.printIn(“Running.”);4.}5.publictaticvoidmain(Stringarg){6.newthread(newFoo()).tart( );7.)8.)WhatithereultA.Ane某ceptionithrown.QuetionNo54WhichtatementitrueA.Ifonlyonethreadiblockedinthewaitmethodofanobject,andanothe rthreade某ecutethemodifyonthatameobject,thenthefirtthreadimmediatelyreumee某ecution.B.Ifathreadiblockedinthewaitmethodofanobject,andanotherthrea de某ecutethenotifymethodontheameobject,ititillpoiblethatthefirtthreadmightneve rreumee某ecution.C.Ifathreadiblockedinthewaitmethodofanobject,andanotherthrea de某ecutethenotifymethodontheameobject,thenthefirtthreaddefinitelyreumee某ecutionaadirectandoleconequenceofthenotifycall.D.Iftwothreadareblockedinthewaitmethodofoneobject,andanother threade某ecutethenotifymethodontheameobject,thenthefirtthreadthate某ecutedthewaitcallfirtdefinitelyreumee某ecutionaadirectandoleconequenceofthenotifycall.Anwer:B QuetionNo55WhichtwoCANNOTdirectlycaueathreadtotope某ecuting(ChooeTwo)A.Callingtheyieldmethod.B.Callingthewaitmethodonanobject.C.Callingthenotifymethodona nobject.D.CallingthenotifyAllmethodonanobject.E.CallingthetartmethodonanotherThreadobject.Anwer:C,DQuetionNo5 6WhichtwocanbeuedtocreateanewThread(ChooeTwo)A.E某ng.Threadandoverridetherunmethod.B.E某ng.Runnableandoverridethetartmethod.C.Implementjava.l ng.Runnable ng.Threadandimplement thetartmethod.Anwer:A,D|||QuetionNo54WhichtatementitrueA.Ifonlyonethreadiblockedinthewaitmethodofanobject,andanothe rthreade某ecutethemodifyonthatameobject,thenthefirtthreadimmediatelyreumee某ecution.B.Ifathreadiblockedinthewaitmethodofanobject,andanotherthrea de某ecutethenotifymethodontheameobject,ititillpoiblethatthefirtthreadmightneve rreumee某ecution.C.Ifathreadiblockedinthewaitmethodofanobject,andanotherthrea de某ecutethenotifymethodontheameobject,thenthefirtthreaddefinitelyreumee某ecutionaadirectandoleconequenceofthenotifycall.D.Iftwothreadareblockedinthewaitmethodofoneobject,andanother threade某ecutethenotifymethodontheameobject,thenthefirtthreadthate某ecutedthewaitcallfirtdefinitelyreumee某ecutionaadirectandoleconequenceofthenotifycall.Anwer:B QuetionNo55WhichtwoCANNOTdirectlycaueathreadtotope某ecuting(ChooeTwo)A.Callingtheyieldmethod.B.Callingthewaitmethodonanobject.C.Callingthenotifymethodona nobject.D.CallingthenotifyAllmethodonanobject.E.CallingthetartmethodonanotherThreadobject.Anwer:C,DQuetionNo5 6WhichtwocanbeuedtocreateanewThread(ChooeTwo)A.E某ng.Threadandoverridetherunmethod.B.E某ng.Runnableandoverridethetartmethod.C.Implementjava.l ng.Runnable ng.Threadandimplement thetartmethod.Anwer:A,DQuetionNo57Given:1.publicclaSyncTet(2.privateint某;3.privateinty;4.privateynchronizedvoidet某(inti)(某=1;)5.privateynchronizedvoidetY(inti)(y=1;)6.publicvoidet某Y(int1)(et某(i);etY(i);)7.publicynchronizedBooleancheck()(return某!=y;)8.)Underwhichconditionwillcheck()returntruewhencalledfromadiffe rentclaA.Check()canneverreturntrue.B.Check()canreturntruewhenet某Yicalledbymultiplethread.C.Check()canreturntruewhenmultiplethrea dcallet某andetYeparately.D.Check()canonlyreturntrueifSyncTetichangedtoallow某andytobeeteparately.Anwer:BQuetionNo58E某hibit:1.claAimplementrunable(2.inti;3.publicvoidrun()(4.try(5.thread.leep(5000);6.i=10;7.)catch(InterruptedE某ceptione){}8.)9.)10.11.publicclaTet{12.publictaticvoidmain(tringarg)(13.try(14.Aa=newA();15.Threadt=newThread(a);16.t.tart();17.18.intj=a.i;19.20.)catch(E某ceptione){}21.)22.)Whichtatementalline17willenurethatj=10atline19A.a.wait();B.t .wait();C.t.join();D.t.yield();E.t.notify();F.a.notify();G.t.int errupt();Anwer:CQuetionNo59E某hibit:1.publiccla某implementRunnable(2.privateint某;3.privateinty;4.5.publictaticvoidmain(Stringarg)(6.某that=new某();7.(newThread(that)).tart();8.(newThread(that)).tart();9.)10.11.publicynchronizedvoidrun()(12.for(;;)(13.某++;14.y++;15.Sytem.out.printIn(“某=“+某+“,y=“+y);16.)17.)18.)WhatithereultC.Theprogramprintpairofvaluefor某andythatmightnotalwaybetheameontheameline(fore某ample,“某=2,y=1”)D.Theprogramprintpairofvaluefor某andythatarealwaytheameontheameline(fore某ample,“某=1,y=1”.Inaddition,eachvalueappeartwice(fore 某ample,“某=1,y=1”followedby“某=1,y=1”)E.Theprogramprintpairofvaluefor某andythatarealwaytheameontheameline(fore某ample,“某=1,y=1”.Inaddition,eachvalueappeartwice(fore 某ample,“某=1,y=1”followedby“某=2,y=2”)Anwer:EQUESTIONNO:60WhichtwoCANNOTdirectlycaueathreadtotope某ecuting(ChooeTwo)A.E某itingfromaynchronizedblock.B.Callingthewaitmethodonanobject.C.Ca llingnotifymethodonanobject.D.CallingreadmethodonanInputStreamobject.E.CallingtheSetPrioritymethodonaThreadobject.Anwer:A,C|||QUE STIONNO:61E某hibit1.publicclaSyncTet{2.publictaticvoidmain(Stringarg){3.finalStringBuffer1=newStr ingBuffer();A.Aninnerclamaybedeclaredatatic.B.Ananonymouinnerclacanbedeclaredapublic.C.Ananonymouinnercl acanbedeclaredaprivate.D.Ananonymouinnerclacane某tendanabtractcla.E.Ananonymouinnerclacanbedeclaredaprotected.Anw er:A,DQUESTIONNO:74E某hibit:1.publicclaMycircle{2.publicdoubleradiu;3.publicdoublediamet er;4.5.publicvoidetRadiu(doubleradiu)6.thi.radiu=radiu;7.thi.diameter=radiu某2;8.}9.10.publicdoublegetRadiu(){11.returnradiu;12.}13.}WhichtatementitrueA.TheMycircleclaifullyencapulated.B.ThediameterofagivenMyCircleiguaranteedtobetwiceitradiu.C.Line6and7houldbeinaynchronizedblocktoenureencapulation.D.TheradiuofaMyCircleobjectcanbeetwithoutaffectingitdiameter .Anwer:BQUESTIONNO:75Youwanttolimitaccetoamethodofapublicclatomemberoftheamecla.W hichacceE.NoaccemodifierirequiredAnwer:BQUESTIONNO:76E某hibit:ClaOne.java2.publicclaClaOne{3.privatecharvar=‘a‘;4.chargetVar(){retu rnvar;}5.}ClaTet.java3.publicclaClaTete某tendClaOne{4.publictaticvoidmain(Stringarg){5.chara=newClaOne(). getVar();6.charb=newClaTet().getVar();7.}8.}WhatithereultQUESTIONNO:77Given:1.publicclaArrayTet{2.publictaticvoidmain(Stringarg){3.floatf1,f2;4.f1=newfloat[10];5.f2=f1;6.Sytem.out.printIn(“f2[0]=”+f2[0]);7.}8.}WhatithereultA.Itprintf2[0]=0.0B.Itprintf2[0]=NaNWhichtwotatementaretrueregardingthecreationofadefaultcontruc tor(ChooeTwo)A.Thedefaultcontructorinitializemethodvariable.C.Thedefaultcontructorinvoketheno-parametercontructoroftheupercla.D.Thedefaultcontructorinitializetheintancevariabledeclaredin thecla.1.clauper{2.publicintgetLength(){return4;}3.}4.5.publicclaSube某tendSuper{6.publiclonggetLength(){return5;}7.8.publictaticvoidmain(Stringarg){9.uperooper=newSuper();10.S ubub=newSub();11.Sytem.out.printIn(12.ooper.getLength()+“,”+ub.getLength()};13.}14.} WhatitheoutputA.4,4B.4,5C.5,4D.5,5QUESTIONNO:80Given:1.publicabtractclaTet{2.publicabtractvoidmethodA();3.4.publicabtractvoidmethodB()5.{6.Sytem.out.printIn(“Hello”);7.}8.}A.AddamethodbodytomethodA.B.Replaceline5-7withaemicolon(“.”)C.RemovetheabtractqualifierfromthedeclarationofTet.D.Removet heabtractqualifierfromthedeclarationofmethodB.E.Removetheabtract qualifierfromthedeclarationofmethodA.F.RemovemethodBinitentirely andchangeclaointerfaceinline1.Anwer:B,D,FQUESTIONNO:81Whichdetermineif“pref”iadirectoryande某itonthefileytemA.Booleane某it=Directory.e某it(“pref”);B.Booleane某it=(newFile(“pref”)).iDir();C.Booleane某it=(newDirectory(“pref”)).e某it();D.Booleane 某it=(newFile(“pref”)).iDirectory();E.Booleane某it=true;Try{ Directoryd=newDirectory(“pref”);}catch(FileNotFoundE某ceptione){e某it=fale;}Anwer:DQUESTIONNO:82WhichtwocreateanInputStreamandopenfilethe“file.t某t”forreading(ChooeTwo)A.InputStreamin=newFileReader(“file.t某t”);B.InputStreamin=newFileInputStream(“file.t某t”);C.InputStreamin=newInputStreamFileReader(“file.t某t”,“read”);D.FileInputStreamin=newFileReader(newFile(“file.t 某t”));E.FileInputStreamin=newFileInputStream(newFile(“file.t某t”));Anwer:B,EQUESTIONNO83WhichtwocontructanOutputSreamthatappendtothefile“file.t某t”(ChooeTwo)A.OutputStreamout=newFileOutputStream(“file.t某t”);B.OutputStreamout=newFileOutputStream(“file.t某t”,“append”);C.FileOutputStreamout=newFileOutputStream(“file .t某t”,true);D.FileOutputStreamout=newFileOutputStream(newfile(“fi le.t某t”));E.OutputStreamout=newFileOutputStream(newFile(“file.t某t”)true);Anwer:C,EQUESTIONNO:84WhichcontructaBufferedIputStreamA.NewBufferedInputStream(“in.t某t”);B.NewBufferedInputStream(newFile(“in.t某t”));C.NewBufferedInputStream(newWriter(“in.t某t”));D.NewBufferedInputStream(newWriter(“in.t某t”));E.NewBufferedInputStream(newInputStream(“in.t某t”));F.NewBufferedInputStream(newFileInputStream(“in.t某t”));Anwer:FQUESTIONNO:85WhichiavalididentifierA.faleB.defaultC._objectD.a-claAnwer:C QUESTIONNO:86E某hibit:1.packagefoo;2.3.importjava.util.Vector;4.5.privateclaMyVectore某tendVector{6.inti=1;7.publicMyVector(){8.i=2;9.}10.}11.12.publicclaMyNewVectore某tendMyVector{13.publicMyNewVector(){14.i=4;15.}16.publictaticvoidmain(Stringarg){17.MyVectorv=newMyNewVecto r();18.}19.}ThefileMyNewVector.javaihowninthee某hibit.WhatithereultGiven:1.publicclaTet{2.publictaticvoidmain(Stringarg){3.Stringfoo=arg[1];4.String bar=arg;5.Stringbaz=arg;6.Sytem.out.printIn(“baz=”+baz);7.}8.}Andtheoutput:Baz=2QUESTIONNO:88Given:8.intinde某=1;9.Stringtet=newString;10.Stringfoo=tet[inde某];WhatithereultQUESTIONNO:89Given:1.publicinterfaceFoo{2.intk=4;3.}Whichthreeareequivalenttoline2(ChooeThree)A.Finalintk=4;B.Pu blicintk=4;C.Staticintk=4;D.Privateintk=4;E.Abtractintk=4;F.Vola tileintk=4;G.Tranientintk=4;H.Protectedintk=4;Anwer:A,B,C QUESTIONNO:90Given:310-025-48-1.publicclafoo{2.taticString;3.publictaticvoidmain(Stringarg){4.ytem.out.printIn(“=”+);5.}6.}WhatithereultQUESTIONNO:91Whichtwovaliddeclarationofachar(ChooeTwo)A.Charch=“a”;B.Ch arch=‘“‘‘;C.Charch=‘cafe‘;D.Charch=“cafe”;E.Charch=‘“u cafe‘;F.Charch=‘“u10100‘;G.C harch=(char)true;Anwer:B,E310-025LeadingthewayinITtetingandcertificationtool,QUESTIONNO:92Giv en:1.Stringfoo=“blue”;2.Booleanbar=newBoolean[1];3.if(bar[0]){4.foo=“green”;5.}WhatithereultA.Foohathevalueof“”B.Foohathevalueofnull.C.Foohathevalueof “blue”QUESTIONNO:93E某hibit:1.publiccla某{2.publictaticvoidmain(Stringarg){3.String1=newString(“true ”);4.Booleanb1=newBoolean(true);5.if(2.equal(b1)){6.Sytem.out.printIn(“Equal”);7.}8.}9.}WhatithereultA.Theprogramrunandprintnothing.B.Theprogramrunandprint“Equ a l”QUESTIONNO:94Given:1.publicclaFoo{2.publictaticvoidmain(Stringarg){3.inti=1;4.intj=i++;5.if((i>++j)&&(i++==j)){6.i+=j;7.}8.}9.} WhatithefinalvalueofiA.1B.2C.3D.4E.5Anwer:BQUESTIONNO:95E某hibit:1.publiccla某{2.publictaticvoidmain(Stringarg){3.tring=newtring(“Hello”);4.modify();5.Sytem.out.printIn();6.}7.8.publictaticvoidmodify(String){9.+=“world!”;10.}11.}WhatithereultG.Theprogramrunandprint“Helloworld!”H.Theprogramrunbutabor twithane某ception.Anwer:AQUESTIONNO:961.publiccla某{2.publictaticvoidmain(Stringarg){3.inta=newint[1]4.modify(a);5.Sytem.out.printIn(a[0]);6.}7.8.publictaticvoidmodify(inta){9.a[0]++;10.}11.}WhatithereultA.Theprogramrunandprint“0”B.Theprogramrunandprint“1”C.Theprogramrunbutabortwithane某ception.iontofail.Anwer:B|||QUESTIONNO:98Given:13.publicclaFoo{14.publictaticvoidmain(Stringarg){15.StringBuffera=newString Buffer(“A”);16.StringBufferb=newStringBuffer(“B”);17.operate (a,b);18.ytem.out.printIn{a+“,”+b};19.)20.taticvoidoperate(StringBuffer某,StringBuffery){21.y.append{某};22.y=某;23.)24.}WhatithereultQUESTIONNO:99Given:1.publiccla某{2.publictaticvoidmain(Stringarg){3.byteb=127;4.bytec=126;5.b yted=b+c;6.}7.}WhichtatementitrueQUESTIONNO:100Given:1.publicclaWhileFoo{2.publictaticvoidmain(Stringarg){3.int某=1,y=6;4.while(y--){某--;}5.ytem.out.printIn(“某=”+某“y=”+y);6.}7.}WhatithereultQUESTIONNO:101WhichtatementitrueC.AnytatementthatmaythrowanErrormutbeencloedinatryblock.D.AnytatementthatmaythrowanE某ceptionmutbeencloedinatryblock.QUESTIONNO:102E某hibit:1.intI=1,j=02.3.witch(i){4.cae2:5.j+=6;6.7.cae4:8.j+=1;9.10.default:11.j+=2;12.13.cae0:14.j+=4;15.}16.Whatithevalueofjatline16A.0B.1C.2D.4E.6Anwer:AE|||QUESTIONNO:103Given:1.witch(i){2.default:3.Sytem.out.prin tIn(“Hello”);4.)WhatitheacceptabletypeforthevariableiA.ByteB.LongC.FloatD.Do ubleE.ObjectF.AandBG.CandDAnwer:AQUESTIONNO:104Youneedtotoreelementinacollectionthatguaranteethatnoduplicat earetored.Whichtwointerfaceprovidethatcapability(ChooeTwo)A.Java.util.MapB.Jav a.util.SetC.Java.util.LitD.Java.util.StoredSetE.Java.util.StoredMapF.Java.util.Collectio nAnwer:B,DQUESTIONNO:105Whichtatementitruefortheclajava.util.ArrayLitA.Theelementint hecollectionareordered.B.Thecollectioniguaranteedtobeimmutable.C.Theelementinthecollectionareguaranteedtobeunique.D.Theelementinthecollectionareacceeduingauniquekey.E.Theelem entinthecollectionareguaranteedtobeynchronized.Anwer:AQUESTIONNO:106E某hibit:1.publiccla某implementRunnable(2.privateint某;3.privateinty;4.5.publictaticvoidmain(Stringarg)6.某that=new某();7.(newThread(that)).tart();8.(newThread(that)).tart();9.)10.11.publicvoidrun()(12.for(;;)(13.某++;14.y++;15.Sytem.out.printIn(“某=”+某+“,y=”+y);16.)17.)18.)WhatithereultB.Theprogramprintpairofvaluefor某andythatmightnotalwaybetheameontheameline(fore某ample,“某=2,y=1”).C.Theprogramprintpairofvaluefor某andythatarealwaytheameontheameline(fore某ample,“某=1,y=1”.Inaddition,eachvalueappeartwice(fore 某ample,“某=1,y=1”followedby“某=1,y=1”).D.Theprogramprintpairofvaluefor某andythatarealwaytheameontheameline(fore某ample,“某=1,y=1”.Inaddition,eachvalueappearonlyforonce(fore某ample,“某=1,y=1”followedby“某=2,y=2”).Anwer:DQUESTIONNO:107Given:1.publicclaSyncTet{2.privateint某;3.privateinty;4.publicynchronizedvoidet某(inti)(某=1;)5.publicynchronizedvoidetY(inti)(y=1;)6.publicynchronizedvoidet某Y(int1)(et某(i);etY(i);)7.publicynchronizedBooleancheck()(return某!=y;)8.)Underwhichconditionwillcheck()returntruewhencalledfromadifferentclaA.Check()canneverreturntrue.B.Check()canreturntruewhenet某Yicalledbymultiplethread.C.Check()canreturntruewhenmultiplethrea dcallet某andetYeparately.D.Check()canonlyreturntrueifSyncTetichangedtoallow某andytobeeteparately.Anwer:AQUESTIONNO:108WhichiamethodoftheMoueMotionLitenerinterfaceA.Publicvoidmoue Dragged(MoueEvent)B.PublicbooleanmoueDragged(MoueEvent)C.Publicv oidmoueDragged(MoueMotionEvent)D.PublicbooleanMoueDragged(MoueMo tionEvent)E.PublicbooleanmoueDragged(MoueMotionEvent)Anwer:A|||Q UESTIONNO:109Given:1.Stringfoo=“bae”;2.foo.ubtring(0,3);3.foo.concat(“ket”) ;4.foo+=“ball”;5.Typethevalueoffooatline8.Anwer:BASEBALLQUESTIONNO110Given:1.publicclaTet{2.publictaticvoidlefthift(inti,intj){3.i<<=j;4.}5.publictaticvoidmain(Stringarg){6.inti=4,j=2;7.lefthift(i,j );8.Sytem.out.printIn(i);9.}10.}WhatithereultA.2B.4C.8D.16QUESTIONNO111Given:1.publicclaFoo{2.privateintval;3.publicfoo(intv)(val=v;)}4.publictaticvoidmain(Stringarg){5.Fooa=newFoo(10);6.Foob=ne wFoo(10);7.Fooc=a;8.intd=10;9.doublee=10.0;10.}11.}Whichthreelogicale某preionevaluatetotrue(ChooeThree)A.(a==c)B.(d==e)C.(b==d)D.(a==b)E.(b==c)F.(d==10.0)Anwer:A,B,FQUESTIONNO112E某hibit:1.publiccla某{2.privatetaticinta;3.5.publictaticvoidmain(Stringarg){6.modify(a);7.}8.9.publictaticvoidmodify(inta){10.a++;11.}12.}WhatithereultA.Theprogramrunandprint“0”B.Theprogramrunandprint“1”C.Theprogramrunbutabortwithane某ception.QUESTIONNO113E某hibit:1.publicclaTet{2.publictaticvoidreplaceJ(tringte某t){3.te某t.replace(‘j‘,‘l‘);4.}5.6.publictaticvoidmain(Stringarg){7.tringte某t=newString(“java”)8.replaceJ(te某t);9.ytem.out.printIn(te某t);10.}11.}WhatithereultA.Theprogramprint“lava”B.Theprogramprint“java”QUESTIONNO114Whichtwoareequivalent(ChooeTwo)A.3/2B.3<2C.3某4D.3<<2E.3某2^2F.3<<<2Anwer:C,DQUESTIONNO115WhatithenumericalrangeofacharA.0...32767B.0...65535C.–256...255D.–32768 (32767)E.Rangeiplatformdependent.Anwer:B|||QUESTIONNO116Given:1.publicclaTet{2.publictaticvoidmain(Stringarg){3.unignedbyteb=0;4.b--;5.6.}7.}Whatithevalueofbatline5A.-1B.255C.127QUESTIONNO117Given:1.publicclaFoo{2.publicvoidmain(Stringarg){3.ytem.out.printIn(“HelloWorld.”);4.}5.}WhatithereultC.“HelloWorld.”Iprintedtotheterminal.D.Theprograme某itwithoutprintinganything.Anwer:AQUESTIONNO118Given:1.//point某2.publicclafoo(。
SCJP 6.0认证教战手册考题201-244.pdf

SCJP 6.0 認證教戰手冊黃彬華著碁峰出版書名:SCJP 6.0 認證教戰手冊作者:黃彬華完全擬真試題 201-244(共 244 題)第201題Given:1.import java.util.*;2.class A{}3.class B extends A{}4.public class Test{5.public static void main(Strang[] args){6.List<A> listA = new LinkedList<A>();7.List<B> listB = new LinkedList<B>();8.List<Obect> listO = new LinkedList<Obect>();9.//insert code here10.}11.public static void m1(List<? extends A> list){}12.public static void m2(List<A> list){}Place a result onto each method call to indicate what would happen if the method call were inserted at line 9. Note: Results can be used more than once.Method Calls Resultm1(listA); m2(listA); Does not compile.m1(listB); m2(listB); Compiles and runs without error.m1(listO); m2(listO); An exception is thrown atruntime.答案:m1(listA);Compiles and runs without error.m1(listB);Compiles and runs without error.m1(listO);Does not compile.m2(listA);Compiles and runs without error.m2(listB);Does not compile.m2(listO);Does not compile.參考:12-3 泛型第202題Given:NumberNames nn = new NumberNames();nn.put("one", 1);System.out.println(nn.getNames());Place the code into position to create a class that maps from Strings to integer values. The result of execution must be [one]. Some options may be used more than once.public class NumberNames{private HashMap< Place here , Place here > map =SCJP 6.0 認證教戰手冊黃彬華著碁峰出版public void put(String name, int value){map.put( Place here , Place here );}public Place here getNames(){return map.keySet();}}CodeSet<int> Set<Integer> HashSetSet<Integer, String> Set<int, String> Set<String, Integer>Set<String, int> Set<String> NumberNamesString Integer int >>() namevalue map答案:public class NumberNames{private HashMap< String , Integer > map =new HashMap< String , Integer>() ;public void put(String name, intvalue){ map.put( name , value );}public Set<String>getNames(){ returnmap.keySet();}}參考:12-5-1 HashMap第203題 Given:5.import java.util.*;6.public class SortOf{7.public static void main(String[] args){8.ArrayList<Integer> a = new ArrayList<Integer>();9. a.add(1); a.add(5); a.add(3);10.Collections.sort(a);11. a.add(2);12.Collections.reverse(a);13.System.out.println(a);14.}15.}What is the result?A.[1, 2, 3, 5]2D.[5, 3, 2, 1]E.[1, 3, 5, 2]pilation fails.G.An exception is thrown at runtime.答案:C參考:12-2-2 Collections 類別、12-4-5 List 集合第204題Given:11.public class Person{12.private name;13.public Person(String name){ = name;15.}16.public int hashCode(){17.return 420;18.}19.}Which statement is true?A.The time to find the value from HashMap with a Person key depends on the size of the map.B.Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.C.Inserting a second Person object into a HashSet will cause the first Person object to be removed asa duplicate.D.The time to determine whether a Person object is contained in a HashSet is constant and does NOTdepend on the size of the map.答案:A參考:12-4-2 equals()、hashCode()方法的改寫第205題Given:12.import java.util.*;13.public class Explorer2{14.public static void main(String[] args){15.TreeSet<Integer> s = new TreeSet<Integer>();16.TreeSet<Integer> subs = new TreeSet<Integer>();17.for(int i=606; i<613; i++)18.if(i%2 == 0) s.add(i);19.subs = (TreeSet)s.subSet(608, true, 611, true);20.s.add(629);21.System.out.println(s + " " + subs);22.}23.}What is the result?pilation fails.B.An exception is thrown at runtime.C.[608, 610, 612, 629] [608, 610]D.[608, 610, 612, 629] [608, 610, 629]E.[606, 608, 610, 612, 629] [608, 610]F.[606, 608, 610, 612, 629] [608, 610, 629]答案:E參考:12-4-4 子集檢視第206題Given:1.public class Drink implements Comparable{2.public String name;3.public int compareTo(Object o){4.return 0;5.}6.}and:20.Drink one = new Drink();21.Drink two = new Drink(); = "Coffee"; = "Tea";24.TreeSet set = new TreeSet();25.set.add(one);26.set.add(two);A programmer iterates over the TreeSet and prints the name of each Drink object.What is the result?A.TeaB.CoffeeC.Coffee Teapilation fails.E.The code runs with no output.F.An exception is thrown at runtime.答案:B參考:12-4-3 SortedSet 集合第207題A programmer must create a generic class MinMax and the type parameter of MinMax must implement Comparable. Which implementation of MinMax will compile?A.class MinMax<E extendsComparable<E>>{ E min = null;E max = null;public MinMax(){}public void put(E value){/* store min or max */}B.class MinMax<E implementsComparable<E>>{ E min = null;E max = null;public MinMax(){}public void put(E value){/* store min or max */}C.class MinMax<E extendsComparable<E>>{ <E> E min = null;<E> E max = null;public MinMax(){}public <E> void put(E value){/* store min or max */}D.class MinMax<E implementsComparable<E>>{ <E> E min = null;<E> E max = null;public MinMax(){}public <E> void put(E value){/* store min or max */}答案:A參考:12-3 泛型第208題Given:1.import java.util.*;2.public class Example{3.public static void main(String[] args){4.//insert code here5.set.add(new Integer(2));6.set.add(new Integer(1)),7.System.out.println(set);8.}9.}Which code, inserted at line 4, guarantees that this program will output [1, 2]?A.Set set = new TreeSet();B.Set set = new HashSet();C.Set set = new SortedSet();D.List set = new SortedList();E.Set set = new LinkedHashSet();答案:A參考:12-4-3 SortedSet 集合第209題Given:1.import java.util.*;2.public class TestSet{3.enum Example{ONE, TWO, THREE}4.public static void main(String[] args){5.Collection coll = new ArrayList();6.coll.add(Example.THREE);7.coll.add(Example.THREE);8.coll.add(Example.THREE);9.coll.add(Example.TWO);10.coll.add(Example.TWO);11.coll.add(Example.ONE)12.Set set = new HashSet(coll);13.}14.}Which statement is true about the set variable on line 12?A.The set variable contains all six elements from the coll collection, and the order is guaranteed tobe preserved.B.The set variable contains only three elements from the coll collection, and the order is guaranteed tobe preserved.C.The set variable contains all six elements from the coll collection, but the order is NOT guaranteed tobe preserved.D.The set variable contains only three elements from the coll collection, but the order is NOTguaranteed to be preserved.答案:D參考:12-4-1 Set 集合、12-4-5 List 集合第210題Given:11.public class Person{12.private String name, comment;13.private int age;14.public Person(String n, int a, String c){ = n; age = a; comment = c;16.}17.public boolean equals(Object o){18.if (!(0 instanceof Person)) return false;19.Person p = (Person)o;20.return age == p.age && name.equals();21.}22.}What is the appropriate definition of the hashCode method in class Person?A.return super.hashCode();B.return name.hashcode() + age * 7;C.return name.hashCode() + comment.hashCode() / 2;D.return name.hashCode() + comment.hashCode() / 2- age * 3;答案:D參考:12-4-2 equals()、hashCode()方法的改寫第211題Given:11.public class Key{12.private long id1,13.private long id2;14.15.//class Key methods16.}A programmer is developing a class Key, that will be used as a key in a standard java.util.HashMap. Which two methods should be overridden to assure that Key works correctly as a key? (Choose two.)A.public int hashCode()B.public void hashCode()C.public int compareTo(Object o)D.public boolean equals(Object o)E.public boolean compareTo(Key k)答案:AD參考:12-4-2 equals()、hashCode()方法的改寫第212題Given:3.import java.util.*;4.public class Hancock{5.//insert code here6.list.add("foo");7.}8.}Which two code fragments, inserted independently at line 5, will compile without warnings? (Choose two.)A.public void addStrings(List list){B.public void addStrings(List<String> list){C.public void addStrings(List<? super String> list){D.public void addStrings(List<? extends String> list){答案:BC參考:12-4-2 equals()、hashCode()方法的改寫第213題Given a class whose instances, when found in a collection of objects, are sorted by using the compareTo() method, which two statements are true? (choose two.)A.The class implements parable.B.The class implements parator.C.The interface used to implement sorting allows this class to define only one sort sequence.D.The interface used to implement sorting allows this class to define many different sort sequences. 答案:AC參考:12-4-3 SortedSet 集合第214題Given:12.import java.util.*;13.public class Explorer3{14.public static void main(String[] args){15.TreeSet<Integer> s = new TreeSet<Integer>();16.TreeSet<Integer> subs = new TreeSet<Integer>();17.for(int i=606; i<613; i++)18.if(i%2 == 0) s.add(i);19.subs = (TreeSet)s.subSet(608, true, 611, true);20.subs.add(629);21.System.out.println(s + " " + subs);22.}23.}What is the result?pilation fails.B.An exception is thrown at runtime.C.[608, 610, 612, 629] [608, 610]D.[608, 610, 612, 629] [608, 610, 629]E.[606, 608, 610, 612, 629] [608, 610]F.[606, 608, 610, 612, 629] [608, 610, 629]答案:B參考:12-4-4 子集檢視第215題Given:1.import java.util.*;2.3.public class LetterASort{4.public static void main(String[] args){5.ArrayList<String> strings = new ArrayList<String>();6.strings.add("aAaA");7.strings.add("AaA");8.strings.add("aAa");9.strings.add("AAaa");10.Collections.sort(strings);11.for(String s : strings){System.out.print(s + " ");}12.}13.}What is the result?pilation fails.B.aAaA aAa AAaa AaAC.AAaa AaA aAa aAaAD.AaA AAaa aAaA aAaE.aAa AaA aAaA AAaaF.An exception is thrown at runtime.答案:C參考:12-2-2 Collections 類別、12-4-5 List 集合第216題Given:1.import java.util.*,2.public class TestGenericConversion{3.public static void main(String[] args){4.List list = new LinkedList();5.list.add("one");6.list.add("two");7.System.out.print(((String)list.get(O)).length());8.}9.}Refactor this class to use generics without changing the code's behavior.1. import java.util.*,2. public class TestGenericConversion{3. public static void main(String[] args){4. Place here5. list.add("one");6. list.add("two");7. Place here8. }9. }CodeList list = new LinkedList();System.out.print(list.get(0).length());List<String> list = new LinkedList<String>();System.out.print(list.get<String>(0).length()); List<String> list = new LinkedList(); System.out.print(<String>list.get(0).length());List list = new LinkedList<String>(); System.out.print((List<String>)list.get(0).length());1.import java.util.*,2.public class TestGenericConversion{3.public static void main(String[] args){4.List<String> list = new LinkedList<String>();5.list.add("one");6.list.add("two");7.System.out.print(list.get(0).length());8.}9.}參考:12-3 泛型SCJP 6.0 認證教戰手冊黃彬華著碁峰出版第217題Place the code into the GenericB class definition to make the class compile successfully.答案:參考:12-3 泛型10SCJP 6.0 認證教戰手冊黃彬華著碁峰出版第218題Place the code elements in position so that the Flags2 class will compile and make appropriate use of the wait/notify mechanism. Note You may reuse code elements.class Flags2{private boolean isReady = false;public Place here void produce(){isReady = true;Place here ;}public Place here voidconsume(){ while(!isReady){try{Placehere ; }catch(Exceptionex){}}isReady = Place here ;}}Code Elementssynchronizedtruefalsewait()volatilesynchronized()notifyAll()synchronize答案:class Flags2{private boolean isReady = false;public synchronized void produce(){isReady = true;notifyAll() ;}public synchronized voidconsume(){ while(!isReady){try{wait() ; }catch(Exception ex){}}isReady = false ;}}參考:13-5 執行緒的互動處理第219題 Given:1.public class Threads2 implements Runnable{114.System.out.println("run.");5.throw new RuntimeException("Problem");6.}7.public static void main(String[] args){8.Thread t = new Thread(new Threads2());9.t.start();10.System.out.println("End of method.");11.}12.}Which two can be results? (Choose two.)ng.RuntimeException: ProblemB.run.ng.RuntimeException: ProblemC.End of method.ng.RuntimeException: ProblemD.End of method.run.ng.RuntimeException: ProblemE.run.ng.RuntimeException: ProblemEnd of method.答案:DE參考:13-2 Java 執行緒與 Thread 類別第220題Which factor or factorsA.It is possible for more than two threads to deadlock at once.B.The JVM implementation guarantees that multiple threads cannot enter into a deadlocked state.C.Deadlocked threads release once their sleep() method's sleep duration has expired.D.Deadlocking can occur only when the wait(), notify() and notifyAll() methods are used incorrectly.E.It is possible for a single-threaded application to deadlock if synchronized blocks are used incorrectly.F.If a piece of code is capable of deadlocking, you cannot eliminate the possibility of deadlocking byinserting invocations of Thread.yield().答案:AF參考:13-5 執行緒的互動處理第221題Given:7.void waitForSignal(){8.Object obj = new Object();9.synchronized(Thread.currentThread()){10.obj.wait();11.obj.notify();12.}13.}Which statement is true?A.This code can throw an InterruptedException.B.This code can throw an IllegalMonitorStateException.C.This code can throw a TimeoutException after ten minutes.D.Reversing the order of obj.wait() and obj.notify() might cause this method to complete normally.E. A call to notify() or notifyAll() from another thread might cause this method to complete normally.F.This code does NOT compile unless "obj.wait()" is replaced with "((Thread) obj).wait()".答案:B參考:13-5 執行緒的互動處理第222題Given:10.public class Starter extends Thread{11.private int x = 2;12.public static void main(String[] args) throws Exception{13.new Starter().makeItSo();14.}15.public Starter(){16.x = 5;17.start();18.}19.public void makeItSo() throws Exception{20.join();21.x = x - 1;22.System.out.println(x);23.}24.public void run(){x *= 2;}25.}What is the output if the main() method is run?A. 4B. 5C.8D.9pilation fails.F.An exception is thrown at runhime.G.It is impossible to determine for certain.答案:D參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第223題Given:11.class PingPong2{12.synchronized void hit(long n){13.for(int i=1; i<3; i++)14.System.out.print(n + "-" + i + " ");15.}16.}17.public dass Tester implements Runnable{18.static PingPong2 pp2 = new PingPong2();19.public static void main(String[] args){20.new Thread(new Tester()).start();21.new Thread(new Tester()).start();22.}23.public void run(){pp2.hit(Thread.currentThread.getId());}24.}Which statement is true?A.The output could be 5-1 6-1 6-2 5-2B.The output could be 6-1 6-2 5-1 5-2C.The output could be 6-1 5-2 6-2 5-1D.The output could be 6-1 6-2 5-1 7-1答案:B參考:13-4 執行緒的同步性與安全性第224題Given:1.public class Threads4{2.public static void main(String[] args){3.new Threads4.go();4.}5.public void go(){6.Runnable r = new Runnable(){7.public void run(){8.System.out.print("foo");9.}10.};11.Thread t = new Thread(r);12.t.start();13.t.start();14.}15.}What is the result?pilation fails.B.An exception is thrown at runtime.C.The code executes normally and prints "foo";D.The code executes normally, but nothing is printed.答案:B參考:13-4 執行緒的同步性與安全性第225題Given:10.Runnable r = new Runnable(){11.public void run(){12.try{13.Thread.sleep(1000);14.}catch(InterruptedException e){15.System.out.println("interrupted");16.}17.System.out.println("ran");18.}19.};20.Thread t = new Thread(r);21.t.start();22.System.out.println("started");23.t.sleep(2000):24.System.out.println("interrupting");25.t.interrupt();26.System.out.println("ended");Assume that sleep(n) executes in exactly n milliseconds. and all other code executes in an insignificant amount of time.Place the fragments in the output area to show the result of running this code.答案:第226題Which two statements are true? (Choose two.)A. It is possible to synchronize static methods.15SCJP 6.0 認證教戰手冊黃彬華著碁峰出版B.When a thread has yielded as a result of yield(), it releases its locks.C.When a thread is sleeping as a result of sleep(), it releases its locks.D.The Object.wait() method can be invoked only from a synchronized context.E.The Thread.sleep() method can be invoked only from a synchronized context.F.When the thread scheduler receives a notify() request, and notifies a thread, that thread immediatelyreleases its lock.答案:AD參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面、13-5 執行緒的互動處理第227題Given:1.public class TestOne implements Runnable{2.public static void main (String[] args)throws Exception{3.Thread t = new Thread(new TestOne());4.t.start();5.System.out.pririt("Started");6.t.join();7.System.out.print("Complete");8.}9.public void run(){10.for(int i=0; i<4; i++){11.System.out.print(i);12.}13.}14.}What can be a result?pilation fails.B.An exception is thrown at runtime.C.The code executes and prints "StartedComplete".D.The code executes and prints "StartedComplete0123".E.The code executes and prints "Started0123Complete".答案:E參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第228題Which three will compile and run without exception? (Choose three.)A.private synchronized Object o;B.void go(){synchronized(){/* code here */}C.public synchronized void go(){/* code here */}D.private synchronized(this) void go(){/* code here */}E.void go(){synchronized(Object.class){/* code here */}F.void go(){Object o = new Object();synchronized(o){/* code here */}答案:CEF參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面、13-5 執行緒的互動處理第229題Given:1.public class TestFive{2.private int x;3.public void foo(){4.int current = x;5.x = current + 1;6.}7.public void go(){8.for(int i=0; i<5; i++){9.new Thread(){10.public void run(){11. foo();12. System.out.print(x + ", ");13.}}.start();14.}}Which two changes, taken together, would guarantee the output: 1, 2, 3, 4, 5, ? (Choose two.)A.move the line 12 print statement into the foo() methodB.change line 7 to public synchronized void go(){C.change the variable declaration on line 2 to private volatile int x;D.wrap the code inside the foo() method with a synchronized(this) blockE.wrap the for loop code inside the go() method with a synchronized block synchronized(this){//for loopcode here}答案:AD參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第230題Given that t1 is a reference to a live thread, which is true?A.The Thread.sleep() method can take t1 as an argument.B.The Object.notify() method can take t1 as an argument.C.The Thread.yield() method can take t1 as an argument.D.The Thread.setPriority() method can take t1 as an argument.E.The Object.notify() method arbitrarily chooses which thread to notify.答案:E參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面、13-5 執行緒的互動處理第231題Given:11.Runnable r = new Runnable(){12.public void run(){13.System.out.print("Cat");14.}15.};16.Thread t = new Thread(r){17.public void run(){18.System.outprint("Dog");19.}20.};21.t.start();What is the result?A.CatB.Dogpilation fails.D.The code runs with no output.E.An exception is thrown at runtime.答案:B參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第232題Given:1.public class Threads5{2.public static void main(String[] args){3.new Thread(new Runnable(){4.public void run(){5.System.out.print("bar");6.}}).start();7.}8.}What is the result?pilation fails.B.An exception is thrown at runtime.C.The code executes normally and prints "bar".D.The code executes normally, but nothing prints.答案:C參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第233題Given:1.public class Threads1{2.int x = 0;3.public class Runner implements Runnable{4.public void run(){S.int current = 0;6.for(int i=0; i<4; i++){7.current = x;8.System.out.print(current + ", ");9.x = current + 2;10.}11.}12.}13.14.public static void main(String[] args){15.new Threads1().go();16.}17.18.public void go(){19.Runnable rl = new Runner();20.new Thread(r1).start();21.new Thread(r1).start();22.}23.}Which two are possible results? (Choose two.)A.0, 2, 4, 4, 6, 8, 10, 6,B.0, 2, 4, 6, 8, 10, 2, 4,C.0, 2, 4, 6, 8, 10, 12, 14,D.0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,E.0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,答案:AC參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第234題Given:foo and bar are public references available to many other threads, foo refers to a Thread and bar is an Object. The thread foo is currently executing bar.wait().From another thread, what provides the most reliable way to ensure that foo will stop executing wait()?A.foo.notify();B.bar.notify();C.foo.notifyAll();D.Thread.notify();E.bar.notifyAll();F.Object.notify();答案:E參考:13-5 執行緒的互動處理第235題Given:11.public class PingPong implements Runnable{12.synchronized void hit(long n){13.for(int i=1; i<3; i++)14.System.out.print(n + "-" + i + " ");15.}16.public static void main(String[] args){17.new Thread(new PingPong()).start();18.new Thread(new PingPong()).start();19.}20.public void run(){21.hit(Thread.currentThread().getId);22.}23.}Which two statements are true? (Choose two.)A.The output could be 8-1 7-2 8-2 7-1B.The output could be 7-1 7-2 8-1 6-1C.The output could be 8-1 7-1 7-2 8-2D.The output could be 8-1 8-2 7-1 7-2答案:CD參考:13-4 執行緒的同步性與安全性第236題Given:1.class Computation extends Thread{2.3.private int num;4.private boolean isComplete;5.private int result;6.7.public Computation(int num){this.num = num;}8.9.public synchronized void run(){10.result = num * 2;11.isComplete = true;12.notify();13.}14.15.public synchronized int getResult(){16.while(!isComplete){17.try{18.wait();19.}catch(InterruptedException e){}20.}21.return result;22.}23.24.public static void main(String[] args){putation[] computations = new Computation[4];26.for(int i=0; i<computations.length; i++){putations[i] = new Computation(i);putations[i].start();29.}30.for(Computation c : computations)31.System.out.print(c.getResult() + " ");32.}33.}What is the result?A.The code will deadlock.B.The code may run with no output.C.An exception is thrown at runtime.D.The code may run with output "0 6".E.The code may run with output "2 0 6 4".F.The code may run with output "0 2 4 6".答案:F參考:13-4 執行緒的同步性與安全性第237題Place the code elements into the class so that the code compiles and prints "Run. Run. doIt. " in exactly that order. Note that there may be more than one correct solution.class TesTwo extends Thread{public static void main(String[] a) throwsException{ TesTwo t = new TesTwo();t.start();Place herePlace herePlace here}public voidrun(){ System.out.print("Run. ");}public voiddoIt(){ System.out.print("doIt. ");}}Code Elementst.start();t.join();t.pause(10);run();t.run();t.doIt(); doIt();答案:class TesTwo extends Thread{public static void main(String[] a) throws21SCJP 6.0 認證教戰手冊黃彬華著碁峰出版t.run();t.join();t.doIt();}public voidrun(){ System.out.print("Run. ");}public voiddoIt(){ System.out.print("doIt. ");}}參考:13-2 Java 執行緒與 Thread 類別第238題Which two code fragments will execute the method doStuff() in a separate thread? (Choose two.)A.new Thread(){public voidrun(){doStuff();} };B.new Thread(){public voidstart(){doStuff();} };C new Thread(){public voidstart(){doStuff();} }.run();D.new Thread(){public voidrun(){doStuff();} }.start();E.new Thread(newRunnable(){ public voidrun(){doStuff();} }).run();F.new Thread(newRunnable(){ public voidrun(){doStuff();}}).start();答案:DF參考:8-5-4 匿名內部類別、13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面第239題 Given:22SCJP 6.0 認證教戰手冊黃彬華著碁峰出版4.System.out.println("sleep");5.}6.}What is the result?pilation fails.B.An exception is thrown at runtime.C.The code executes normally and prints "sleep".D.The code executes normally, but nothing is printed.答案:C參考:13-2 Java 執行緒與 Thread 類別第240題Place a Class on each method that is declared in the class.參考:13-2 Java 執行緒與 Thread 類別、13-3 Runnable 介面、13-5 執行緒的互動處理第241題Given:1.public class Threads3 implements Runnable{2.public void run(){3.System.out.print("running");4.}5.public static void main(String[] args){6.Thread t = new Thread(new Threads3());7.t.run();11.}23What is the result?pilation fails.B.An exception is thrown at runtime.C.The code executes and prints "running".D.The code executes and prints "runningrunning".E.The code executes and prints "runningrunningrunning".答案:E參考:13-3 Runnable 介面第242題Given:public classNamedCounter{ privatefinal String name; privateint count;public NamedCounter(String name){ = name;}public String getName(){return name;}public void increment(){count++;}public int getCount(){return count;}public void reset(){count = 0;}Which three changes should be made to adapt this class to be used safely by multiple threads? (Choose three.)A.declare reset() using the synchronized keywordB.declare getName() using the synchronized keywordC.declare getCount() using the synchronized keywordD.declare the constructor using the synchronized keywordE.declare increment() using the synchronized keyword答案:ACE參考:13-3 Runnable 介面第243題Given that Triangle implements Runnable, and:31.void go() throws Exception{32.Thread t = new Thread(new Triangle());33.t.start();34.for(int x=1; x<100000; x++){35.//insert code here36.if(x%100 == 0) System.out.print("g");37.}}38.public void run(){39.try{40.for(int x=1; x<100000; x++){41.//insert the same code here42.if(x%100 == 0) System.out.print("t");43.}24。
JAVA认证历年真题:SCJP认证套题解析[2]
![JAVA认证历年真题:SCJP认证套题解析[2]](https://img.taocdn.com/s3/m/012b841d3968011ca300914f.png)
JAVA认证历年真题:SCJP认证套题解析[2]JAVA认证历年真题:SCJP认证套题解析[2]JAVA认证历年真题:SCJP认证套题解析[2]21、which of the following assignment is not correct?a. float f = 11.1;b. double d = 5.3e12;c. double d = 3.14159;d. double d = 3.14d.(a)题目:下面的哪些赋值语句是不对的。
浮点数的赋值是带有小数点的数字缺省是double型的,如果在浮点数后面加f或者f则是float,后面加d或者d则是double,科学计数法形式的浮点数也是double型的,而double的精度比float 高,将一个高精度的double赋值给一个低精度的float时需要进行强制类型转换,反之则不需要。
22、given the uncompleted code of a class:class person {string name, department;int age;public person(string n){ name = n; }public person(string n, int a){ name = n; age = a; }public person(string n, string d, int a) {// doing the same as two arguments version of constructor// including assignment name=n,age=adepartment = d;}}which expression can be added at the "doing the same as..." part of the constructor?a. person(n,a);b. this(person(n,a));c. this(n,a);d. this(name,age).(c)题目:给出下面的不完整的类代码:下面的哪些表达式可以加到构造方法中的"doing the same as..."处?在同一个类的不同构造方法中调用该类的其它构造方法需要使用this( )的形式,而且必须是在构造方法的第一行调用,这个和普通的方法重载调用的方式不同,普通的方法可以直接使用方法名加参数来调用,而且调用位置没有限制,因此答案a是不行的,b的语法就是错误的,d的错误在于在父类型的构造函数被调用前不能引用类的成员。
SUN认证Java2程序员考试(SCJP) 试题解析(2)

SUN认证Java2程序员考试(SCJP) 试题解析(2)SUN认证Java2程序员考试(SCJP) 试题解析(2) which of the following lines of code will pile without error?a.int i=0;if (i) {system.out.println(“hi”);}b.boolean b=true;boolean b2=true;if(b==b2) {system.out.println(“so true”); }c.int i=1;int j=2;if(i==1|| j==2)system.out.println(“ok”);d.int i=1;int j=2;if (i==1 &| j==2)system.out.println(“ok”);解答:b, c点评:选项a错,因为if语句后需要一个boolean类型的表达式。
逻辑操作有^、&、| 和 &&、||,但是“&|”是非法的,所以选项d不正确。
例题5:which two demonstrate a "has a" relationship? (choose two) a. public interface person { }public class employee extends person{ }b. public interface shape { }public interface rectandle extends shape { }c. public interface colorable { }public class shape implements colorable{ }d. public class species{ }public class animal{private species species;}e. interface ponent{ }class container implements ponent{private ponent[] children;}解答:d, e点评:在java中代码重用有两种可能的方式,即组合(“has a”关系)和继承(“is a”关系)。
JAVA认证历年真题:SCJP认证套题解析(3)

JAVA认证历年真题:SCJP认证套题解析(3)41、Which of the following statements are legal?A. long l = 4990;B. int i = 4L;C. float f = 1.1;D. double d = 34.4;E. double t = 0.9F.(ade)题目:下面的哪些声明是合法的。
此题的考点是数字的表示法和基本数据类型的类型自动转换,没有小数点的数字被认为是int型数,带有小数点的数被认为是double型的数,其它的使用在数字后面加一个字母表示数据类型,加l或者L是long型,加d或者D是double,加f或者F是float,可以将低精度的数字赋值给高精度的变量,反之则需要进行强制类型转换,例如将int,short,byte赋值给long 型时不需要显式的类型转换,反之,将long型数赋值给byte,short,int型时需要强制转换(int a=(int)123L;)。
42、public class Parent {int change() {…}}class Child extends Parent {}Which methods can be added into class Child?A. public int change(){}B. int chang(int i){}C. private int change(){}D. abstract int chang(){}(ab)题目:哪些方法可被加入类Child。
这个题目的问题在第35题中有详尽的叙述。
需要注意的是答案D的内容,子类可以重写父类的方法并将之声明为抽象方法,但是这引发的问题是类必须声明为抽象类,否则编译不能通过,而且抽象方法不能有方法体,也就是方法声明后面不能带上那两个大括号({}),这些D都不能满足。
43、class Parent {String one, two;public Parent(String a, String b){one = a;two = b;}public void print(){ System.out.println(one); }}public class Child extends Parent {public Child(String a, String b){super(a,b);}public void print(){System.out.println(one + " to " + two);}public static void main(String arg[]){Parent p = new Parent("south", "north");Parent t = new Child("east", "west");p.print();t.print();}}Which of the following is correct?A. Cause error during compilation.B. southeastC. south to northeast to westD. south to northeastE. southeast to west(e)题目:下面的哪些正确。
SCJP认证试题及答案

转载对题目和答案谨做参考Q1A method is ...1) an implementation of an abstraction.2) an attribute defining the property of a particular abstraction.3) a category of objects.4) an operation defining the behavior for a particular abstraction.5) a blueprint for making operations.Q2An object is ...1) what classes are instantiated from.2) an instance of a class.3) a blueprint for creating concrete realization of abstractions.4) a reference to an attribute.5) a variable.Q3Which line contains a constructor in this class definition?public class Counter { // (1)int current, step;public Counter(int startValue, int stepValue) { // (2)set(startValue);setStepValue(stepValue);}public int get() { return current; } // (3)public void set(int value) { current = value; } // (4)public void setStepValue(int stepValue) { step = stepValue; } // (5) }1) Code marked with (1) is a constructor2) Code marked with (2) is a constructor3) Code marked with (3) is a constructor4) Code marked with (4) is a constructor5) Code marked with (5) is a ConstructorQ4Given that Thing is a class, how many objects and reference variables are created by the following code?Thing item, stuff;item = new Thing();Thing entity = new Thing();1) One object is created2) Two objects are created3) Three objects are created4) One reference variable is created5) Two reference variables are created6) Three reference variables are created.Q5An instance member…1) is also called a static member2) is always a variable3) is never a method4) belongs to a single instance, not to the class as a whole5) always represents an operationQ6How do objects pass messages in Java?1) They pass messages by modifying each other's member variables2) They pass messages by modifying the static member variables of each other's classes3) They pass messages by calling each other's instance member methods4) They pass messages by calling static member methods of each other's classes.Q7Given the following code, which statements are true?class A {int value1;}class B extends A {int value2;}1) Class A extends class B.2) Class B is the superclass of class A.3) Class A inherits from class B.4) Class B is a subclass of class A.5) Objects of class A have a member variable named value2.Q8If this source code is contained in a file called SmallProg.java, what command should be used to compile it using the JDK?public class SmallProg {public static void main(String args[]) { System.out.println("Good luck!"); }}1) java SmallProg2) avac SmallProg3) java SmallProg.java4) javac SmallProg.java5) java SmallProg mainQ9Given the following class, which statements can be inserted at position 1 without causing the code to fail compilation?public class Q6db8 {int a;int b = 0;static int c;public void m() {int d;int e = 0;// Position 1}}1) a++;2) b++;3) c++;4) d++;5) e++;Q10Which statements are true concerning the effect of the >> and >>> operators?1) For non-negative values of the left operand, the >> and >>> operators will have the same effect.2) The result of (-1 >> 1) is 0.3) The result of (-1 >>> 1) is -1.4) The value returned by >>> will never be negative as long as the value of the right operand is equal to or greater than 1.5) When using the >> operator, the leftmost bit of the bit representation of the resulting value will always be the same bit value as the leftmost bit of the bit representation of the left operand.Q11What is wrong with the following code?class MyException extends Exception {}public class Qb4ab {public void foo() {try {bar();} finally {baz();} catch (MyException e) {}}public void bar() throws MyException {throw new MyException();}public void baz() throws RuntimeException {throw new RuntimeException();}}1) Since the method foo() does not catch the exception generated by the method baz(), it must declare the RuntimeException in its throws clause.2) A try block cannot be followed by both a catch and a finally block.3) An empty catch block is not allowed.4) A catch block cannot follow a finally block.5) A finally block must always follow one or more catch blocks.Q12What will be written to the standard output when the following program is run?public class Qd803 {public static void main(String args[]) {String word = "restructure";System.out.println(word.substring(2, 3));}}1) est2) es3) str4) st5) sQ13Given that a static method doIt() in a class Work represents work to be done, what block of code will succeed in starting a new thread that will do the work?CODE BLOCK A:Runnable r = new Runnable() { public void run() {Work.doIt();}};Thread t = new Thread(r);t.start();CODE BLOCK B:Thread t = new Thread() {public void start() {Work.doIt();}};t.start();CODE BLOCK C:Runnable r = new Runnable() { public void run() {Work.doIt();}};r.start();CODE BLOCK D:Thread t = new Thread(new Work()); t.start();CODE BLOCK E:Runnable t = new Runnable() { public void run() {Work.doIt();}};t.run();1) Code block A.2) Code block B.3) Code block C.4) Code block D.5) Code block E.Q14Write a line of code that declares a variable named layout of type LayoutManager and initializes it with a new object, which when used with a container can lay out components in a rectangular grid of equal-sized rectangles, 3 components wide and 2 components high.Q15public class Q275d {static int a;int b;public Q275d() {int c;c = a;a++;b += c;}public static void main(String args[]) {new Q275d();}}1) The code will fail to compile, since the constructor is trying to access static members.2) The code will fail to compile, since the constructor is trying to use static member variable a before it has been initialized.3) The code will fail to compile, since the constructor is trying to use member variable b before it has been initialized.4) The code will fail to compile, since the constructor is trying to use local variable c before it has been initialized.5) The code will compile and run without any problems.Q16What will be written to the standard output when the following program is run?public class Q63e3 {public static void main(String args[]) {System.out.println(9 ^ 2);}}1) 812) 73) 114) 05) falseQ17Which statements are true concerning the default layout manager for containers in the java.awt package?1) Objects instantiated from Panel do not have a default layout manager.2) Objects instantiated from Panel have FlowLayout as default layout manager.3) Objects instantiated from Applet have BorderLayout as default layout manager.4) Objects instantiated from Dialog have BorderLayout as default layout manager.5) Objects instantiated from Window have the same default layout manager as instances of Applet.Q18Which declarations will allow a class to be started as a standalone program?1) public void main(String args[])2) public void static main(String args[])3) public static main(String[] argv)4) final public static void main(String [] array)5) public static void main(String args[])Q19Under which circumstances will a thread stop?1) The method waitforId() in class MediaTracker is called.2) The run() method that the thread is executing ends.3) The call to the start() method of the Thread object returns.4) The suspend() method is called on the Thread object.5) The wait() method is called on the Thread object.Q20When creating a class that associates a set of keys with a set of values, which of these interfaces is most applicable?1) Collection2) Set3) SortedSet4) MapQ21What does the value returned by the method getID() found in class java.awt.AWTEvent uniquely identify?1) The particular event instance.2) The source of the event.3) The set of events that were triggered by the same action.4) The type of event.5) The type of component from which the event originated.Q22What will be written to the standard output when the following program is run?class Base {int i;Base() {add(1);}void add(int v) {i += v;}void print() {System.out.println(i);}}class Extension extends Base {Extension() {add(2);}void add(int v) {i += v*2;}}public class Qd073 {public static void main(String args[]) {bogo(new Extension());}static void bogo(Base b) {b.add(8);b.print();}}1) 92) 183) 204) 215) 22Q23Which lines of code are valid declarations of a native method when occurring within the declaration of the following class?public class Qf575 {// insert declaration of a native method here}1) native public void setTemperature(int kelvin);2) private native void setTemperature(int kelvin);3) protected int native getTemperature();4) public abstract native void setTemperature(int kelvin);5) native int setTemperature(int kelvin) {}Q24How does the weighty property of the GridBagConstraints objects used in grid bag layout affect the layout of the components?1) It affects which grid cell the components end up in.2) It affects how the extra vertical space is distributed.3) It affects the alignment of each component.4) It affects whether the components completely fill their allotted display area vertically.Q25Which statements can be inserted at the indicated position in the following code to make the program write 1 on the standard output when run?public class Q4a39 {int a = 1;int b = 1;int c = 1;class Inner {int a = 2;int get() {int c = 3;// insert statement herereturn c;}}Q4a39() {Inner i = new Inner();System.out.println(i.get());}public static void main(String args[]) {new Q4a39();}}1) c = b;2) c = this.a;3) c = this.b;4) c = Q4a39.this.a;5) c = c;Q26Which is the earliest line in the following code after which the object created on the line marked (0) will be a candidate for being garbage collected, assuming no compiler optimizations are done?public class Q76a9 {static String f() {String a = "hello";String b = "bye"; // (0)String c = b + "!"; // (1)String d = b;b = a; // (2)d = a; // (3)return c; // (4)}public static void main(String args[]) {String msg = f();System.out.println(msg); // (5)}}1) The line marked (1).2) The line marked (2).3) The line marked (3).4) The line marked (4).5) The line marked (5).Q27Which methods from the String and StringBuffer classes modify the object on which they are called?1) The charAt() method of the String class.2) The toUpperCase() method of the String class.3) The replace() method of the String class.4) The reverse() method of the StringBuffer class.5) The length() method of the StringBuffer class.Q28Which statements, when inserted at the indicated position in the following code, will cause a runtime exception when attempting to run the program?class A {}class B extends A {}class C extends A {}public class Q3ae4 {public static void main(String args[]) {A x = new A();B y = new B();C z = new C();// insert statement here}}1) x = y;2) z = x;3) y = (B) x;4) z = (C) y;5) y = (A) y;Q29Which of these are keywords in Java?1) default2) NULL3) String4) throws5) longQ30It is desirable that a certain method within a certain class can only be accessed by classes that are defined within the same package as the class of the method. How can such restrictions be enforced?1) Mark the method with the keyword public.2) Mark the method with the keyword protected.3) Mark the method with the keyword private.4) Mark the method with the keyword package.5) Do not mark the method with any accessibility modifiers.Q31Which code fragments will succeed in initializing a two-dimensional array named tab with a size that will cause the expression tab[3][2] to access a valid element?CODE FRAGMENT A:int[][] tab = {{ 0, 0, 0 },{ 0, 0, 0 }};CODE FRAGMENT B:int tab[][] = new int[4][];for (int i=0; iCODE FRAGMENT C:int tab[][] = {0, 0, 0, 0,0, 0, 0, 0,0, 0, 0, 0,0, 0, 0, 0};CODE FRAGMENT D:int tab[3][2];CODE FRAGMENT E:int[] tab[] = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0} };1) Code fragment A.2) Code fragment B.3) Code fragment C.4) Code fragment D.5) Code fragment E.Q32What will be the result of attempting to run the following program?public class Qaa75 {public static void main(String args[]) {String[][][] arr = {{ {}, null },{ { "1", "2" }, { "1", null, "3" } },{},{ { "1", null } }};System.out.println(arr.length + arr[1][2].length);}}1) The program will terminate with an ArrayIndexOutOfBoundsException.2) The program will terminate with a NullPointerException.3) 4 will be written to standard output.4) 6 will be written to standard output.5) 7 will be written to standard output.Q33Which expressions will evaluate to true if preceded by the following code? String a = "hello";String b = new String(a);String c = a;char[] d = { 'h', 'e', 'l', 'l', 'o' };1) (a == "Hello")2) (a == b)3) (a == c)4) a.equals(b)5) a.equals(d)Q34Which statements concerning the following code are true?class A {public A() {}public A(int i) { this(); }}class B extends A {public boolean B(String msg) { return false; }}class C extends B {private C() { super(); }public C(String msg) { this(); }public C(int i) {}}1) The code will fail to compile.2) The constructor in A that takes an int as an argument will never be called as a result of constructing an object of class B or C.3) Class C has three constructors.4) Objects of class B cannot be constructed.5) At most one of the constructors of each class is called as a result of constructing an object of class C.Q35Given two collection objects referenced by col1 and col2, which of these statements are true?1) The operation col1.retainAll(col2) will not modify the col1 object.2) The operation col1.removeAll(col2) will not modify the col2 object.3) The operation col1.addAll(col2) will return a new collection object,containing elements from both col1 and col2.4) The operation col1.containsAll(Col2) will not modify the col1 object.Q36Which statements concerning the relationships between the following classes are true?class Foo {int num;Baz comp = new Baz();}class Bar {boolean flag;}class Baz extends Foo {Bar thing = new Bar();double limit;}1) A Bar is a Baz.2) A Foo has a Bar.3) A Baz is a Foo.4) A Foo is a Baz.5) A Baz has a Bar.Q37Which statements concerning the value of a member variable are true, when no explicit assignments have been made?1) The value of an int is undetermined.2) The value of all numeric types is zero.3) The compiler may issue an error if the variable is used before it is initialized.4) The value of a String variable is "" (empty string).5) The value of all object variables is null.Q38Which statements describe guaranteed behavior of the garbage collection and finalization mechanisms?1) Objects are deleted when they can no longer be accessed through any reference.2) The finalize() method will eventually be called on every object.3) The finalize() method will never be called more than once on an object.4) An object will not be garbage collected as long as it is possible for an active part of the program to access it through a reference.5) The garbage collector will use a mark and sweep algorithm.Q39Which code fragments will succeed in printing the last argument given on the command line to the standard output, and exit gracefully with no output if no arguments are given?CODE FRAGMENT A:public static void main(String args[]) {if (args.length != 0)System.out.println(args[args.length-1]);}CODE FRAGMENT B:public static void main(String args[]) {try { System.out.println(args[args.length]); }catch (ArrayIndexOutOfBoundsException e) {}}CODE FRAGMENT C:public static void main(String args[]) {int ix = args.length;String last = args[ix];if (ix != 0) System.out.println(last);}CODE FRAGMENT D:public static void main(String args[]) {int ix = args.length-1;if (ix > 0) System.out.println(args[ix]);}CODE FRAGMENT E:public static void main(String args[]) {try { System.out.println(args[args.length-1]); }catch (NullPointerException e) {}}1) Code fragment A.2) Code fragment B.3) Code fragment C.4) Code fragment D.5) Code fragment E.Q40Which of these statements concerning the collection interfaces are true?1) Set extends Collection.2) All methods defined in Set are also defined in Collection.3) List extends Collection.4) All methods defined in List are also defined in Collection.5) Map extends Collection.Q41What is the name of the method that threads can use to pause their execution until signalled to continue by another thread?Fill in the name of the method (do not include a parameter list).Q42Given the following class definitions, which expression identifies whether the object referred to by obj was created by instantiating class B rather than classes A, C and D?class A {}class B extends A {}class C extends B {}class D extends A {}1) obj instanceof B2) obj instanceof A && ! (obj instanceof C)3) obj instanceof B && ! (obj instanceof C)4) obj instanceof C || obj instanceof D5) (obj instanceof A) && ! (obj instanceof C) && ! (obj instanceof D)Q43What will be written to the standard output when the following program is run?public class Q8499 {public static void main(String args[]) {double d = -2.9;int i = (int) d;i *= (int) Math.ceil(d);i *= (int) Math.abs(d);System.out.println(i);}}1) 122) 183) 84) 125) 27Q44What will be written to the standard output when the following program is run?public class Qcb90 {int a;int b;public void f() {a = 0;b = 0;int[] c = { 0 };g(b, c);System.out.println(a + " " + b + " " + c[0] + " ");}public void g(int b, int[] c) {a = 1;b = 1;c[0] = 1;}public static void main(String args[]) {Qcb90 obj = new Qcb90();obj.f();}}1) 0 0 02) 0 0 13) 0 1 04) 1 0 05) 1 0 1Q45Which statements concerning the effect of the statement gfx.drawRect(5, 5, 10, 10) are true, given that gfx is a reference to a valid Graphics object?1) The rectangle drawn will have a total width of 5 pixels.2) The rectangle drawn will have a total height of 6 pixels.3) The rectangle drawn will have a total width of 10 pixels.4) The rectangle drawn will have a total height of 11 pixels.Q46Given the following code, which code fragments, when inserted at the indicated location, will succeed in making the program display a button spanning the whole window area?import java.awt.*;public class Q1e65 {public static void main(String args[]) {Window win = new Frame();Button but = new Button("button");// insert code fragment herewin.setSize(200, 200);win.setVisible(true);}}1) win.setLayout(new BorderLayout()); win.add(but);2) win.setLayout(new GridLayout(1, 1)); win.add(but);3) win.setLayout(new BorderLayout()); win.add(but, BorderLayout.CENTER);4) win.add(but);5) win.setLayout(new FlowLayout()); win.add(but);Q47Which method implementations will write the given string to a file named "file", using UTF8 encoding?IMPLEMENTATION A:public void write(String msg) throws IOException {FileWriter fw = new FileWriter(new File("file"));fw.write(msg);fw.close();}IMPLEMENTATION B:public void write(String msg) throws IOException {OutputStreamWriter osw =new OutputStreamWriter(new FileOutputStream("file"), "UTF8");osw.write(msg);osw.close();}IMPLEMENTATION C:public void write(String msg) throws IOException { FileWriter fw = new FileWriter(new File("file"));fw.setEncoding("UTF8");fw.write(msg);fw.close();}IMPLEMENTATION D:public void write(String msg) throws IOException { FilterWriter fw = FilterWriter(new FileWriter("file"), "UTF8"); fw.write(msg);fw.close();}IMPLEMENTATION E:public void write(String msg) throws IOException { OutputStreamWriter osw = new OutputStreamWriter(new OutputStream(new File("file")), "UTF8");osw.write(msg);osw.close();}1) Implementation A.2) Implementation B.3) Implementation C.4) Implementation D.5) Implementation E.Q48Which are valid identifiers?1) _class2) $value$3) zer@4) ¥ngstr5) 2muchuqQ49What will be the result of attempting to compile and run the following program?public class Q28fd {public static void main(String args[]) {int counter = 0;l1:for (int i=10; i<0; i--) {l2:int j = 0;while (j < 10) {if (j > i) break l2;if (i == j) {counter++;continue l1;}}counter--;}System.out.println(counter);}}1) The program will fail to compile.2) The program will not terminate normally.3) The program will write 10 to the standard output.4) The program will write 0 to the standard output.5) The program will write 9 to the standard output.Q50Given the following interface definition, which definitions are valid?interface I {void setValue(int val);int getValue();}DEFINITION A:(a) class A extends I {int value;void setValue(int val) { value = val; }int getValue() { return value; }}DEFINITION B:(b) interface B extends I {void increment();}DEFINITION C:(c) abstract class C implements I {int getValue() { return 0; }abstract void increment();}DEFINITION D:(d) interface D implements I {void increment();}DEFINITION E:(e) class E implements I {int value;public void setValue(int val) { value = val; } }1) Definition A.2) Definition B.3) Definition C.4) Definition D.5) Definition E.Q51Which statements concerning the methods notify() and notifyAll() are true?1) Instances of class Thread have a method called notify().2) A call to the method notify() will wake the thread that currently owns the monitor of the object.3) The method notify() is synchronized.4) The method notifyAll() is defined in class Thread.5) When there is more than one thread waiting to obtain the monitor of an object, there is no way to be sure which thread will be notified by the notify() method.Q52Which statements concerning the correlation between the inner and outer instances of non-static inner classes are true?1) Member variables of the outer instance are always accessible to inner instances, regardless of their accessibility modifiers.2) Member variables of the outer instance can never be referred to using only the variable name within the inner instance.3) More than one inner instance can be associated with the same outer instance.4) All variables from the outer instance that should be accessible in the inner instance must be declared final.5) A class that is declared final cannot have any inner classes.Q53What will be the result of attempting to compile and run the following code?public class Q6b0c {public static void main(String args[]) {int i = 4;float f = 4.3;double d = 1.8;int c = 0;if (i == f) c++;if (((int) (f + d)) == ((int) f + (int) d)) c += 2;System.out.println(c);}}1) The code will fail to compile.2) 0 will be written to the standard output.3) 1 will be written to the standard output.4) 2 will be written to the standard output.5) 3 will be written to the standard output.Q54Which operators will always evaluate all the operands?1) ||2) +3) &&4) ? :5) %Q55Which statements concerning the switch construct are true?1) All switch statements must have a default label.2) There must be exactly one label for each code segment in a switch statement.3) The keyword continue can never occur within the body of a switch statement.4) No case label may follow a default label within a single switch statement.5) A character literal can be used as a value for a case label.Q56Which modifiers and return types would be valid in the declaration of a working main() method for a Java standalone application?1) private2) final3) static4) int5) abstractQ57What will be the appearance of an applet with the following init() method?public void init() {add(new Button("hello"));}1) Nothing appears in the applet.2) A button will cover the whole area of the applet.3) A button will appear in the top left corner of the applet.4) A button will appear, centered in the top region of the applet.5) A button will appear in the center of the applet.Q58Which statements concerning the event model of the AWT are true?1) At most one listener of each type can be registered with a component.2) Mouse motion listeners can be registered on a List instance.3) There exists a class named ContainerEvent in package java.awt.event.4) There exists a class named MouseMotionEvent in package java.awt.event.5) There exists a class named ActionAdapter in package java.awt.event.Q59Which statements are true, given the code new FileOutputStream("data", true) for creating an object of class FileOutputStream?1) FileOutputStream has no constructors matching the given arguments.2) An IOExeception will be thrown if a file named "data" already exists.3) An IOExeception will be thrown if a file named "data" does not already exist.4) If a file named "data" exists, its contents will be reset and overwritten.5) If a file named "data" exists, output will be appended to its current contents.Q60Given the following code, write a line of code that, when inserted at the indicated location, will make theoverriding method in Extension invoke the overridden method in class Base on the current object.class Base {public void print() {System.out.println("base");}}class Extention extends Base {public void print() {System.out.println("extension");// insert line of implementation here}}public class Q294d {public static void main(String args[]) {Extention ext = new Extention();ext.print();}}Fill in a single line of implementation.Q61Given that file is a reference to a File object that represents a directory, which code fragments will succeed in obtaining a list of the entries in the directory?1) Vector filelist = ((Directory) file).getList();2) String[] filelist = file.directory();3) Enumeration filelist = file.contents();4) String[] filelist = file.list();5) Vector filelist = (new Directory(file)).files();Q62What will be written to the standard output when the following program is run?。
SCJP模拟题 AND Answer [6]
![SCJP模拟题 AND Answer [6]](https://img.taocdn.com/s3/m/6f7931d6360cba1aa811da09.png)
Java Certification Mock ExamQ. 1Which colour is used to indicate instance methods in the standard "javadoc" format documentation:A. blueB. redC. purpleD. orangeSelect the most appropriate answer.Q. 2What is the correct ordering for the import, class and package declarations when found in a single file?A. package, import, classB. class, import, packageC. import, package, classD. package, class, importSelect the most appropriate answer.Q. 3Which methods can be legally applied to a string object?A. equals(String)B. equals(Object)C. trim()D. round()E. toString()Select all correct answers.Q. 4What is the parameter specification for the public static void main method?A. String args []B. String [] argsC. Strings args []D. String argsSelect all correct answers.Q. 5What does the zeroth element of the string array passed to the public static void main method contain?A. The name of the programB. The number of argumentsC. The first argument if one is presentSelect the most appropriate answer.Q. 6Which of the following are Java keywords?A. gotoB. mallocC. extendsD. FALSESelect all correct answersQ. 7What will be the result of compiling the following code:public class Test {public static void main (String args []) {int age;age = age + 1;System.out.println("The age is " + age);}}A. Compiles and runs with no outputB. Compiles and runs printing out The age is 1C. Compiles but generates a runtime errorD. Does not compileE. Compiles but generates a compile time errorSelect the most appropriate answer.Q. 8Which of these is the correct format to use to create the literal char value a?A. ‘a’B. "a"C. new Character(a)D. \000aSelect the most appropriate answer.Q. 9What is the legal range of a byte integral type?A. 0 - 65, 535B. (–128) – 127C. (–32,768) – 32,767D. (–256) – 255Select the most appropriate answer.Q. 10Which of the following is illegal:A. int i = 32;B. float f = 45.0;C. double d = 45.0;Select the most appropriate answer.Q. 11What will be the result of compiling the following code:public class Test {static int age;public static void main (String args []) {age = age + 1;System.out.println("The age is " + age);}}A. Compiles and runs with no outputB. Compiles and runs printing out The age is 1C. Compiles but generates a runtime errorD. Does not compileE. Compiles but generates a compile time errorSelect the most appropriate answer.Q. 12Which of the following are correct?A. 128 >> 1 gives 64B. 128 >>> 1 gives 64C. 128 >> 1 gives –64D. 128 >>> 1 gives –64Select all correct answersQ. 13Which of the following return true?A. "john" == "john"B. "john".equals("john")C. "john" = "john"D. "john".equals(new Button("john"))Select all correct answers.Q. 14Which of the following do not lead to a runtime error?A. "john" + " was " + " here"B. "john" + 3C. 3 + 5D. 5 + 5.5Select all correct answers.Q. 15Which of the following are so called "short circuit" logical operators?A. &B. ||C. &&D. |Select all correct answers.Q. 16Which of the following are acceptable?A. Object o = new Button("A");B. Boolean flag = true;C. Panel p = new Frame();D. Frame f = new Panel();E. Panel p = new Applet();Select all correct answers.Q. 17What is the result of compiling and running the following code:public class Test {static int total = 10;public static void main (String args []) {new Test();}public Test () {System.out.println("In test");System.out.println(this);int temp = this.total;if (temp > 5) {System.out.println(temp);}}}A. The class will not compileB. The compiler reports and error at line 2C. The compiler reports an error at line 9D. The value 10 is one of the elements printed to the standard outputE. The class compiles but generates a runtime errorSelect all correct answers.Q 18Which of the following is correct:A. String temp [] = new String {"j" "a" "z"};B. String temp [] = { "j " " b" "c"};C. String temp = {"a", "b", "c"};D. String temp [] = {"a", "b", "c"};Select the most appropriate answer.Q. 19What is the correct declaration of an abstract method that is intended to be public:A. public abstract void add();B. public abstract void add() {}C. public abstract add();D. public virtual add();Select the most appropriate answer.Q. 20Under what situations do you obtain a default constructor?A. When you define any classB. When the class has no other constructorsC. When you define at least one constructorSelect the most appropriate answer.Q. 21Given the following code:public class Test {…}Which of the following can be used to define a constructor for this class:A. public void Tes t() {…}B. public Test() {…}C. public static Test() {…}D. public static void Test() {…}Select the most appropriate answer.Q. 22Which of the following are acceptable to the Java compiler:A. if (2 == 3) System.out.println("Hi");B. if (2 = 3) System.out.println("Hi");C. if (true) System.out.println("Hi");D. if (2 != 3) System.out.println("Hi");E. if (aString.equals("hello")) System.out.println("Hi");Select all correct answers.Q. 23Assuming a method contains code which may raise an Exception (but not a RuntimeException), what is the correct way for a method to indicate that it expects the caller to handle that exception:A. throw ExceptionB. throws ExceptionC. new ExceptionD. Don't need to specify anythingSelect the most appropriate answer.Q. 24What is the result of executing the following code, using the parameters 4 and 0:public void divide(int a, int b) {try {int c = a / b;} catch (Exception e) {System.out.print("Exception ");} finally {System.out.println("Finally");}A. Prints out: Exception FinallyB. Prints out: FinallyC. Prints out: ExceptionD. No outputSelect the most appropriate answer.Q.25Which of the following is a legal return type of a method overloading the following method:public void add(int a) {…}A. voidB. intC. Can be anythingSelect the most appropriate answer.Q.26Which of the following statements is correct for a method which is overriding the following method:public void add(int a) {…}A. the overriding method must return voidB. the overriding method must return intC. the overriding method can return whatever it likesSelect the most appropriate answer.Q. 27Given the following classes defined in separate files:class Vehicle {public void drive() {System.out.println("Vehicle: drive");}}class Car extends Vehicle {public void drive() {System.out.println("Car: drive");}}public class Test {public static void main (String args []) {Vehicle v;Car c;v = new Vehicle();c = new Car();v.drive();c.drive();v = c;v.drive();}}What will be the effect of compiling and running this class Test?A. Generates a Compiler error on the statement v= c;B. Generates runtime error on the statement v= c;C. Prints out:Vehicle: driveCar: driveCar: driveD. Prints out:Vehicle: driveCar: driveVehicle: driveSelect the most appropriate answer.Q. 28Where in a constructor, can you place a call to a constructor defined in the super class?A. AnywhereB. The first statement in the constructorC. The last statement in the constructorD. You can't call super in a constructorSelect the most appropriate answer.Q. 29Which variables can an inner class access from the class which encapsulates it?A. All static variablesB. All final variablesC. All instance variablesD. Only final instance variablesE. Only final static variablesSelect all correct answers.Q. 30What class must an inner class extend:A. The top level classB. The Object classC. Any class or interfaceD. It must extend an interfaceSelect the most appropriate answer.Q. 31In the following code, which is the earliest statement, where the object originally held in e, may be garbage collected:1. public class Test {2. public static void main (String args []) {3. Employee e = new Employee("Bob", 48);4. e.calculatePay();5. System.out.println(e.printDetails());6. e = null;7. e = new Employee("Denise", 36);8. e.calculatePay();9. System.out.println(e.printDetails());10. }11. }A. Line 10B. Line 11C. Line 7D. Line 8E. NeverSelect the most appropriate answer.Q. 32What is the name of the interface that can be used to define a class that can execute within its own thread?A. RunnableB. RunC. ThreadableD. ThreadE. ExecutableSelect the most appropriate answer.Q. 33What is the name of the method used to schedule a thread for execution?A. init();B. start();C. run();D. resume();E. sleep();Select the most appropriate answer.Q. 34Which methods may cause a thread to stop executing?A. sleep();B. stop();C. yield();D. wait();E. notify();F. notifyAll()G. synchronized()Select all correct answers.Q. 35Write code to create a text field able to display 10 characters (assuming a fixed size font) displaying the initial string "hello"::Q. 36Which of the following methods are defined on the Graphics class:A. drawLine(int, int, int, int)B. drawImage(Image, int, int, ImageObserver)C. drawString(String, int, int)D. add(Component);E. setVisible(boolean);F. setLayout(Object);Select all correct answers.Q. 37Which of the following layout managers honours the preferred size of a component:A. CardLayoutB. FlowLayoutC. BorderLayoutD. GridLayoutSelect all correct answers.Q. 38Given the following code what is the effect of a being 5:public class Test {public void add(int a) {loop: for (int i = 1; i < 3; i++){for (int j = 1; j < 3; j++) {if (a == 5) {break loop;}System.out.println(i * j);}}}}A. Generate a runtime errorB. Throw an ArrayIndexOutOfBoundsExceptionC. Print the values: 1, 2, 2, 4D. Produces no outputSelect the most appropriate answer.Q. 39What is the effect of issuing a wait() method on an objectA. If a notify() method has already been sent to that object then it has no effectB. The object issuing the call to wait() will halt until another object sends a notify() or notifyAll() methodC. An exception will be raisedD. The object issuing the call to wait() will be automatically synchronized with any other objects using the receiving object.Select the most appropriate answer.Q. 40The layout of a container can be altered using which of the following methods:A. setLayout(aLayoutManager);B. addLayout(aLayoutManager);C. layout(aLayoutManager);D. setLayoutManager(aLayoutManager);Select all correct answers.Q. 41Using a FlowLayout manager, which is the correct way to add elements to a container:A. add(component);B. add("Center", component);C. add(x, y, component);D. set(component);Select the most appropriate answer.Q. 42Given that a Button can generate an ActionEvent which listener would you expect to have to implement, in a class which would handle this event?A. FocusListenerB. ComponentListenerC. WindowListenerD. ActionListenerE. ItemListenerSelect the most appropriate answer.Q. 43Which of the following, are valid return types, for listener methods:A. booleanB. the type of event handledC. voidD. ComponentSelect the most appropriate answer.Q. 44Assuming we have a class which implements the ActionListener interface, which method should be used to register this with a Button?A. addListener(*);B. addActionListener(*);C. addButtonListener(*);D. setListener(*);Select the most appropriate answer.Q. 45In order to cause the paint(Graphics) method to execute, which of the following is the mostappropriate method to call:A. paint()B. repaint()C. paint(Graphics)D. update(Graphics)E. None – you should never cause paint(Graphics) to executeSelect the most appropriate answer.Q. 46Which of the following illustrates the correct way to pass a parameter into an applet: A. tags?A. line 1, 2, 3B. line 2, 5, 6, 7C. line 3, 4, 5D. line 8, 9, 10E. line 8, 9Select all correct answers.Q. 59Which of the following is a legal way to construct a RandomAccessFile:A. RandomAccessFile("data", "r");B. RandomAccessFile("r", "data");C. RandomAccessFile("data", "read");D. RandomAccessFile("read", "data");Select the most appropriate answer.Q. 60Carefully examine the following code:public class StaticTest {static {System.out.println("Hi there");}public void print() {System.out.println("Hello");}public static void main(String args []) {StaticTest st1 = new StaticTest();st1.print();StaticTest st2 = new StaticTest();st2.print();}}When will the string "Hi there" be printed?A. Never.B. Each time a new instance is created.C. Once when the class is first loaded into the Java virtual machine.D. Only when the static method is called explicitly.Select the most appropriate answer.Q. 61Consider the following program:public class Test { public static void main (String args []) { boolean a = false; if (a = true)System.out.println("Hello");ElseSystem.out.println("Goodbye");}}What is the result:A. Program produces no output but terminates correctly.B. Program does not terminate.C. Prints out "Hello"D. Prints out "Goodbye"Select the most appropriate answer.Q. 62Examine the following code which includes an inner class:public final class Test4 implements A {class Inner {void test() {if (Test4.this.flag); {sample();}}}private boolean flag = false;public void sample() {System.out.println("Sample");}public Test4() {(new Inner()).test();}public static void main(String args []) {new Test4();}}What is the result:A. Prints out "Sample"B. Program produces no output but terminates correctly.C. Program does not terminate.D. The program will not compileSelect the most appropriate answer.Q. 63Carefully examine the following class:public class Test5 { public static void main (String args []) { /* This is the start of a commentif (true) {Test5 = new test5();System.out.println("Done the test");}/* This is another comment */System.out.println ("The end");}}What is the result:A. Prints out "Done the test" and nothing else.B. Program produces no output but terminates correctly.C. Program does not terminate.D. The program will not compile.E. The program generates a runtime exception.F. The program prints out "The end" and nothing else.G. The program prints out "Done the test" and "The end" Select the most appropriate answer.Q. 64The following code defines a simple applet:import java.applet.Applet;import java.awt.*;public class Sample extends Applet {private String text = "Hello World";public void init() {add(new Label(text));}public Sample (String string) {text = string;}}It is accessed form the following HTML page:What is the result of compiling and running this applet:A. Prints "Hello World".B. Generates a runtime error.C. Does nothing.D. Generates a compile time error.Select the most appropriate answer.Q. 65Examine the following code:public class Calc {public static void main (String args []) {int total = 0;for (int i = 0, j = 10; total > 30; ++i, --j) {System.out.println(" i = " + i + " : j = " + j);total += (i + j);}System.out.println("Total " + total);}}Does this code:A. Produce a runtime errorB. Produce a compile time errorC. Print out "Total 0"D. Generate the following as output:i = 0 : j = 10i = 1 : j = 9i = 2 : j = 8Total 30Please select the most appropriate answer.Answers to Java Certification Mock Exam1. B2. A3. A, B, C, E4. A, B5. C6. A, C7. D8. A9. B 10. B11. B 12. A,B 13. A, B 14. A, B, C, D 15.B, C16. A, E 17. D 18. D 19. A 20. B21. B 22. A, C, D, E 23. B 24. A 25. C26. A 27. C 28. B 29. A, B, C 30. C31. C 32. A 33. B 34. A, B, C, D 35. new TextField("hello", 10) 36. A, B, C 37. B 38. D 39. B 40. A41. A 42. D 43. C 44. B 45. B46. B 47. A, E 48. B 49. C 50. C51. F 52. A 53. F 54. C 55. D56. D, F 57. F 58. A, E 59. A 60. C61. C 62. A 63. F 64. B 65. C。
SCJP认证考试题库2

SCJP认证考试题库2What is the result?A. n ullB. zeroC. s omeD. C ompilation failsE. An exception is thrown at runtimeAnswer: ( D )13行会报错,应在15行使用else if 参考大纲:流程控制QUESTION 63Given the exhibit:What is the result?A. testB. ExceptionC. Compilation failsD. NullPointerExceptionAnswer: ( C )18行出错,应该先catch子异常,再catch Exception;13行把args赋null ,14行会报NullPointerException如果没有第13行运行时14行会报ArrayIndexOutOfBoundsException异常。
参考大纲:异常处理QUESTION 64Given the exhibit:What is the result?A. Compilation failsB. aAaA aAa AAaa AaAC. AAaa AaA aAa aAaAD. AaA AAaa aAaA aAaE. aAa AaA aAaA AAaaF. An exception is thrown at runtimeAnswer: ( C )第10行将对strings这个集合做自然排序(ASCII小到大,一个一个比较)Collections.sort(List list) 对list进行排序,对set 不能排序!List里可以放对象,所以当list里面存放的是对象的时候就不能用Collections.sort(List list)去排序了。
因为JVM不知道用什么规则去排序!!只有把对象类实现Comparable接口,然后改写compareTo()参考大纲:集合QUESTION 65Given the exhibit:What is the result?A. 0B. 1C. 2D. 3E. 4F. Compilation fails.G. An exception is thrown at runtimeAnswer: ( D )Set中存放的元素是无序不重复的。
一些SCJP考试题含答案

一些SCJP考试题含答案Leading the way in IT testing and certification tools,QUESTION NO: 92 Given:1. String foo = “blue”;2. Boolean[]bar = new Boolean [1];3. if (bar[0]) {4. foo = “green”;5. }What is the result?A. Foo has the value of “”B. Foo has the value of null.C. Foo has the value of “blue”D. Foo has the value of “green”E. An exception is thrown.F. The code will not compile.Answer: FQUESTION NO: 93Exhibit:1. public class X {2. public static void main (String[]args) {3. String s1 = new String (“true”);4. Boolean b1 = new Boolean (true);5. if (s2.equals(b1)) {6. System.out.printIn(“Equal”);7. }8. }9. }What is the result?A. The program runs and prints nothing.B. The program runs and prints “Equal”C. An error at line 5 causes compilation to fail.D. The program runs but aborts with an exception.Answer: AQUESTION NO: 94Given:1. public class Foo {2. public static void main (String []args) {3. int i = 1;4. int j = i++;5. if ((i>++j) && (i++ ==j)) {6. i +=j;7. }9. }What is the final value of i?A. 1B. 2C. 3D. 4E. 5Answer: BQUESTION NO: 95Exhibit:1. public class X {2. public static void main (String[]args) {3. string s = new string (“Hello”);4. modify(s);5. System.out.printIn(s);6. }7.8. public static void modify (String s) {9. s += “world!”;10. }11. }What is the result?E. The program runs and prints “Hello”F. An error causes compilation to fail.G. The program runs and prints “Hello world!”H. The program runs but aborts with an exception. Answer: AQUESTION NO: 96Which two are equivalent? (Choose Two)A. 16>4B. 16/2C. 16*4D. 16>>2E. 16/2^2F. 16>>>2Answer: D, EQUESTION NO: 97Exhibit:1. public class X {2. public static void main (String[]args) {3. int [] a = new int [1]4. modify(a);5. System.out.printIn(a[0]);7.8. public static void modify (int[] a) {9. a[0] ++;10. }11. }What is the result?A. The program runs and prints “0”B. The program runs and prints “1”C. The program runs but aborts with an exception.D. An error “possible undefined variable” at line 4 causes compilation to fail.E. An error “possible undefined variable” at line 9 causes compilation to fail. Answer: BQUESTION NO: 98Given:13. public class Foo {14. public static void main (String [] args) {15. StringBuffer a = new StringBuffer (“A”);16. StringBuffer b = new StringBuffer (“B”);17. operate (a,b);18. system.out.printIn,a + “,” +b-;19. )20. static void operate (StringBuffer x, StringBuffer y) {21. y.append {x};22. y = x;23. )24. }What is the result?A. The code compiles and prints “A,B”.B. The code compiles and prints “A, BA”.C. The code compiles and prints “AB, B”.D. The code compiles and prints “AB, AB”.E. The code compiles and prints “BA, BA”.F. The code does not compile because “+” cannot be overloaded for stringBuffer. Answer: BQUESTION NO: 99Given:1. public class X {2. public static void main (String[] args) {3. byte b = 127;4. byte c = 126;5. byte d = b + c;6. }7. }Which statement is true?A. Compilation succeeds and d takes the value 253.B. Line 5 contains an error that prevents compilation.C. Line 5 throws an exception indicating “Out of range”D. Line 3 and 4 contain error that prevent compilation.E. The compilation succeeds and d takes the value of 1.Answer: BQUESTION NO: 100Given:1. public class WhileFoo {2. public static void main (String []args) {3. int x= 1, y = 6;4. while (y--) {x--;}5. system.out.printIn(“x=” + x “y =” + y);6. }7. }What is the result?A. The output is x = 6 y = 0B. The output is x = 7 y = 0C. The output is x = 6 y = -1D. The output is x = 7 y = -1E. Compilation will fail.Answer: EQUESTION NO: 101Which statement is true?A. The Error class is a untimeException.B. No exceptions are subclasses of Error.C. Any statement that may throw an Error must be enclosed in a try block.D. Any statement that may throw an Exception must be enclosed in a try block.E. Any statement that may thro a runtimeException must be enclosed in a try block. Answer: DQUESTION NO: 102Exhibit:1. int I=1, j=02.3. switch(i) {4. case 2:5. j+=6;6.7. case 4:8. j+=1;9.10. default:11. j +=2;12.13. case 0:14. j +=4;15. }16.What is the value of j at line 16?A. 0B. 1C. 2D. 4E. 6Answer: AEQUESTION NO: 103Given:1. switch (i) {2. default:3. System.out.printIn(“Hello”);4. )What is the acceptable type for the variable i?A. ByteB. LongC. FloatD. DoubleE. ObjectF. A and BG. C and DAnswer: AQUESTION NO: 104You need to store elements in a collection that guarantees that no duplicates are stored. Which twointerfaces provide that capability? (Choose Two)A. Java.util.MapB. Java.util.SetC. Java.util.ListD. Java.util.StoredSetE. Java.util.StoredMapF. Java.util.CollectionAnswer: B, DQUESTION NO: 105Which statement is true for the class java.util.ArrayList?A. The elements in the collection are ordered.B. The collection is guaranteed to be immutable.C. The elements in the collection are guaranteed to be unique.D. The elements in the collection are accessed using a unique key.E. The elements in the collections are guaranteed to be synchronized.Answer: AQUESTION NO: 106Exhibit:1. public class X implements Runnable(2. private int x;3. private int y;4.5. public static void main(String[]args)6. X that = new X();7. (new Thread(that)).start();8. (new Thread(that)).start();9. )10.11. public void run() (12. for (;;) (13. x++;14. y++;15. System.out.printIn(“x=” + x + “, y = ” + y);16. )17. )18. )What is the result?A. Errors at lines 7 and 8 cause compilation to fail.B. The program prints pairs of values for x and y that might not always be the same on the same line(for example, “x=2, y=1”).C. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”.In addition, each value appears twice (for example, “x=1, y=1” followed by “x=1, y=1”).D. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”. In addition, each value appears only for once (for example, “x=1, y=1”followed by “x=2, y=2”).Answer: DQUESTION NO: 107Given:1. public class SyncTest {2. private int x;3. private int y;4. public synchronized void setX (int i) (x=1;)5. public synchronized void setY (int i) (y=1;)6. public synchronized void setXY(int 1)(set X(i); setY(i);)7. public synchronized Boolean check() (return x !=y;)8. )Under which conditions will check () return true when called from a different class?A. Check() can never return true.B. Check() can return true when setXY is called by multiple threads.C. Check() can return true when multiple threads call setX and setY separately.D. Check() can only return true if SyncTest is changed to allow x and y to be set separately. Answer: AQUESTION NO: 108Which is a method of the MouseMotionListener interface?A. Public void mouseDragged(MouseEvent)B. Public boolean mouseDragged(MouseEvent)C. Public void mouseDragged(MouseMotionEvent)D. Public boolean MouseDragged(MouseMotionEvent)E. Public boolean mouseDragged(MouseMotionEvent)Answer: AQUESTION NO: 109Given:1. String foo = “base”;2. foo.substring(0,3);3. foo.concat(“ket”);4. foo += “ball”;5.Type the value of foo at line 8.Answer: BASEBALLQUESTION NO 110Given:1. public class Test {2. public static void leftshift(int i, int j) {3. i<<=j;4. }5. public static void main(String args[]) {6. int i = 4, j = 2;7. leftshift(i, j);8. System.out.printIn(i);9. }10. }What is the result?A. 2B. 4C. 8D. 16E. The code will not compile.Answer: BQUESTION NO 111Given:1. public class Foo {2. private int val;3. public foo(int v) (val = v;) }4. public static void main (String [] args) {5. Foo a = new Foo (10);6. Foo b = new Foo (10);7. Foo c = a;8. int d = 10;9. double e = 10.0;10. }11. }Which three logical expression evaluate to true? (Choose Three)A. (a ==c)B. (d ==e)C. (b ==d)D. (a ==b)E. (b ==c)F. (d ==10.0)Answer: A, B, FQUESTION NO 112Exhibit:1. public class X {2. private static int a;3.5. public static void main (String[] args) {6. modify (a);7. }8.9. public static void modify (int a) {10. a++;11. }12. }What is the result?A. The program runs and prints “0”B. The program runs and prints “1”C. The program runs but aborts with an exception.D. En error “possible undefined variable” at line 5 causes compilation to fail.F. En error “possible undefined variable” at line 10 causes compilation to fail. Answer: AQUESTION NO 113Exhibit:1. public class Test {2. public static void replaceJ(string text) {3. text.replace (‘j’, ‘l’);4. }5.6. public static void main(String args[]) {7. string text = new String (“java”)8. replaceJ(text);9. system.out.printIn(text);10. }11. }What is the result?A. The program prints “lava”B. The program prints “java”C. An error at line 7 causes compilation to fail.D. Compilation succeeds but the program throws an exception. Answer: BQUESTION NO 114Which two are equivalent? (Choose Two)A. 3/2B. 3<2C. 3*4D. 3<<2E. 3*2^2F. 3<<<2Answer: C, DQUESTION NO 115What is the numerical range of a char?A. 0 . . . 32767B. 0 . . . 65535C. ?256 . . . 255D. ?32768 . . . 32767E. Range is platform dependent.Answer: BQUESTION NO 116Given:1. public class Test {2. public static void main (String []args) {3. unsigned byte b = 0;4. b--;5.6. }7. }What is the value of b at line 5?A. -1B. 255C. 127D. Compilation will fail.E. Compilation will succeed but the program will throw an exception at line 4.Answer: DQUESTION NO 117Given:1. public class Foo {2. public void main (String [] args) {3. system.out.printIn(“Hello World.”);4. }5. }What is the result?A. An exception is thrown.B. The code does no compile.C. “Hello World.” Is printed to the terminal.D. The program exits without printing anything.Answer: AQUESTION NO 118Given:1. //point X2. public class foo (3. public static void main (String[]args) throws Exception {4. java.io.printWriter out = new java.io.PrintWriter (5. new java.io.outputStreamWriter (System.out), true;6. out.printIn(“Hello”);7. }8. }Which statement at PointX on line 1 allows this code to compile and run?A. Import java.io.*;B. Include java.io.*;C. Import java.io.PrintWriter;D. Include java.io.PrintWriter;E. No statement is needed.Answer: EQUESTION NO 119Which will declare a method that is available to all members of the same package and can be referencedwithout an instance of the class?A. Abstract public void methoda();B. Public abstract double methoda();C. Static void methoda(double d1){}D. Public native double methoda() {}E. Protected void methoda(double d1) {}Answer: CQUESTION NO 120Which type of event indicates a key pressed on a ponent?A. KeyEventB. KeyDownEventC. KeyPressEventD. KeyTypedEventE. KeyPressedEventAnswer: AQUESTION NO 121Exhibit:1. import java.awt.*;2.3. public class X extends Frame {4. public static void main (String [] args) {5. X x = new X();6. x.pack();7. x.setVisible(true);8. }9.10. public X() {11. setLayout (new BordrLayout());12. Panel p = new Panel ();13. add(p, BorderLayout.NORTH);14. Button b = new Button (“North”);15. p.add(b):16. Button b = new Button (“South”);17. add(b1, BorderLayout.SOUTH):18. }19. }Which two statements are true? (Choose Two)A. The buttons labeled “North” and “South” will have the s ame width.B. The buttons labeled “North” and “South” will have the same height.C. The height of the button labeled “North” can very if the Frame is resized.D. The height of the button labeled “South” can very if the Frame is resized.E. The width of the button labeled “North” is constant even if the Frame is resized.F. The width of the button labeled “South” is constant even if the Frame is resized. Answer: B, EQUESTION NO 122How can you create a listener class that receives events when the mouse is moved?A. By extending MouseListener.B. By implementing MouseListener.C. By extending MouseMotionListener.D. By implementing MouseMotionListener.E. Either by extending MouseMotionListener or extending MouseListener.F. Either by implementing MouseMotion Listener or implementing MouseListener.Answer: DQUESTION NO 123Which statement is true?A. A grid bag layout can position components such that they span multiple rows and/or columns.B. The “North” region of a border layout is the proper place to locat e a menuBar component in a Frame.C. Components in a grid bag layout may either resize with their cell, or remain centered in that cell attheir preferred size.D. A border layout can be used to position a component that should maintain a constant size evenwhen the container is resized.Answer: AQUESTION NO 124You want a class to have access to members of another class in the same package. Which is the mostrestrictive access modifier that will accomplish that will accomplish this objective?A. PublicB. PrivateC. ProtectedD. TransientE. No access modifier is required.Answer: EQUESTION NO 125Which two statements are true regarding the creation of a default constructor? (Choose Two)A. The default constructor initializes method variables.B. The default constructor invokes the no-parameter constructor of the superclass.C. The default constructor initializes the instance variables declared in the class.D. If a class lacks a no-parameter constructor,, but has other constructors, the compiler creates a default constructor.E. The compiler creates a default constructor only when there are no other constructors for the class.Answer: C, EQUESTION NO 126Given:1. public class OuterClass {2. private double d1 1.0;3. //insert code here4. }You need to insert an inner class declaration at line2. Which two inner class declarations are valid?(Choose Two)A. static class InnerOne {public double methoda() {return d1;}}B. static class InnerOne {static double methoda() {return d1;}}C. private class InnerOne {public double methoda() {return d1;}}D. protected class InnerOne {static double methoda() {return d1;}}E. public abstract class InnerOne {public abstract double methoda();}Answer: C, EQUESTION NO 127Which two declarations prevent the overriding of a method? (Choose Two)A. Final void methoda() {}B. Void final methoda() {}C. Static void methoda() {}D. Static final void methoda() {}E. Final abstract void methoda() {}Answer: A, DQUESTION NO 128Given:1. public class Test {2. public static void main (String args[]) {3. class Foo {4. public int i = 3;5. }6. Object o = (Object) new Foo();7. Foo foo = (Foo)o;8. System.out.printIn(foo. i);9. }10. }What is the result?A. Compilation will fail.B. Compilation will succeed and the progr am will print “3”C. Compilation will succeed but the program will throw a ClassCastException at line 6.D. Compilation will succeed but the program will throw a ClassCastException at line 7. Answer: BQUESTION NO 129Which two create an instance of an array? (Choose Two)A. int[] ia = new int [15];B. float fa = new float [20];C. char*+ ca = “Some String”;D. Object oa = new float[20];E. Int ia [][] = (4, 5, 6) (1, 2, 3)Answer: A, DQUESTION NO 130Given:1. public class ExceptionTest {2. class TestException extends Exception {}3. public void runTest () throws TestException {}4. public void test () /* Point X*/ {5. runTest ();6. }7. }At point X on line 4, which code can be added to make the code compile?A. Throws Exception.B. Catch (Exception e).C. Throws RuntimeException.D. Catch (TestException e).E. No code is necessary.Answer: BQUESTION NO 131Exhibit:1. public class SwitchTest {2. public static void main (String []args) {3. System.out.PrintIn(“value =” +switchIt(4));4. }5. public static int switchIt(int x) {6. int j = 1;7. switch (x) {8. case 1: j++;9. case 2: j++;10. case 3: j++;11. case 4: j++;12. case 5: j++;13. default:j++;14. }15. return j + x;16. }17. }What is the output from line 3?A. Value = 3B. Value = 4C. Value = 5D. Value = 6E. Value = 7F. Value = 8Answer: FQUESTION NO 132Which four types of objects can be thrown using the throw statement? (Choose Four)A. ErrorB. EventC. ObjectD. ExceptionE. ThrowableF. RuntimeExceptionAnswer: A, D, E, FQUESTION NO 133Given:1. public class ForBar {2. public static void main(String []args) {3. int i = 0, j = 5;4. tp: for (;;) {5. i ++;6. for(;;)7. if(i > --j) break tp;8. }9. system.out.printIn(“i = ” + i + “, j = “+ j);10. }11. }What is the result?A. The program runs and prints “i=1, j=0”B. The program runs and prints “i=1, j=4”C. The program runs and prints “i=3, j=4”D. The program runs and prints “i=3, j=0”E. An error at line 4 causes compilation to fail.F. An error at line 7 causes compilation to fail.Answer: AQUESTION NO 134Which two can directly cause a thread to stop executing? (Choose Two)A. Exiting from a synchronized block.B. Calling the wait method on an object.C. Calling the notify method on an object.D. Calling the notifyAll method on an object.E. Calling the setPriority method on a thread object.Answer: B, EQUESTION NO 135Given:1. public class Foo implements Runnable (2. public void run (Thread t) {3. system.out.printIn(“Running.”);4. }5. public static void main (String[] args) {6. new thread (new Foo()).start();7. )8. )What is the result?A. An exception is thrown.B. The program exists without printing anything.C. An error at line 1 causes compilation to fail.D. An error at line 6 causes the compilation to fail.E. “Running” is printed and the program exits. Answer: CQUESTION NO 136Which constructs a DataOutputStream?A. New dataInputStream(“in.txt”);B. New dataInputStream(new file(“in.txt”));C. New dataInputStream(new writer(“in.txt”));D. New dataInputSt ream(new FileWriter(“in.txt”));E. New dataInputStream(new InputStream(“in.txt”));F. New dataInputStream(new FileInputStream(“in.txt”)); Answer: FQUESTION NO 137Which can be used to decode charS for output?A. Java.io.InputStream.B. Java.io.EncodedReader.C. Java.io.InputStreamReader.D. Java.io.InputStreamWriter.E. Java.io.BufferedInputStream.Answer: CQUESTION NO 138Given:1. public class Test {2. public static void main (String [] args) {3. string foo = “blue”;4. string bar = foo;5. foo = “green”;6. System.out.printIn(bar);7. }8. }What is the result?A. An exception is thrown.B. The code will not compile.C. The program prints “null”D. The program prints “blue”E. The program prints “green”Answer: DQUESTION NO 139Which code determines the int value foo closest to a double value bar?A. Int foo = (int) Math.max(bar);B. Int foo = (int) Math.min(bar);C. Int foo = (int) Math.abs(bar);D. Int foo = (int) Math.ceil(bar);E. Int foo = (int) Math.floor(bar);F. Int foo = (int) Math.round(bar);Answer: FQUESTION NO 140Which two demonstrate encapsulation of data? (Choose Two)A. Member data have no access modifiers.B. Member data can be modified directly.C. The access modifier for methods is protected.D. The access modifier to member data is private.E. Methods provide for access and modification of data.Answer: D, EQUESTION NO 141Exhibit:1. class A {2. public String toString () {3. return “4”;4. }5. }6. class B extends A {7. 8. public String toString () {8. return super.toString() + “3”;9. }10. }11. public class Test {12. public static void main(String[]args) {13. System.out.printIn(new B());14. }15. }What is the result?A. Compilation succeeds and 4 is printed.B. Compilation succeeds and 43 is printed.C. An error on line 9 causes compilation to fail.D. An error on line 14 causes compilation to fail.E. Compilation succeeds but an exception is thrown at line 9.Answer: BQUESTION NO 142Which two statements are true? (Choose Two)A. An anonymous inner class can be declared inside of a methodB. An anonymous inner class constructor can take arguments in some situation.C. An anonymous inner class that is a direct subclass that is a direct subclass of Object can implementmultiple interfaces.D. Even if a class Super does not implement any interfaces, it is still possible to define an anonymousinner class that is an immediate subclass of Super that implements a single interface.E. Event if a class Super does not implement any interfaces, it is still possible to define an anonymousinner class that is an immediate subclass of Super that implements multiple interfaces. Answer: A, BQUESTION NO 143Given:1. public class MethodOver {2. private int x, y;3. private float z;4. public void setVar(int a, int b, float c){5. x = a;6. y = b;7. z = c;8. }9. }Which two overload the setVar method? (Choose Two)A. void setVar (int a, int b, float c){x = a;y = b;z = c;}B. public void setVar(int a, float c, int b) {setVar(a, b, c);}C. public void setVar(int a, float c, int b) {this(a, b, c);}D. public void setVar(int a, float b){x = a;z = b;}E. public void setVar(int ax, int by, float cz) {x = ax;y = by;z = cz;}Answer: B, DQUESTION NO 144Which statements about static inner classes are true? (Choose Two)A. A static inner class requires a static initializer.B. A static inner class requires an instance of the enclosing class.C. A static inner class has no reference to an instance of the enclosing class.D. A static inner class has access to the non-static members of the outer class.E. Static members of a static inner class can be referenced using the class name of the static inner class.Answer: C, EQUESTION NO 145Given:1. public class X {2. public object m () {3. object o = new float (3.14F);4. object [] oa = new object [1];5. oa[0]= o;6. o = null;7. oa[0] = null;9. return o;9. }10. }When is the float object created in line 3, eligible for garbage collection?A. Just after line 5.B. Just after line 6.C. Just after line 7.D. Just after line 8(that is, as the method returns).Answer: CQUESTION NO 146Which two interfaces provide the capability to store objects using a key-value pair? (Choose Two)A. Java.util.Map.B. Java.util.Set.C. Java.util.List.D. Java.util.StoredSet.E. Java.util.StoredMap.F. Java.util.Collection.Answer: A, EQUESTION NO 147Which interface does java.util.Hashable implement?A. Java.util.Map.B. Java.util.List.C. Java.util.Hashable.D. Java.util.Collection. Answer: A。
SCJP官方题库

QUESTION NO: 1Given:1. public class Threads2 implements Runnable {2.3. public void run() {4. System.out.println("run.");5. throw new RuntimeException("Problem");6. }7. public static void main(String[] args) {8. Thread t = new Thread(new Threads2());9. t.start();10. System.out.println("End of method.");11. }12. }Which two can be results? (Choose two.)A. ng.RuntimeException: ProblemB. runng.RuntimeException: ProblemC. End of method.ng.RuntimeException: ProblemD. End of method.run.ng.RuntimeException: ProblemE. runng.RuntimeException: ProblemEnd of method.Answer: D,EQUESTION NO: 2Which two statements are true? (Choose two.)A. It is possible for more than two threads to deadlock at once.B. The JVM implementation guarantees that multiple threads cannot enter into a deadlocked state.C. Deadlocked threads release once their sleep() method's sleep duration has expired.D. Deadlocking can occur only when the wait(), notify(), and notifyAll() methods are usedincorrectly.E. It is possible for a single-threaded application to deadlock if synchronized blocks are usedincorrectly.F. If a piece of code is capable of deadlocking, you cannot eliminate the possibility of deadlockingby inserting invocations of Thread.yield().Answer: A,FQUESTION NO: 3Given:7. void waitForSignal() {8. Object obj = new Object();9. synchronized (Thread.currentThread()) {10. obj.wait();11. obj.notify();12. }13. }Which statement is true?A. This code can throw an InterruptedException.B. This code can throw an IllegalMonitorStateException.C. This code can throw a TimeoutException after ten minutes.D. Reversing the order of obj.wait() and obj.notify() might cause this method to complete normally.E. A call to notify() or notifyAll() from another thread might cause this method to completenormally.F. This code does NOT compile unless "obj.wait()" is replaced with "((Thread)obj).wait()".Answer: BQUESTION NO: 4Click the Exhibit button.What is the output if the main() method is run?A. 4B. 5C. 8D. 9E. Compilation fails.F. An exception is thrown at runtime.G. It is impossible to determine for certain. Answer: DQUESTION NO: 5Given:11. class PingPong2 {12. synchronized void hit(long n) {13. for(int i = 1; i < 3; i++)14. System.out.print(n + "-" + i + " ");15. }16. }17. public class Tester implements Runnable {18. static PingPong2 pp2 = new PingPong2();19. public static void main(String[] args) {20. new Thread(new Tester()).start();21. new Thread(new Tester()).start();22. }23. public void run() { pp2.hit(Thread.currentThread().getId()); }24. }Which statement is true?A. The output could be 5-1 6-1 6-2 5-2B. The output could be 6-1 6-2 5-1 5-2C. The output could be 6-1 5-2 6-2 5-1D. The output could be 6-1 6-2 5-1 7-1 Answer: BQUESTION NO: 6Given:1. public class Threads4 {2. public static void main (String[] args) {3. new Threads4().go();4. }5. public void go() {6. Runnable r = new Runnable() {7. public void run() {8. System.out.print("foo");9. }10. };11. Thread t = new Thread(r);12. t.start();13. t.start();14. }15. }What is the result?A. Compilation fails.B. An exception is thrown at runtime.C. The code executes normally and prints "foo".D. The code executes normally, but nothing is printed. Answer: BQUESTION NO: 7Given:11. public abstract class Shape {12. private int x;13. private int y;14. public abstract void draw();15. public void setAnchor(int x, int y) {16. this.x = x;17. this.y = y;18. }19. }Which two classes use the Shape class correctly? (Choose two.)A. public class Circle implements Shape {private int radius;}B. public abstract class Circle extends Shape { private int radius;}C. public class Circle extends Shape {private int radius;public void draw();}D. public abstract class Circle implements Shape { private int radius;public void draw();}E. public class Circle extends Shape {private int radius;public void draw() {/* code here */}F. public abstract class Circle implements Shape { private int radius;public void draw() { /* code here */ } Answer: B,EQUESTION NO: 8Given:11. public class Barn {12. public static void main(String[] args) {13. new Barn().go("hi", 1);14. new Barn().go("hi", "world", 2);15. }16. public void go(String... y, int x) {17. System.out.print(y[y.length - 1] + " ");18. }19. }What is the result?A. hi hiB. hi worldC. world worldD. Compilation fails.E. An exception is thrown at runtime.Answer: DQUESTION NO: 9Given:10. class Nav{11. public enum Direction { NORTH, SOUTH, EAST, WEST }12. }13. public class Sprite{14. // insert code here15. }Which code, inserted at line 14, allows the Sprite class to compile?A. Direction d = NORTH;B. Nav.Direction d = NORTH;C. Direction d = Direction.NORTH;D. Nav.Direction d = Nav.Direction.NORTH; Answer: DQUESTION NO: 10Click the Exhibit button.Which statement is true about the classes and interfaces in the exhibit?A. Compilation will succeed for all classes and interfaces.B. Compilation of class C will fail because of an error in line 2.C. Compilation of class C will fail because of an error in line 6.D. Compilation of class AImpl will fail because of an error in line 2.Answer: CQUESTION NO: 11Click the Exhibit button.What is the result?A. 4321B. 0000C. An exception is thrown at runtime.D. Compilation fails because of an error in.Answer: DQUESTION NO: 12Given:11. public class Rainbow {12. public enum MyColor {13. RED(0xff0000), GREEN(0x00ff00), BLUE(0x0000ff);14. private final int rgb;15. MyColor(int rgb) { this.rgb = rgb; }16. public int getRGB() { return rgb; }17. }; 18. public static void main(String[] args) {19. // insert code here20. }21. }Which code fragment, inserted at line 19, allows the Rainbow class to compile?A. MyColor skyColor = BLUE;B. MyColor treeColor = MyColor.GREEN;C. if(RED.getRGB() < BLUE.getRGB()) { }D. Compilation fails due to other error(s) in the code.E. MyColor purple = new MyColor(0xff00ff);F. MyColor purple = MyColor.BLUE + MyColor.RED; Answer: BQUESTION NO: 13Given:11. class Mud {12. // insert code here13. System.out.println("hi");14. }15. }And the following five fragments:public static void main(String...a) {public static void main(String.* a) {public static void main(String... a) {public static void main(String[]... a) {public static void main(String...[] a) {How many of the code fragments, inserted independently at line 12, compile?A. 0B. 1C. 2D. 3E. 4F. 5Answer: DQUESTION NO: 14Given:5. class Atom {6. Atom() { System.out.print("atom "); }7. }8. class Rock extends Atom {9. Rock(String type) { System.out.print(type); }10. }11. public class Mountain extends Rock {12. Mountain() {13. super("granite ");14. new Rock("granite ");15. }16. public static void main(String[] a) { new Mountain(); }17. }What is the result?A. Compilation fails.B. atom graniteC. granite graniteD. atom granite graniteE. An exception is thrown at runtime.F. atom granite atom graniteAnswer: FQUESTION NO: 15Given:1. interface TestA { String toString(); }2. public class Test {3. public static void main(String[] args) {4. System.out.println(new TestA() {5. public String toString() { return "test"; }6. });7. }8. }What is the result?A. testB. nullC. An exception is thrown at runtime.D. Compilation fails because of an error in line 1.E. Compilation fails because of an error in line 4.F. Compilation fails because of an error in line 5. Answer: AQUESTION NO: 16Given:11. public static void parse(String str) {12. try {13. float f = Float.parseFloat(str);14. } catch (NumberFormatException nfe) {15. f = 0;16. } finally {17. System.out.println(f);18. }19. }20. public static void main(String[] args) {21. parse("invalid");22. }What is the result?A. 0.0B. Compilation fails.C. A ParseException is thrown by the parse method at runtime.D. A NumberFormatException is thrown by the parse method at runtime.Answer: BQUESTION NO: 17Given:1. public class Blip {2. protected int blipvert(int x) { return 0; }3. }4. class Vert extends Blip {5. // insert code here6. }Which five methods, inserted independently at line 5, will compile? (Choose five.)A. public int blipvert(int x) { return 0; }B. private int blipvert(int x) { return 0; }C. private int blipvert(long x) { return 0; }D. protected long blipvert(int x) { return 0; }E. protected int blipvert(long x) { return 0; }F. protected long blipvert(long x) { return 0; }G. protected long blipvert(int x, int y) { return 0; } Answer: A,C,E,F,GQUESTION NO: 18Given:1. class Super {2. private int a;3. protected Super(int a) { this.a = a; }4. }...11. class Sub extends Super {12. public Sub(int a) { super(a); }13. public Sub() { this.a = 5; }14. }Which two, independently, will allow Sub to compile? (Choose two.)A. Change line 2 to:public int a;B. Change line 2 to:protected int a;C. Change line 13 to:public Sub() { this(5); }D. Change line 13 to:public Sub() { super(5); }E. Change line 13 to:public Sub() { super(a); }Answer: C,DQUESTION NO: 19Which Man class properly represents the relationship "Man has a best friend who is a Dog"?A. class Man extends Dog { }B. class Man implements Dog { }C. class Man { private BestFriend dog; }D. class Man { private Dog bestFriend; }E. class Man { private Dog<bestFriend>; }F. class Man { private BestFriend<dog>; } Answer: DQUESTION NO: 20Given:1. package test;2.3. class Target {4. public String name = "hello";5. }What can directly access and change the value of the variable name?A. any classB. only the Target classC. any class in the test packageD. any class that extends TargetAnswer: CQUESTION NO: 21Given:11. abstract class Vehicle { public int speed() { return 0; }12. class Car extends Vehicle { public int speed() { return 60; }13. class RaceCar extends Car { public int speed() { return 150; }...21. RaceCar racer = new RaceCar();22. Car car = new RaceCar();23. Vehicle vehicle = new RaceCar();24. System.out.println(racer.speed() + ", " + car.speed()25. + ", " + vehicle.speed());What is the result?A. 0, 0, 0B. 150, 60, 0C. Compilation fails.D. 150, 150, 150E. An exception is thrown at runtime.Answer: DQUESTION NO: 22Given:5. class Building { }6. public class Barn extends Building {7. public static void main(String[] args) {8. Building build1 = new Building();9. Barn barn1 = new Barn();10. Barn barn2 = (Barn) build1;11. Object obj1 = (Object) build1;12. String str1 = (String) build1;13. Building build2 = (Building) barn1;14. }15. }Which is true?A. If line 10 is removed, the compilation succeeds.B. If line 11 is removed, the compilation succeeds.C. If line 12 is removed, the compilation succeeds.D. If line 13 is removed, the compilation succeeds.E. More than one line must be removed for compilation to succeed.Answer: CQUESTION NO: 23A team of programmers is reviewing a proposed API for a new utility class. After some discussion,they realize that they can reduce the number of methods in the API without losing anyfunctionality. If they implement the new design, which two OO principles will they be promoting?A. Looser couplingB. Tighter couplingC. Lower cohesionD. Higher cohesionE. Weaker encapsulationF. Stronger encapsulationAnswer: AQUESTION NO: 24 Given:21. class Money {22. private String country = "Canada";23. public String getC() { return country; }24. }25. class Yen extends Money {26. public String getC() { return super.country; }27. }28. public class Euro extends Money {29. public String getC(int x) { return super.getC(); }30. public static void main(String[] args) {31. System.out.print(new Yen().getC() + " " + newEuro().getC());32. }33. }What is the result?A. CanadaB. nullCanadaC. Canada nullD. Canada CanadaE. Compilation fails due to an error on line 26.F. Compilation fails due to an error on line 29. Answer: EQUESTION NO: 25Assuming that the serializeBanana() and the deserializeBanana() methods will correctly use Java serialization and given:13. import java.io.*;14. class Food implements Serializable {int good = 3;}15. class Fruit extends Food {int juice = 5;}16. public class Banana extends Fruit {17. int yellow = 4;18. public static void main(String [] args) {19. Banana b = new Banana(); Banana b2 = new Banana();20. b.serializeBanana(b); // assume correct serialization21. b2 = b.deserializeBanana(); // assume correct22. System.out.println("restore "+b2.yellow+b2.juice+b2.good);24. }25. // more Banana methods go here50. }What is the result?A. restore 400B. restore 403C. restore 453D. Compilation fails.E. An exception is thrown at runtime.Answer: CQUESTION NO: 26Given a valid DateFormat object named df, and16. Date d = new Date(0L);17. String ds = "December 15, 2004";18. // insert code hereWhat updates d's value with the date represented by ds?A. 18. d = df.parse(ds);B. 18. d = df.getDate(ds);C. 18. try {19. d = df.parse(ds);20. } catch(ParseException e) { };D. 18. try {19. d = df.getDate(ds);20. } catch(ParseException e) { };Answer: CQUESTION NO: 27Given:11. double input = 314159.26;12. NumberFormat nf =NumberFormat.getInstance(Locale.ITALIAN);13. String b;14. //insert code hereWhich code, inserted at line 14, sets the value of b to 314.159,26?A. b = nf.parse( input );B. b = nf.format( input );C. b = nf.equals( input );D. b = nf.parseObject( input );Answer: BQUESTION NO: 28Given:1. public class TestString1 {2. public static void main(String[] args) {3. String str = "420";4. str += 42;5. System.out.print(str);6. }7. }What is the output?A. 42B. 420C. 462D. 42042E. Compilation fails.F. An exception is thrown at runtime.Answer: DQUESTION NO: 29Which capability exists only in java.io.FileWriter?A. Closing an open stream.B. Flushing an open stream.C. Writing to an open stream.D. Writing a line separator to an open stream. Answer: DQUESTION NO: 30Given that the current directory is empty, and that the user has read and write permissions, andthe following:11. import java.io.*;12. public class DOS {13. public static void main(String[] args) {14. File dir = new File("dir");15. dir.mkdir(); 16. File f1 = new File(dir, "f1.txt");17. try {18. f1.createNewFile();19. } catch (IOException e) { ; }20. File newDir = new File("newDir");21. dir.renameTo(newDir);22. }23. }Which statement is true?A. Compilation fails.B. The file system has a new empty directory named dir.C. The file system has a new empty directory named newDir.D. The file system has a directory named dir, containing a file f1.txt.E. The file system has a directory named newDir, containing a file f1.txt.Answer: EQUESTION NO: 31Given:22. StringBuilder sb1 = new StringBuilder("123");23. String s1 = "123";24. // insert code here25. System.out.println(sb1 + " " + s1);Which code fragment, inserted at line 24, outputs "123abc 123abc"?A. sb1.append("abc"); s1.append("abc");B. sb1.append("abc"); s1.concat("abc");C. sb1.concat("abc"); s1.append("abc");D. sb1.concat("abc"); s1.concat("abc");E. sb1.append("abc"); s1 = s1.concat("abc");F. sb1.concat("abc"); s1 = s1.concat("abc");G. sb1.append("abc"); s1 = s1 + s1.concat("abc");H. sb1.concat("abc"); s1 = s1 + s1.concat("abc"); Answer: EQUESTION NO: 32Click the Exhibit button.Which code, inserted at line 14, will allow this class tocorrectly serialize and deserialize?A. s.defaultReadObject();B. this = s.defaultReadObject();C. y = s.readInt(); x = s.readInt();D. x = s.readInt(); y = s.readInt();Answer: DQUESTION NO: 33Given:1. public class LineUp {2. public static void main(String[] args) {3. double d = 12.345;4. // insert code here5. }6. }Which code fragment, inserted at line 4, produces the output | 12.345|?A. System.out.printf("|%7d| \n", d);B. System.out.printf("|%7f| \n", d);C. System.out.printf("|%3.7d| \n", d);D. System.out.printf("|%3.7f| \n", d);E. System.out.printf("|%7.3d| \n", d);F. System.out.printf("|%7.3f| \n", d);Answer: FQUESTION NO: 34Given:11. public class Test {12. public static void main(String [] args) {13. int x = 5;14. boolean b1 = true;15. boolean b2 = false;16.17. if ((x == 4) && !b2 )18. System.out.print("1 ");19. System.out.print("2 ");20. if ((b2 = true) && b1 )21. System.out.print("3 ");22. }23. }What is the result?A. 2B. 3C. 1 2D. 2 3E. 1 2 3F. Compilation fails.G. An exception is thrown at runtime. Answer: DQUESTION NO: 35Given:10. interface Foo {}11. class Alpha implements Foo {}12. class Beta extends Alpha {}13. class Delta extends Beta {14. public static void main( String[] args ) {15. Beta x = new Beta(); 16. // insert code here17. }18. }Which code, inserted at line 16, will cause ang.ClassCastException?A. Alpha a = x;B. Foo f = (Delta)x;C. Foo f = (Alpha)x;D. Beta b = (Beta)(Alpha)x;Answer: BQUESTION NO: 36Given:22. public void go() {23. String o = "";24. z:25. for(int x = 0; x < 3; x++) {26. for(int y = 0; y < 2; y++) {27. if(x==1) break;28. if(x==2 && y==1) break z;29. o = o + x + y;30. }31. }32. System.out.println(o);33. }What is the result when the go() method is invoked?A. 00B. 0001C. 000120D. 00012021E. Compilation fails.F. An exception is thrown at runtime.Answer: CQUESTION NO: 37Given:11. static void test() throws RuntimeException {12. try {13. System.out.print("test ");14. throw new RuntimeException();15. }16. catch (Exception ex) { System.out.print("exception "); }17. }18. public static void main(String[] args) {19. try { test(); }20. catch (RuntimeException ex){ System.out.print("runtime "); }21. System.out.print("end ");22. }What is the result?A. test endB. Compilation fails.C. test runtime endD. test exception endE. A Throwable is thrown by main at runtime. Answer: DQUESTION NO: 38Given:33. try {34. // some code here35. } catch (NullPointerException e1) {36. System.out.print("a");37. } catch (Exception e2) {38. System.out.print("b");39. } finally {40. System.out.print("c");41. }If some sort of exception is thrown at line 34, which output is possible?A. aB. bC. cD. acE. abcAnswer: DQUESTION NO: 39Given:31. // some code here32. try {33. // some code here34. } catch (SomeException se) {35. // some code here36. } finally {37. // some code here38. }Under which three circumstances will the code on line 37 be executed? (Choose three.)A. The instance gets garbage collected.B. The code on line 33 throws an exception.C. The code on line 35 throws an exception.D. The code on line 31 throws an exception.E. The code on line 33 executes successfully. Answer: B,C,EQUESTION NO: 40Given:10. int x = 0;11. int y = 10;12. do {13. y--;14. ++x;15. } while (x < 5);16. System.out.print(x + "," + y);What is the result?A. 5,6B. 5,5C. 6,5D. 6,6Answer: BQUESTION NO: 41Given:1. public class Donkey2 {2. public static void main(String[] args) {3. boolean assertsOn = true;4. assert (assertsOn) : assertsOn = true;5. if(assertsOn) {6. System.out.println("assert is on");7. }8. }9. }If class Donkey is invoked twice, the first time without assertions enabled, and the second timewith assertions enabled, what are the results?A. no outputB. no output assert is onC. assert is onD. no outputAn AssertionError is thrown.E. assert is onAn AssertionError is thrown.Answer: CQUESTION NO: 42Click the Exhibit button.Given:31. public void method() {32. A a = new A();33. a.method1();34. }Which statement is true if a TestException is thrown on line 3 of class B?A. Line 33 must be called within a try block.B. The exception thrown by method1 in class A is not required to be caught.C. The method declared on line 31 must be declared to throw a RuntimeException.D. On line 5 of class A, the call to method2 of class B does not need to be placed in atry/catch block.Answer: BQUESTION NO: 43Given:11. Float pi = new Float(3.14f);12. if (pi > 3) {13. System.out.print("pi is bigger than 3. ");14. }15. else {16. System.out.print("pi is not bigger than 3. ");17. }18. finally {19. System.out.println("Have a nice day.");20. }What is the result?A. Compilation fails.B. pi is bigger than 3.C. An exception occurs at runtime.D. pi is bigger than 3. Have a nice day.E. pi is not bigger than 3. Have a nice day. Answer: AQUESTION NO: 44Given:1. public class Boxer1{2. Integer i;3. int x;4. public Boxer1(int y) {5. x = i+y;6. System.out.println(x);7. }8. public static void main(String[] args) {9. new Boxer1(new Integer(4));10. }11. }What is the result?A. The value "4" is printed at the command line.B. Compilation fails because of an error in line 5.C. Compilation fails because of an error in line 9.D. A NullPointerException occurs at runtime.E. A NumberFormatException occurs at runtime.F. An IllegalStateException occurs at runtime. Answer: DQUESTION NO: 45Given:1. public class Person {2. private String name;3. public Person(String name) { = name; }4. public boolean equals(Person p) {5. return .equals();6. }7. }Which statement is true?A. The equals method does NOT properly override the Object.equals method.B. Compilation fails because the private attribute cannot be accessed in line 5.C. To work correctly with hash-based data structures, this class must also implement thehashCode method.D. When adding Person objects to a java.util.Set collection, the equals method in line 4 willprevent duplicates. Answer: AQUESTION NO: 46Which two statements are true about the hashCode method? (Choose two.)A. The hashCode method for a given class can be used to test for object equality and objectinequality for that class.B. The hashCode method is used by thejava.util.SortedSet collection class to order the elements within that set.C. The hashCode method for a given class can be used to test for object inequality, butNOT object equality, for that class.D. The only important characteristic of the values returned by a hashCode method is that thedistribution of values must follow a Gaussian distribution.E. The hashCode method is used by the java.util.HashSet collection class to group the elementswithin that set into hash buckets for swift retrieval.Answer: C,EQUESTION NO: 47Given:1. public class Score implements Comparable<Score> {2. private int wins, losses;3. public Score(int w, int l) { wins = w; losses = l; }4. public int getWins() { return wins; }5. public int getLosses() { return losses; }6. public String toString() {7. return "<" + wins + "," + losses + ">";8. }9. // insert code here10. }Which method will complete this class?A. public int compareTo(Object o){/*more code here*/}B. public int compareTo(Score other){/*more code here*/}C. public int compare(Score s1,Score s2){/*more code here*/}D. public int compare(Object o1,Object o2){/*more code here*/}Answer: BQUESTION NO: 48Given a pre-generics implementation of a method:11. public static int sum(List list) {12. int sum = 0;13. for ( Iterator iter = list.iterator(); iter.hasNext(); ) {14. int i = ((Integer)iter.next()).intValue();15. sum += i;16. }17. return sum;18. }What three changes allow the class to be used with generics and avoid an unchecked warning?(Choose three.)A. Remove line 14.B. Replace line 14 with "int i = iter.next();".C. Replace line 13 with "for (int i : intList) {".D. Replace line 13 with "for (Iterator iter : intList) {".E. Replace the method declaration with "sum(List<int> intList)".F. Replace the method declaration with"sum(List<Integer> intList)".Answer: A,C,FQUESTION NO: 49Given:23. Object [] myObjects = {24. new Integer(12),25. new String("foo"),26. new Integer(5),27. new Boolean(true)28. };29. Arrays.sort(myObjects);30. for(int i=0; i<myObjects.length; i++) {31. System.out.print(myObjects[i].toString());32. System.out.print(" ");33. }What is the result?A. Compilation fails due to an error in line 23.B. Compilation fails due to an error in line 29.C. A ClassCastException occurs in line 29.D. A ClassCastException occurs in line 31.E. The value of all four objects prints in natural order. Answer: CQUESTION NO: 50Given a class Repetition:1. package utils;2.3. public class Repetition {4. public static String twice(String s) { return s + s; }5. }and given another class Demo:1. // insert code here2.3. public class Demo {4. public static void main(String[] args) {5. System.out.println(twice("pizza"));6. }7. }Which code should be inserted at line 1 of Demo.java to compile and run Demo to print"pizzapizza"?A. import utils.*;B. static import utils.*;C. import utils.Repetition.*;D. static import utils.Repetition.*;E. import utils.Repetition.twice();F. import static utils.Repetition.twice;G. static import utils.Repetition.twice;Answer: FQUESTION NO: 51A UNIX user named Bob wants to replace his chess program with a new one, but he is not surewhere the old one is installed. Bob is currently able to run a Java chess program starting from hishome directory /home/bob using the command:java -classpath /test:/home/bob/downloads/*.jar games.ChessBob's CLASSPATH is set (at login time) to:/usr/lib:/home/bob/classes:/opt/java/lib:/opt/java/lib/*.jar What is a possible location for the Chess.class file?A. /test/Chess.classB. /home/bob/Chess.classC. /test/games/Chess.classD. /usr/lib/games/Chess.classE. /home/bob/games/Chess.classF. inside jarfile /opt/java/lib/Games.jar (with a correct manifest)G. inside jarfile /home/bob/downloads/Games.jar (with a correct manifest)Answer: CQUESTION NO: 52Given the following directory structure:bigProject|--source| |--Utils.java||--classes|--And the following command line invocation:javac -d classes source/Utils.javaAssume the current directory is bigProject, what is the result?A. If the compile is successful, Utils.class is added to the source directory.B. The compiler returns an invalid flag error.C. If the compile is successful, Utils.class is added to the classes directory.D. If the compile is successful, Utils.class is added to the bigProject directory.Answer: CQUESTION NO: 53Given:1. package pany.application;2.3. public class MainClass {4. public static void main(String[] args) {}5. }And MainClass exists in the/apps/com/company/application directory. Assume the CLASSPATH environment variable is set to "." (current directory).Which two java commandsentered at the command line will run MainClass? (Choose two.)A. java MainClass if run from the /apps directoryB. java pany.application.MainClass if run from the /apps directoryC. java -classpath /appspany.application.MainClass if run from any directoryD. java -classpath . MainClass if run from the/apps/com/company/application directory。
scjp考题1(详尽答案)

scjp考题1(详尽答案)本文Matrix永久镜像:说明:本文可能由Matrix原创,也可能由Matrix的会员整理,或者由Matrix的Crawler在全球知名Java或者其他技术相关站点抓取并永久保留镜像,Matrix会保留所有原来的出处URL,并在显著地方作出说明,如果你发觉出处URL有误,请联系Matrix改正.好资源共享,这份考题有详尽答案,部分题目还有本人心得。
这是试题1。
1. What will happen when you attempt to compile and run the following code?(Assume that the code is compiled and run with assertions enabled.)public class AssertTest{public void methodA(int i){assert i >= 0 : methodB();System.out.println(i);}public void methodB(){ //无返回值System.out.println("The value must not be negative");}public static void main(String args[]){AssertT est test = new AssertTest();test.methodA(-10);}}A.it will print -10B.it will result in AssertionError showing the message-“the value must not be negative”.C.the code will not compile.D.None of these.C is correct. An assert statement can take any one of these two forms -assert Expression1;assert Expression1 : Expression2;Note that, in the second form; the second part of the statement must be an expression- Expression2. In this code, the methodB() returns void, which is not an expression and hence it results in a compile time error. The code will compile if methodB() returns any value such as int, String etc.Also, in both forms of the assert statement, Expression1 must have type boolean or a compile-time error occurs.2. What will happen when you attempt to compile and run the following code?public class Static{static{int x = 5; //在static内有效}static int x,y; //初始化为0public static void main(String args[]){x--; //-1myMethod();System.out.println(x + y + ++x);}public static void myMethod(){y = x++ + ++x; //y=-1+1 x=1}}piletime errorB.prints: 1C.prints: 2D.prints: 3E.prints: 7F.prints: 8D is the correct choice. The above code will not give any compilation error. Note that "Static" is a valid class name. Thus choice A is incorrect.In the above code, on execution, first the static variables (x and y) will be initialized to 0. Then static block will be called and finally main() method will be called. The execution of static block will have no effect on the output as it declares a new variable (int x).The first statement inside main (x--) will result in x to be -1. After that myMethod() will be executed. The statement "y = x++ + ++x;" will be evaluated to y = -1 + 1 and x will become 1. In case the statement be "y =++x + ++x", it would be evaluated to y = 0 + 1 and x would become 1. Finally when System.out is executed "x + y + ++x" will be evaluated to "1 + 0 + 2" which result in 3 as the output. Thus choice D is correct.3. Given the following code, what will be the output?class Value{public int i = 15;}public class Test{public static void main(String argv[]){Test t = new Test();t.first();}public void first(){int i = 5;Value v = new Value();v.i = 25;second(v, i);System.out.println(v.i);}public void second(Value v, int i){i = 0;v.i = 20;Value val = new Value();v = val;System.out.println(v.i + " " + i);}}A.15 0 20B.15 0 15C.20 0 20D.0 15 20A is correct. When we pass references in Java what actually gets passed is the value of that reference (i.e. memory address of the object being referenced and not the actual object referenced by that reference) and it gets passed as value (i.e a copy of the reference is made). Now when we make changes to the object referenced by that reference it reflects on that object even outside of the method being called but any changes made to the reference itself is not reflected on that reference outside of the method which is called. In the example above when the referencev is passed from method first() to second() the value of v is passed. When we assign the value val to v it is valid only inside the method second() and thus inside the method second() what gets printed is 15 (initial value of i in the object referenced by val), then a blank space and then 0 (value of local variable i). After this when we return to the method first() v actually refers to the same object to which it was referring before the method second() was called, but one thing should be noted here that the value of i in that object (referred by v inside the method first()) was changed to 20 in the method second() and this change does reflect even outside the method second(), hence 20 gets printed in the method first(). Thus overall output of the code in consideration is15 0204. What will happen when you attempt to compile and run the following code?class MyParent {int x, y;MyParent(int x, int y){this.x = x;this.y = y;}public int addMe(int x, int y){return this.x + x + y + this.y;}public int addMe(MyParent myPar){return addMe(myPar.x, myPar.y);}}class MyChild extends MyParent{int z;MyChild (int x, int y, int z){super(x,y);this.z = z;}public int addMe(int x, int y, int z){return this.x + x + this.y + y + this.z + z; }public int addMe(MyChild myChi){ return addMe(myChi.x, myChi.y, myChi.z); }public int addMe(int x, int y){return this.x + x + this.y + y;}}public class MySomeOne{public static void main(String args[]){ MyChild myChi = new MyChild(10, 20, 30); MyParent myPar = new MyParent(10, 20); int x = myChi.addMe(10, 20, 30);int y = myChi.addMe(myChi);int z = myPar.addMe(myPar);System.out.println(x + y + z);}}A.300B.240C.120D.180pile errorF.none of the aboveA is the correct choice. In the above code, MyChild class overrides the addMe(int x, int y) method of the MyParent class. And in both the MyChild and MyParent class, addMe() method is overloaded. There is no compilation error anywhere in the above code.On execution, first, the object of MyChild class will be constructed. Please note that there is a super() call from the constructor of MyChild class, which will call the constructor of MyParent class. This will cause the value of z variable of MyChild class to be 30 and x, y variables of MyParent class will become 10 and 20 respectively. The next statement will again call the constructor of MyParent class with same x and y values. This is followed by execution of addMe() method of MyChild class with x as 10, y as 20 and z as 30. Also x and y are inherited by MyChild class from the MyParent class. Thus in the addMe() method of the MyChild class, the value of this.x will be 10, this.y will be 20 and this.z will be 30. The return value of this method will be "10 + 10 + 20 + 20 + 30 + 30", which is equal to 120. Thus x will become 120.This is followed by the invocation of the other addMe() method which takes object reference of the MyChild class. From this method, the method which was called earlier is invoked. This call is exactly the same as the earlier one. Thus the value of y will also be 120 like x.Now the addMe() method of MyParent class is invoked. This method invokes another addMe() method of the same class. Itsequivalent to the invocation of addMe(int x, int y) method with x as 10 and y as 20. Also the value of instance variables x and y of My Parent class is 10 and 20 respectively. The value of z will be evaluated to "10 + 10 + 20 + 20", which is equal to 60. Thus the value of x, y and z after all the invocations will be 120, 120 and 60 respectively. As a result of this finally, "120 + 120 + 60" which is equal to 300 will be printed. Thus A is the correct choice.5. The class AssertionError has "is -a" relationship with these classes (choose two)A.RuntimeExceptionB.ErrorC.VirtualMachineErrorD.IllegalAccessExceptionE.ThrowableB and E are correct. The class AssertionError is an Error, which denotes an “incorrect condition” as opposed to an“unusual condition” (Exception). Since, the class Error descends from Throwable, AssertionError also has “is-a” relationship with Throwable. Here is the hierarchy –ng.Object|+ng.Throwable|+ng.Error Exception| |+ng.AssertionError +RuntimeException IOExceptionWant to know more?You can find more information about this as an answer to the question - “Why is AssertionError a subclass of Error rather thanRuntimeException?” at - /j2se/1.4/docs/guide/lang/assert.html #design-faq-error6. What will be the result of executing the following code?1. boolean a = true;2. boolean b = false;3. boolean c = true;4. if (a == true)5. if (b == true)6. if (c == true) System.out.println("Some things are true in this world");7. else System.out.println("Nothing is true in this world!");8. else if (a && (b = c)) //这里是赋值,不是比较System.out.println("It‘s too confusing to tell what is true and what is false");9. else System.out.println("Hey this won‘t compile");A.The code won’t compile.B.“some things are true in this world” will be printedC.“hey this won’t compile” will be printedD.None of theseD is correct. This is a very good question to test the concepts of execution flow in case of if conditions. The rule for attaching else statements with if conditions is the same as attaching close brackets with open brackets. A close bracket attaches with the closest open bracket, which is not already closed. Similarly an else statement attaches with the closest if statement, which doesn‘t have an else statement already, attached to it. So the else statement at line 7 attaches to the if statement at line 6. The else statement at line 8 attaches to the if statement at line 5. The else statement at line 9 attaches to the if statement at line 8.Now let‘s look at the execution. At line 4 since a is equal to true the execution falls to line 5. At line 5 since b is not true the execution goes to the corresponding else statement at line 8. Now it evaluates the condition inside the if statement. Please note here that an assignment statement also has a value equal to the value being assigned, hence (b = c) evaluates to true and subsequently a && (b = c) ev aluates to true and "It‘s too confusing to tell what is true and what is false" will be printed. Hence the correct answer is choice D.7. What will happen when you attempt to compile and run the following code?interface MyInterface{}public class MyInstanceTest implements MyInterface{static String s;public static void main(String args[]){MyInstanceT est t = new MyInstanceTest();if(t instanceof MyInterface){System.out.println("I am true interface");}else {System.out.println("I am false interface");}if(s instanceof String){System.out.println("I am true String");}else {System.out.println("I am false String");}}}pile time errorB.runtime errorC.prints: “I am true interface” followed by “I am true String”D.prints: “I am false interface” followed by “I am false String”E.prints: “I am true interface” followed by “I am false String”F.prints: “I am false interface” followed by “I am true String”E is the correct choice. The "instanceof" operator tests the class of an object at runtime. It returns true if the class of the left-hand argument is the same as, or is some subclass of, the class specified by the right-hand operand. The right-hand operand may equally well be an interface. In such a case, the test determines if the object at left-hand argument implements the specified interface.In the above case there will not be any compiletime or runtime error. The result of "t instance of MyInterface" will be true as "t" is the object of MyInstanceTest class which implements the MyInstance interface. But the result of "s instanceof String" will be false as "s" refers to null. Thus the output of the above program will be : "I am true interface" followed by " I am false String". Thus choice E is correct and others are incorrect.8. What results from attempting to compile and run the following code?public class Ternary{public static void main(String args[]){int a = 5;System.out.println("Value is - " + ((a < 5) ? 9.0 : 9));}}A.print:Value is -9B.print:Value is -5pilation errorD.None of theseD is correct. The code compiles successfully. In this code the optional value for the ternary operator, 9.0(a double) and 9(an int) are of different types. The result of a ternary operator must be determined at the compile time, and here the type chosen using the rules of promotion for binary operands, is double. Since the result is a double, the output value is printed in a floating point format. The choice of which value to be printed is made on the basis of the result of the comparison "a < 5" which results in false, hence the variable "a" takes the second of the two possible values, which is 9, but because the result type is promoted to double, the output value is actually written as 9.0, rather than the more obvious 9, hence D is correct.9. In the following pieces of code, A and D will compile without any error. True/False?A: StringBuffer sb1 = "abcd";B: Boolean b = new Boolean("abcd");C: byte b = 255;D: int x = 0x1234;E: float fl = 1.2;TrueFalseThe code segments B and D will compile without any error.A is not a valid way to construct a StringBuffer, you need to creata StringBuffer object using "new". B is a valid construction of a Boolean (any string other than "true" or "false" to the Boolean constructor will result in a Boolean with a value of "false"). C will fail to compile because the valid range for a byte is -128 to +127 (ie, 8 bits,signed). D is correct, 0x1234 is the hexadecimal representation in java. E fails to compile because the compiler interprets 1.2 as a double being assigned to a float (down-casting), which is not valid. You either need an explicit cast (as in "(float)1.2") or "1.2f", to indicate a float.10. Considering the following code, Which variables may be referenced correctly at line 12?1.public class Outer2.{3.public int a = 1;4.private int b = 2;5.public void method(final int c)6.{7.int d = 3;8.class Inner9.{10.private void iMethod(int e)11. {12.13.}14.}15.}16.}a b c d eA, B, C and E are correct. Since Inner is not a static inner class,it has a reference to an enclosing object, and all the variables of that object are accessible. Therefore A and B are correct, even if b is private. Variables in the enclosing method are only accessible when they are marked as final hence c is accessible but not d. E is obviously correct as it is a parameter to the method containing line 12 itself.11. What will be the result of executing the following code?public static void main(String args[]){char digit = ‘a‘;for (int i = 0; i < 10; i++){switch (digit){case ‘x‘ :{int j = 0;System.out.println(j);}default :{int j = 100;System.out.println(j);}}}int i = j;System.out.println(i);}A.100 will be printed 11 times.B.100 will be printed 10 times and then there will be a runtime exceptionC.The code will not compile because the variable i cannot be declared twice within the mani() method.D.The code will not compile because the variable j cannot be declared twice within the switch statement.E.None of these.E is correct. The code will not compile. There is no problem with the declaration of another variable i as both the variables are in disjoint blocks (first one is inside the for loop and its scope ends with the for loop, whereas the second is outside the for loop) and, therefore, different scopes and hence valid. The problem is with the variable j. The two declarations of the variable j are perfectly valid as they are in disjoint blocks and, therefore, different scopes. The error is that both the declarations of j are not available outside the case or default statement, whereas we are trying to assign it to the variable i. Therefore the compiler objects and reports variable j not found.12. Which of the following collection classes from java.util package are Thread safe?A.VectorB.ArrayList //与Vector类似,只是不同步C.HashMapD.HashtableA and D are correct. Vector and Hashtable are two collection classes that are inherently thread safe or synchronized; whereas, the classes ArrayList and HashMap are unsynchronized and must be "wrapped" via Collections.SynchronizedList or Collections.synchronizedMap if synchronization is desired.13. What will happen when you attempt to compile and run the following code?class MyThread extends Thread{public void run(){System.out.println("MyThread: run()");}public void start(){System.out.println("MyThread: start()");}}class MyRunnable implements Runnable{public void run(){System.out.println("MyRunnable: run()");}public void start(){System.out.println("MyRunnable: start()");}}public class MyTest {public static void main(String args[]){MyThread myThread = new MyThread();MyRunnable myRunnable = new MyRunnable();Thread thread = new Thread(myRunnable); myThread.start();thread.start();}}A.prints: MyThread: start() followed by MyRunnable: run()B.prints: MyThread: run() followed by MyRunnable: start()C.prints: MyThread: start() followed by MyRunnable: start()D.prints: MyThread: run() followed by MyRunnable: run()pile time errorF.None of the aboveA is the correct choice. In the above code there is not anycompilation error. Thus choice E is incorrect. Inside main() method, objects of MyThread and MyRunnable class are created followed by creation of Thread with object of MyRunnable class.Note that MyThread class extends Thread class and overrides the start() method of the Thread class. Thus on execution of "myThread.start()" statement, the start() method of the MyThread class will be executed and as a result "MyThread:start()" will be printed. Had the start() method not there in MyThread class, the start() method of the Thread class would be called which in turn would call the run() method of the MyThread class.On execution of "thread.start();", the start() method of the Thread class would be called which in turn will call the run() method of the class which is passed to Thread constructor (i.e. MyRunnable class). Thus "MyRunnable:run()" will be printed out. Thus choice A is correct.14. What will be the result of executing the following code?// Filename; SuperclassX.javapackage packageX;public class SuperclassX{protected void superclassMethodX(){}int superclassVarX;}// Filename SubclassY.java1.package packageX.packageY;2.3.public class SubclassY extends SuperclassX4.{5.SuperclassX objX = new SubclassY();6.SubclassY objY = new SubclassY();7.void subclassMethodY()8.{9.objY.superclassMethodX();10.int i;11.i = objY.superclassVarX;12.}13.}pile error at line 5.pile error at line 9.C.Runtime exception at line 11.D.None of theseD is correct. When no access modifier is specified for a member, it is only accessible by another class in the package where its class is defined. Even if its class is visible in another package, the member is not accessible there. In the question above the variable superclassVarX has no access modifier specified and hence it cannot be accessed in the packageY even though the class SuperclassX is visible and the protected method superclassMethodX() can be accessed. Thus the compiler will raise an error at line 11.15. Consider the class hierarchy shown below:FourWheeler(implements DrivingUtilities)/ / \ \/ / \ \/ / \ \/ / \ \/ / \ \Car Truck Bus CraneConsider the following code below:1.DrivingUtilities du;2.FourWheeler fw;3.Truck myTruck = new Truck();4.du = (DrivingUtilities)myTruck;5.fw = new Crane();6.fw = du;Which of the statements below are true?A.Line 4 will not compile because an interface cannot refer to an object.B.The code will compile and run.C.The code will not compile without an explicit cast at line 6, because going down the hierarchy without casting is not allowed.D.The code at line 4 will compile even without the explicit cast.E.The code will compile if we put an explicit cast at line 6 but will throw an exception at runtime.C andD are correct. A and B are obviously wrong because there is nothing wrong in an interface referring to an object. C is correct because an explicit cast is needed to go down the hierarchy. D is correct because no explicit cast is needed at line 4, because we are going up the hierarchy.E is incorrect because if we put an explicit cast at line 6, the code will compile and run perfectly fine, no exception will be thrown because the runtime class of du (that is Truck) can be converted to type FourWheeler without any problem.16. What results from the following code?1.class MyClass2.{3.void myMethod(int i) {System.out.println("int version");}4.void myMethod(String s) {System.out.println("String version");}5.public static void main(String args[])6.{7.MyClass obj = new MyClass();8.char ch = ‘c‘;9.obj.myMethod(ch);10.}11.}A.Line 4 will not compile as void method can’t e overridden.B.An exception at line 9.C.Line 9 will not compile as there is no version of myMethod which takes a char as argument.D.The code compiles and produces output: int versionE.The code compiles and produces output: String versionD is correct. A is incorrect as void methods can be overridden without any problem. B is incorrect as char ch declaration is valid.C is incorrect as char type in java is internally stored as integer and there is a method which takes int as an input.D is correct, on line 9 char ch is widened to an int and passed to int version of the myMethod().E is incorrect as int version of myMethod() is called.17. What is the result when you compile and run the following code?public class ThrowsDemo {static void throwMethod() {System.out.println("Inside throwMethod.");throw new IllegalAccessException("demo");}public static void main(String args[]) {try {throwMethod();} catch (IllegalAccessException e) {System.out.println("Caught " + e);}}}pile errorB.runtime errorpile successfully, nothing is printed.D.inside throwMethod followed by caught: ng.IllegalAccessException: demoA is correct. Exception :ng.IllegalAccessExcption must be caught or placed in the throws clause of the throwMethod(), i.e. the declaration of throwMethod() be changed to "static void throwMethod() throws IllegalAccessExcption". Thus compilation error will occur.18. What will be printed when you execute the following code?class X {Y b = new Y();X() {System.out.print("X");}}class Y {Y() {System.out.print("Y");}}public class Z extends X {Y y = new Y();Z() {System.out.print("Z");}public static void main(String[] args) {new Z();}}A.ZB.YZC.XYZD.YXYZD is correct. A difficult but a fundamental question, please observe carefully. Before any object is constructed the object of the parent class is constructed(as there is a default call to the parent‘s constructor from the constructor of the child class via the super() statement). Also note that when an object is constructed the variables are initialized first and then the constructor is executed. So when new Z() is executed , the object of class X will be constructed, which means Y b = new Y() will be executed and "Y" will be printed as a result. After that constructor of X will be called which implies "X" will be printed. Now the object of Z will be constructed and thus Y y = new Y() will beexecuted and Y will be printed and finally the constructor Z() will be called and thus "Z" will be printed. Thus YXYZ will be printed.19. What will happen when you attempt to compile and run the following code snippet?Boolean b = new Boolean("TRUE"); //不区分大小写if(b.booleanValue()){System.out.println("Yes : " + b);}else{System.out.println("No : " + b);}A.The code will not compile.B.It will print – Yes: trueC.It will print – Yes: TRUED.It will print – No: falseE.It will print – No: FALSEB is the correct choice. The wrapper class Boolean has the following constructor -public Boolean(String s) It allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string "true". Otherwise, allocate a Boolean object representing the value false.E.g.new Boolean("TRUE") produces a Boolean object that represents true.new Boolean("anything") produces a Boolean object that represents false.The internal toString() representation of this object produces the boolean value string in lower case, hence it prints "Yes : true" instead of "Yes : TRUE".20. What is the result when you compile and run the following code?public class Test{public void method(){for(int i = 0; i < 3; i++) {System.out.print(i);}System.out.print(i);}}A. 0122B. 0123C. compile errorD. none of theseC is correct. The code on compilation will give compile time error because the scope of variable i is only within "for" loop.21. What will happen when you attempt to compile and run the following code?int Output = 10;boolean b1 = false;if((b1 == true) && ((Output += 10) == 20)){System.out.println("We are equal " + Output);}else{System.out.println("Not equal! " + Output);}pile errorpile and output of “we are equal 10”pile and output of “not equal!20”pile and output of “not equal!10”D is correct, according to short logic operator rule22. What will be the result of executing the following code?Given that Test1 is a class.1. Test1[] t1 = new Test1[10];2. Test1[][] t2 = new Test1[5][];3. if (t1[0] == null)4. {5.t2[0] = new Test1[10] ;6.t2[1] = new Test1[10];7.t2[2] = new Test1[10];8.t2[3] = new Test1[10];9.t2[4] = new Test1[10];10. }11. System.out.println(t1[0]);12. System.out.println(t2[1][0]);A. The code will not compile because the array t2 is not initialized in an unconditional statement before use.B. The code will compile but a runtime exception will be thrown at line 12.C. The code will compile but a runtime exception will be thrown at line 11.D. None of theseD is correct. Though we cannot use local variables without initializing them (compilation error), there is an exception to it. In case of arrays initialization is supposed to be complete when we specify the leftmost dimension of the array. The problem occurs at runtime if we try to access an element of the array which has not been initialized (specification of size). In the question above the array t2 is initialized before use, therefore there will be no。
SUN公司SCJP题库讲解学习

S U N公司S C J P题库yModule 1-JAVA 基础一、选择题:Question 1Given:35. String #name = "Jane Doe";36. int $age=24;37. Double _height = 123.5;38. double ~temp = 37.5;Which two are true? (Choose two.)A. Line 35 will not compile.B. Line 36 will not compile.C. Line 37 will not compile.D. Line 38 will not compile.Answer: AD 标识符以字母,下划线,或者$开始Question 2Given:11. public class Test {12. public static void main(String [] args) {13. int x =5;14. boolean b1 = true;15. boolean b2 = false;16.17.if((x==4) && !b2)18. System.out.print("l ");19. System.out.print("2 ");20. if ((b2 = true) && b1)21. System.out.print("3");22. }23. }What is the result?A. 2B. 3C. 1 2D. 2 3E. 1 2 3F. Compilation fails.G. An exceptional is thrown at runtime. Answer: D 注意20行,=为赋值,不要被骗Question 3Given:42. public class ClassA {43. public int getValue() {44. int value=0;45. boolean setting = true;46. String title="Hello";47. if (value || (setting && title == "Hello")) { return 1; }48. if (value == 1 & title.equals("Hello")) { return 2; }49. }50. }And:70. ClassA a = new ClassA();71. a.getValue();What is the result?A. 1B. 2C. Compilation fails.D. The code runs with no output.E. An exception is thrown at runtime.Answer: C 编译不通过,47行value为int类型不是boolean Question 4Given:11. public void testIfA() {12. if(testIfB("True")) {13. System.out.println("True");14. } else {15. System.out.println("Not true");16. }17. }18. public Boolean testIfB(String str) {19. return Boolean.valueOf(str);20. }What is the result when method testIfA is invoked?A. TrueB. Not trueC. An exception is thrown at runtime.D. Compilation fails because of an error at line 12.E. Compilation fails because of an error at line 19. Answer: A 19行,如果str为true则返回ture,否则返回false Question 5Given:11. public static void main(String[] args) {12. Integer i = new Integer(1) + new Integer(2);13. switch(i) {14. case 3: System.out.println("three"); break;15. default: System.out.println("other"); break;16. }17. }What is the result?A. threeB. otherC. An exception is thrown at runtime.D. Compilation fails because of an error on line 12.E. Compilation fails because of an error on line 13.F. Compilation fails because of an error on line 15. Answer: A 就是两个Integer类型相加Question 6Given:11. public static void main(String[] args) {12. String str = "null";13. if (str == null) {14. System.out.println("null");15. } else (str.length() == 0) {16. System.out.println("zero");17. } else {18. System.out.println("some");19. }20. }‘What is the result?A. nullB. zeroC. someD. Compilation fails.E. An exception is thrown at runtime.Answer: D 这题真恶心 15行少个ifQuestion 7Given:10.int x=0;11.int y=10;12. do {l3. y--;14. ++x;15. } while (x < 5);16. System.out.print(x + "," + y);What is the result?A. 5,6B. 5,5C. 6,5D. 6,6Answer: B (91,82,73,64,55)没啥争议Question 8Given:25.int x=12;26. while (x < 10) {27. x--;28. }29. System.out.print(x);What is the result?A. 0B. 10C. 12D. Line 29 will never be reached.Answer: C 12>10,所以直接跳出循环,输出x=12 Question 9Given:35. int x= 10;36. do {37. x--;38. } while(x< 10);How many times will line 37 be executed?A. ten timesB. zero timesC. one to me timesD. more than ten timesAnswer: D 死循环Question 10Given:11. public static void main(String[] args) {12. for (int i=0;i<= 10;i++){13. if( i>6) break;14. }15. System.out.println(i);16. }What is the result?A. 6B. 7C. 10D. 11E. Compilation fails.F. An exception is thrown at runtime. Answer: E 15行i超出了作用域Question 11Given:55. int []x= {1, 2,3,4, 5};56. int y[] =x;57. System.out.println(y[2]);Which is true?A. Line 57 will print the value 2.B. Line 57 will print the value 3.C. Compilation will fail because of an error in line 55.D. Compilation will fail because of an error in line 56. Answer: B 没争议,考察数组下标是从0开始Question 12Which two code fragments(片段) correctly(正确) create and initialize a static array of int elements? (Choose two.)A. static final int[] a = { 100,200 };B. static final int[] a;static { a=new int[2]; a[0]=100; a[1]=200; }C. static final int[] a = new int[2] { 100,200 };D. static final int[] a;static void init() { a = new int[3]; a[0]=100; a[1]=200; } Answer: AB c不能指定长度,d不能在init方法中赋值,要么在static 代码块中Question 13Given:11. public static void main(String[] args) {12. Object obj = new int[] { 1,2,3 };13. int[] someArray = (int[])obj;14. for (int i: someArray) System.out.print(i +" ")15. }‘What is the result?A. 1 2 3B. Compilation fails because of an error in line 12.C. Compilation fails because of an error in line 13.D. Compilation fails because of an error in line 14.E. A ClassCastException is thrown at runtime.Answer: A 没争议,foeach循环遍历数组Question 14Given:11. String[] elements = { "for", "tea", "too" };12. String first = (elements.length > 0)? elements[0] : null;What is the result?A. Compilation fails.B. An exception is thrown at runtime.C. The variable first is set to null.D. The variable first is set to elements[0].Answer: DQuestion 15Given:10. public class Bar {11.static void foo(int...x) {12. // insert code here13. }14. }Which two code fragments, inserted independently(独立的) at line 12, will allow the class to compile? (Choose two.)A. foreach(x) System.out.println(z);B. for(int z : x) System.out.println(z);C. while( x.hasNext()) System.out.println( x.next());D. for( int i=0; i< x.length; i++ )System.out.println(x[i]);Answer: BD x相当于一个数组,a明显错没有foreach,c中x没有hadNext方法Question 16A programmer(程序员) needs to create a logging method that can accept(接受) an arbitrary(随意任意) number of arguments. For example, it may be called in theseways:logIt("log message 1 ");logIt("log message2”,”log message3");logIt("log message4", "log message5", "log message6");Which declaration(说明) satisfies(符合) this requirement(需求)?A. public void logIt(String * msgs)B. public void logIt(String [] msgs)C. public void logIt(String... msgs)D. public void logIt(String msg1, String msg2, String msg3) Answer: C 可变长参数Question 171. public class A {2. public String doit(int x, int y) {3. return "a";4. }5.6. public String doit(int... vals) {7. return "b";8. }9. }Given:25. A a=new A();26. System.out.println(a.doit(4, 5));What is the result?A. Line 26 prints "a" to System.out.B. Line 26 prints "b" to System.out.C. An exception is thrown at line 26 at runtime.D. Compilation of class A will fail due to an error in line6.Answer: A 确定参数和可变长参数同时存在的时候,优先考虑确定参数的Question 18Given a file GrizzlyBear.java:1. package animals.mammals;2.3. public class GrizzlyBear extends Bear {4. void hunt() {5. Salmon s = findSalmon();6. s.consume();7. }8. }and another file, Salmon.java:1. package animals.fish;2.3. public class Salmon extends Fish {4. void consume() { /* do stuff */ }5. }Assume(假定) both classes are defined in the correct directories for theft packages, and that the Mammal class correctly defines the findSalmon() method. Which two changes allow this code to compile correctly? (Choose two.)A. add public to the start of line 4 in Salmon.javaB. add public to the start of line 4 in GrizzlyBear.javaC. add import animals.mammals.*; at line 2 in Salmon.javaD. add import animals.fish.*; at line 2 in GrizzlyBear.javaE. add import animals.fish.Salmon.*; at line 2 in GrizzlyBear.javaF. add import animals.mammals.GrizzlyBear.*;at line 2 in Salmon.javaAnswer: AD 调用不同包下的类,要先导入,方法权限要设置成public Question 19Given:10. package com.sun.scjp;11. public class Geodetics {12. public static final double DIAMETER = 12756.32; // kilometers13. }Which two correctly access(访问) the DIAMETER member of the Geodetics class? (Choose two.)A. import com.sun.scjp.Geodetics;public class TerraCarta {public double halfway(){ return Geodetics.DIAMETER/2.0; } }B. import static com.sun.scjp.Geodetics;public class TerraCarta {public double halfway() { return DIAMETER/2.0; } }C. import static com.sun.scjp.Geodetics. *;public class TerraCarta {public double halfway() { return DIAMETER/2.0; } }D. package com.sun.scjp;public class TerraCarta {public double halfway() { return DIAMETER/2.0; } }Answer: AC b中不能静态导入类,c中静态导入类属性,正确,d访问错误很明显Question 20Given classes defined in two different files:1. package util;2. public class BitUtils {3. private static void process(byte[] b) { }4. }1. package app;2. public class SomeApp {3. public static void main(String[] args) {4. byte[] bytes = new byte[256];5. // insert code here6. }7. }What is required(必需的) at line 5 in class SomeApp to use the process methodof BitUtils?A. process(bytes);B. BitUtils.process(bytes);C. app.BitUtils.process(bytes);D. util.BitUtils.process(bytes);E. import util.BitUtils. *; process(bytes);F. SomeApp cannot use the process method in BitUtils. Answer: F 私有的,不能被访问Question 21Given a class Repetition(重复):1. package utils;2.3. public class Repetition {4. public static String twice(String s) { return s + s; }5. }and given another class Demo:1. // insert code here2.3. public class Demo {4. public static void main(String[] args) {5. System.out.println(twice("pizza"));6. }7. }Which code should be inserted at line 1 of Demo.java to compile and run Demo to print “pizzapizza”?A. import utils.*;B. static import utils.*;C. import utils.Repetition.*;D. static import utils.Repetition. *;E. import utils.Repetition.twice();F. import static utils.Repetition.twice;G. static import utils.Repetition.twice;Answer: F 静态导入Question 22Given:1. package test;2.3. class Target(目标) {4. public String name = "hello";5. }What can directly(直接的) access and change the value ofthe variable(变量) name?A. any classB. only the Target classC. any class in the test packageD. any class that extends TargetAnswer: C default类型的类本包访问权限Question 23Given:11. rbo = new ReallyBigObject();12. // more code here13. rbo = null;14. /* insert code here */Which statement(语句) should be placed at line 14 tosuggest(促成) that the virtual machine(虚拟机) expend(消耗) effort(努力) toward recycling(回收) the memory used by the object rbo?A. System.gc();B. Runtime.gc();C. System.freeMemory();D. Runtime.getRuntime().growHeap();E. Runtime.getRuntime().freeMemory();Answer: A 题很简单。
SCJP考试真题和解析-Read

SCJP考试真题和解析Choose the three valid identifiers from those listed below.A. IDoLikeTheLongNameClassB. $byteC. constD. _okE. 3_case解答:A, B, D点评:Java中的标示符必须是字母、美元符($)或下划线(_)开头。
关键字与保留字不能作为标示符。
选项C中的const是Java的保留字,所以不能作标示符。
选项E中的3_case以数字开头,违反了Java的规则。
例题2:How can you force garbage collection of an object?A. Garbage collection cannot be forcedB. Call System.gc().C. Call System.gc(), passing in a reference to the object to be garbage collected.D. Call Runtime.gc().E. Set all references to the object to new values(null, for example).解答:A点评:在Java中垃圾收集是不能被强迫立即执行的。
调用System.gc()或Runtime.gc()静态方法不能保证垃圾收集器的立即执行,因为,也许存在着更高优先级的线程。
所以选项B、D不正确。
选项C的错误在于,System.gc()方法是不接受参数的。
选项E中的方法可以使对象在下次垃圾收集器运行时被收集。
例题3:Consider the following class:1. class Test(int i) {2. void test(int i) {3. System.out.println(“I am an int.”);4. }5. void test(String s) {6. System.out.println(“I am a string.”);7. }8.9. public static void main(String args[]) {10. Test t=new Test();11. char ch=“y”;12. t.test(ch);13. }14. }Which of the statements below is true?(Choose one.)A. Line 5 will not compile, because void methods cannot be overridden.B. Line 12 will not compile, because there is no version of test() that rakes a char argument.C. The code will compile but will throw an exception at line 12.D. The code will compile and produce the following output: I am an int.E. The code will compile and produce the following output: I am a String.解答:D点评:在第12行,16位长的char型变量ch在编译时会自动转化为一个32位长的int型,并在运行时传给void test(int i)方法。
SCJP题库 Module7

Module 7-集合和泛型一、选择题:Question 1Given:11. public class Person {12. private name;13. public Person(String name) {14. = name;15. }16. public int hashCode() {17. return 420;18. }19. }Which is true?A. The time to find the value from HashMap with a Person key dependson the size of the map.B. Deleting a Person key from a HashMap will delete all map entries forall keys of type Person.C. Inserting a second Person object into a HashSet will cause the firstPerson object to be removed as a duplicate.D. The time to determine whether a Person object is contained in aHashSet is constant and does NOT depend on the size of the map. Answer: AQuestion 2Given:11. public static Collection get() {12. Collection sorted = new LinkedList();13. sorted.add("B"); sorted.add("C"); sorted.add("A");14. return sorted;15. }16. public static void main(String[] args) {17. for (Object obj: get()) {18. System.out.print(obj + ", ");19. }20. }What is the result?A. A, B, C,B. B, C, A,C. Compilation fails.D. The code runs with no output.E. An exception is thrown at runtime.Answer: BQuestion 3Given:1. import java.util.*;2. public class Example {3. public static void main(String[] args) {4. // insert code here5. set.add(new integer(2));6. set.add(new integer(l));7. System.out.println(set);8. }9. }Which code, inserted at line 4, guarantees that this program willoutput [1, 2]?A. Set set = new TreeSet();B. Set set = new HashSet();C. Set set = new SortedSet();D. List set = new SortedList();E. Set set = new LinkedHashSet();Answer: AQuestion 4Given:1. import java.util.*;2. public class PQ {3. public static void main(String[] args) {4. PriorityQueue<String> pq = new PriorityQueue<String>();5. pq.add("carrot");6. pq.add("apple");7. pq.add("banana");8. System.out.println(pq.poll() +":" + pq.peek());9. }10. }What is the result?A. apple:appleB. carrot:appleC. apple:bananaD. banana:appleE. carrot:carrotF. carrot:bananaAnswer: CQuestion 5Given:1. import java.util.*;2. public class WrappedString {3. private String s;4. public WrappedString(String s) { this.s = s; }5. public static void main(String[] args) {6. HashSet<Object> hs = new HashSet<Object>();7. WrappedString ws1 = new WrappedString("aardvark");8. WrappedString ws2 = new WrappedString("aardvark");9. String s1 = new String("aardvark");10. String s2 = new String("aardvark");11. hs.add(ws1); hs.add(ws2); hs.add(s1); hs.add(s2);12. System.out.println(hs.size()); } }What is the result?A. 0B. 1C. 2D. 3E. 4F. Compilation fails.G. An exception is thrown at runtime.Answer: DQuestion 6Click the Exhibit button.1. import java.util.*;2. public class TestSet {3. enum Example { ONE, TWO, THREE }4. public static void main(String[] args) {5. Collection coll = new ArrayList();6. coll.add(Example.THREE);7. coll.add(Example.THREE);8. coll.add(Example.THREE);9. coll.add(Example.TWO);10. coll.add(Example.TWO);11. coll.add(Example.ONE);12. Set set = new HashSet(coll);13. }14. }Which statement is true about the set variable on line 12? A. The set variable contains all six elements from the coll collection,and the order is guaranteed to be preserved.B. The set variable contains only three elements from the coll collection, and the order is guaranteed to be preserved.C. The set variable contains all six elements from the coil collection,but the order is NOT guaranteed to be preserved.D. The set variable contains only three elements from the coil collection, but the order is NOT guaranteed to be preserved. Answer: DA programmer has an algorithm that requires a java.util.List thatprovides an efficient implementation of add(0,object), but does NOT need to support quick random access. What supports these requirements?A. java.util.QueueB. java.util.ArrayListC. java.util.LinearListD. java.util.LinkedListAnswer: DQuestion 8Click the Exhibit button.1. import java.util.*;2. class KeyMaster {3. public int i;4. public KeyMaster(int i) { this.i = i; }5. public boolean equals(Object o) { return i == ((KeyMaster)o).i; }6. public int hashCode() { return i; }7. }8. public class MapIt {9. public static void main(String[] args) {10. Set<KeyMaster> set = new HashSet<KeyMaster>();11. KeyMaster k1 = new KeyMaster(1);12. KeyMaster k2 = new KeyMaster(2);13. set.add(k1); set.add(k1);14. set.add(k2); set.add(k2);15. System.out.print(set.size() + ":");16. k2.i = 1;17. System.out.print(set.size() + ":");18. set.remove(k1);19. System.out.print(set.size() + ":");20. set.remove(k2);21. System.out.print(set.size());22. }23. }What is the result?A. 4:4:2:2B. 4:4:3:2C. 2:2:1:0D. 2:2:0:0E. 2:1:0:0F. 2:2:1:1G. 4:3:2:1Answer: FGiven:11. public static void append(List list) { list.add("0042"); }12. public static void main(String[] args) {13. List<Integer> intList = new ArrayList<Integer>();14. append(intList);15. System.out.println(intList.get(0));16. }‘What is the result?A. 42B. 0042C. An exception is thrown at runtime.D. Compilation fails because of an error in line 13.E. Compilation fails because of an error in line 14. Answer: BQuestion 10Given:int[] myArray=newint[] {1, 2,3,4, 5};What allows you to create a list from this array?A. List myList = myArray.asList();B. List myList = Arrays.asList(myArray);C. List myList = new ArrayList(myArray);D. List myList = Collections.fromArray(myArray);Answer: BQuestion 11Given:34. HashMap props = new HashMap();35. props.put("key45", "some value");36. props.put("key12", "some other value");37. props.put("key39", "yet another value");38. Set s = props.keySet();39. // insert code hereWhat, inserted at line 39, will sort the keys in the props HashMap?A. Arrays.sort(s);B. s = new TreeSet(s);C. Collections.sort(s);D. s = new SortedSet(s);Answer: BQuestion 12Given:11. public class Person {12. private String name, comment;13. private int age;14. public Person(String n, int a, String c) {15. name = n; age = a; comment = c;17. public boolean equals(Object o) {18. if(! (o instanceof Person)) return false;19, Person p = (Person)o;20. return age == p.age && name.equals();21. }22. }What is the appropriate definition of the hashCode method in classPerson?A. return super.hashCode();B. return name.hashCode() + age * 7;C. return name.hashCode() + comment.hashCode() /2;D. return name.hashCode() + comment.hashCode() / 2 - age * 3; Answer: BQuestion 13Given:11. public class Key {12. private long id1;13. private long 1d2;14.15. // class Key methods16. }A programmer is developing a class Key, that will be used as a key ina standard java.util.HashMap. Which two methods should be overridden to assure that Key works correctly as a key? (Choose two.)A. public int hashCode()B. public boolean equals(Key k)C. public int compareTo(Object o)D. public boolean equals(Object o)E. public boolean compareTo(Key k)Answer: ADQuestion 14Given:11. public class Person {12. private name;13. public Person(String name) {14. = name;15. }16. public boolean equals(Object o) {17. if( !o instanceof Person ) return false;18. Person p = (Person) o;19. return .equals();20. }Which is true?A. Compilation fails because the hashCode method is not overridden.B. A HashSet could contain multiple Person objects with the same name.C. All Person objects will have the same hash code because the hashCode method is not overridden.D. If a HashSet contains more than one Person object with name="Fred", then removing another Person, also with name="Fred",will remove them all.Answer: BQuestion 15Given:1. public class Person {2. private String name;3. public Person(String name) { = name; }4. public boolean equals(Person p) {5. return .equals();6. }7. }Which is true?A. The equals method does NOT properly override the Object.equals method.B. Compilation fails because the private attribute cannot beaccessed in line 5.C. To work correctly with hash-based data structures, this class mustalso implement the hashCode method.D. When adding Person objects to a java.util.Set collection, the equalsmethod in line 4 will prevent duplicates.Answer: AQuestion 16Which two statements are true about the hashCode method? (Choose two.)A. The hashCode method for a given class can be used to test forobject equality and object inequality for that class.B. The hashCode method is used by the java.util.SortedSet collectionclass to order the elements within that set.C. The hashCode method for a given class can be used to test forobject inequality, but NOT object equality, for that class.D. The only important characteristic of the values returned by ahashCode method is that the distribution of values must follow aGaussian distribution.E. The hashCode method is used by the java.util.HashSet collectionclass to group the elements within that set into hash buckets forswift retrieval.Answer: CEQuestion 17Given:enum Example { ONE, TWO, THREE }Which is true?A. The expressions (ONE == ONE) and ONE.equals(ONE) are both guaranteed to be true.B. The expression (ONE < TWO) is guaranteed to be true and pareTo(TWO) is guaranteed to be less than one.C. The Example values cannot be used in a raw java.util.HashMap; instead, the programmer must use a java.util.EnumMap.D. The Example values can be used in a java.util.SortedSet, but theset will NOT be sorted because enumerated types do NOT implement parable.Answer: AQuestion 18Given:1. public class Score implements Comparable<Score> {2. private int wins, losses;3. public Score(int w, int 1) { wins = w; losses = 1; }4. public int getWins() { return wins; }5. public int getLosses() { return losses; }6. public String toString() {7. return "<" + wins + "," + losses + ">";8. }9. // insert code here10. }Which method will complete this class?A. public int compareTo(Object o) {/*mode code here*/}B. public int compareTo(Score other) {/*more code here*/}C. public int compare(Score s1,Score s2){/*more code here*/}D. public int compare(Object o1,Object o2){/*more code here*/} Answer: BQuestion 19Given:1. public class Test {2. public <T extends Comparable> T findLarger(T x, T y) {3. if(pareTo(y) > 0) {4. return x;5. } else {6. return y;7. }8. }9. }and:22. Test t = new Test();23. // insert code hereWhich two will compile without errors when inserted at line 23? (Choose two.)A. Object x = t.findLarger(123, "456");B. int x = t.findLarger(123, new Double(456));C. int x = t.findLarger(123, new Integer(456));D. int x = (int) t.findLarger(new Double(123), new Double(456)); Answer: ACQuestion 20Given:1. public class Drink implements Comparable {2. public String name;3. public int compareTo(Object o) {4. return 0;5. }6. }and:20. Drink one = new Drink();21. Drink two = new Drink();22. = "Coffee";23. = "Tea";23. TreeSet set = new TreeSet();24. set.add(one);25. set.add(two);A programmer iterates over the TreeSet and prints the name of eachDrink object.What is the result?A. TeaB. CoffeeC. CoffeeTeaD. Compilation fails.E. The code runs with no output.F. An exception is thrown at runtime.Answer: BQuestion 21Given:11. List list = // more code here12. Collections.sort(list, new MyComparator());Which code will sort this list in the opposite order of the sort in line12?A. Collections.reverseSort(list, new MyComparator());B. Collections.sort(list, new MyComparator());list.reverse();C. Collections.sort(list, new InverseComparator(new MyComparator()));D. Collections.sort(list, Collections.reverseOrder(new MyComparator()));Answer: DQuestion 22Given:13. public static void search(List<String> list) {14. list.clear();15. list.add("b");16. list.add("a");17. list.add("c");18. System.out.println(Collections.binarySearch(list, "a"));19. }What is the result of calling search with a valid List implementation?A. 0B. 1C. 2D. aE. bF. cG. The result is undefined.Answer: GQuestion 23Given:1. import java.util.*;2.3. public class LetterASort {4. public static void main(String[] args) {5. ArrayList<String> strings = new ArrayList<String>();6. strings.add("aAaA");7. strings.add("AaA");8. strings.add("aAa");9. strings.add("AAaa");10. Collections.sort(strings);11. for (String s: strings) { System.out.print(s + " "); }12. }13. }What is the result?A. Compilation fails.B. aAaA aAa AAaa AaAC. AAaa AaA aAa aAaAD. AaA AAaa aAaA aAaE. aAa AaA aAaA AAaaF. An exception is thrown at runtime.Answer: CQuestion 24Given:ArrayList a = new ArrayList();containing the values {"1", "2", "3", "4", "5", "6", "7", "8"} Which code will return 2?A. Collections. sort(a, a.reverse());int result = Collections.binarySearch(a, "6");B. Comparator c = Collections.reverseOrder();Collections.sort(a, c);int result = Collections.binarySearch(a, "6");C. Comparator c = Collections.reverseOrder();Collections.sort(a, c);int result = Collections.binarySearch(a, "6",c);D. Comparator c = Collections.reverseOrder(a);Collections.sort(a, c);int result = Collections.binarySearch(a, "6",c);E. Comparator c = new InverseComparator(new Comparator()); Collections.sort(a);int result = Collections.binarySearch(a, "6",c);Answer: CQuestion 25Give:11. public static Iterator reverse(List list) {12. Collections.reverse(list);13. return list.iterator();14. }15. public static void main(String[] args) {16. List list = new ArrayList();17. list.add(" 1"); list.add("2"); list.add("3");18. for (Object obj: reverse(list))19. System.out.print(obj + ",");20. }‘What is the result?A. 3,2, 1,B. 1, 2, 3,C. Compilation fails.D. The code runs with no output.E. An exception is thrown at runtime.Answer: CQuestion 26Given a pre-generics implementation of a method:11. public static int sum(List list) {12. int sum = 0;13. for ( Iterator iter = list.iterator(); iter.hasNext(); ) {14. int i = ((Integer)iter.next()).intValue();15. sum += i;16. }17. return sum;18. }Which three changes must be made to the method sum to use generics? (Choose three.)A. remove line 14B. replace line 14 with "int i = iter.next();"C. replace line 13 with "for (int i : intList) {"D. replace line 13 with "for (Iterator iter : intList) {"E. replace the method declaration with "sum(List<int> intList)"F. replace the method declaration with "sum(List<Integer> intList)"Answer: ACFQuestion 27Given:class A {}class B extends A {}class C extends A {}class D extends B {}Which three statements are true? (Choose three.)A. The type List<A> is assignable to List.B. The type List<B> is assignable to List<A>.C. The type List<Object> is assignable to List<?>.D. The type List<D> is assignable to List<? extends B>.E. The type List<? extends A> is assignable to List<A>.F. The type List<Object> is assignable to any List reference.G. The type List<? extends B> is assignable to List<? extends A>.Answer: CDGQuestion 28Given:11. public void addStrings(List list) {12. list.add("foo");13. list.add("bar");14. }What must you change in this method to compile without warnings?A. add this code after line 11:list = (List<String>) list;B. change lines 12 and 13 to:list.add<String>("foo");list.add<String>("bar");C. change the method signature on line 11 to:public void addStrings(List<? extends String> list) {D. change the method signature on line 11 to:public void addStrings(List<? super String> list) {E. No changes are necessary. This method compiles without warnings.Answer: DQuestion 29Given:1. import java.util.*;2. public class Test {3. public static void main(String[] args) {4. List<String> strings = new ArrayList<String>();5. // insert code here6. }7. }Which four, inserted at line 5, will allow compilation to succeed?(Choose four.)A. String s = strings.get(0);B. Iterator i1 = strings.iterator();C. String[] array1 = strings.toArray();D. Iterator<String> i2 = strings.iterator();E. String[] array2 = strings.toArray(new String[1]);F. Iterator<String> i3 = strings.iterator<String>(); Answer: ABDEQuestion 30Given:1. import java.util.*;2. public class Old {3. public static Object get()(List list) {4. return list.get(0);5. }6. }Which three will compile successfully? (Choose three.)A. Object o = Old.get0(new LinkedList());B. Object o = Old.get0(new LinkedList<?>());C. String s = Old.getfl(new LinkedList<String>());D. Object o = Old.get0(new LinkedList<Object>());E. String s = (String)Old.get0(new LinkedList<String>()); Answer: ADEQuestion 31Given:11. // insert code here12. private N min, max;13. public N getMin() { return min; }14. public N getMax() { return max; }15. public void add(N added) {16. if (min == null || added.doubleValue() <min.doubleValue())17. min = added;18. if (max == null ||added.doubleValue() > max.doubleValue())19. max = added;20. }21. }Which two, inserted at line 11, will allow the code to compile? (Choosetwo.)A. public class MinMax<?> {B. public class MinMax<? extends Number> {C. public class MinMax<N extends Object> {D. public class MinMax<N extends Number> {E. public class MinMax<? extends Object> {F. public class MinMax<N extends Integer> {Answer: DFQuestion 32A programmer must create a generic class MinMax and the type parameter of MinMax must implement Comparable. Which implementation of MinMax will compile?A. class MinMax<E extends Comparable<E>> {E min=null;E max=null;public MinMax() { }public void put(E value) { /* store min or max */ }}B. class MinMax<E implements Comparable<E>> {E min=null;E max=null;public MinMax() { }public void put(E value) { /* store min or max */ }}C. class MinMax<E extends Comparable<E>> {<E> E min = null;<E> E max = null;public MinMax() { }public <E> void put(E value) { /* store min or max */ }}D. class MinMax<E implements Comparable<E>> {<E> E min = null;<E> E max = null;public MinMax() { }public <E> void put(E value) { /* store min or max */ }}Answer: A二、拖拽题:Question 1:Answer:Allows access to elements by their integer index------------------java.util.List------------------defines the method V get(Object key)------------------java.util.Map------------------is designed for holding elements prior to processing------------------java.util.Queue------------------contains no pair of elements e1 and e2, such that e1.equals(e2) ------------------java.util.Set------------------Question 2:Place the code into position to create a class that maps from Strings to integer values.The result of execution must be [one]. Some options may be used more than once.Answer:public class NumberNames{private HashMap<String,Integer>map=new HashMap<String,Integer>;public void put(String name,int value){map.put(name,value);}public Set<String> getNames(){return map.keySet();}}Question 3:Answer: m1(listA); Compiles and runs without errorm2(listA); Compiles and runs without errorm1(listB); Compiles and runs without errorm2(listB); Compilation failsm1(listO); Compilation failsm2(listO); Compilation failsQuestion 4:Place the code in the appropriate place such that this program will always output [1, 2].Answer: import java.util.*;public class MyInt implements Comparable{ public static void main(String[] args) { ArrayList<MyInt> list=new ArrayList<MyInt>(); list.add(new MyInt(2));list.add(new MyInt(1));Collections.sort(list);System.out.println(list);}private int i;public MyInt(int i){this.i=i;}public String toString(){return Integer.toString(i);}public int compareTo(Object o) {MyInt i2=(MyInt)o;return i-i2.i;}}Question 5:Given the class definitions:Place the correct Compilation Result on each takeList() method definition to indicate whether or not the go() method would compile given that definition.Answer:public void takeList(ArrayList list){}-----------------------------Compilation succeedspublic void takeList(ArrayList<Dog> list) {}---------------------Compilation succeedspublic void takeList(ArrayList<Animal> list) {}-----------------Compilation failspublic void takeList(ArrayList<? extends Animal> list){}------Compilation succeedspublic void takeList(ArrayList<?> list){}-------------------------Compilation succeedspublic void takeList(ArrayList<Object> list){}------------------Compilation failsQuestion 6:Answer:public class GenericB<T extends Pet>{ public T foo;public void setFoo(T foo){this.foo = foo;}public T getFoo(){return foo;}}Question 7:Answer:ArrayList<String> x1=new ArrayList<String>();foo(x1); //Compilation of the first statement succeeds, but compilation failsdue to an error in the second statementArrayList<Object> x2=new ArrayList<String>();foo(x2); //Compilation fails due to an error in the first statement.ArrayList<Object> x3=new ArrayList<Object>();foo(x3); //Compilation succeedsArrayList x4=new ArrayList();foo(x4); //Compilation succeedsQuestion 8:Answer:public class Gen<T>{ private T object; public Gen(T object){ this.object = object; }public T getObject(){ return object;}}Question 9:Answer:list.add("Foo"); Compilation failslist = new ArrayList<String>(); Compilation succeeds list = new ArrayList<Object>(); Compilation fails String s = list.get(0); Compilation succeedsObject o = list; Compilation succeedsQuestion 10:Answer:import java.util.*;public class _166 {public static void main(String[] args) { List<String> list=new LinkedList<String>(); list.add("one");list.add("two");System.out.println(list.get(0).length());}}。
scjp认证试题及答案

scjp认证试题及答案1. 以下哪个选项是Java中声明接口的正确语法?A. interface MyInterface { }B. public interface MyInterface { }C. abstract class MyInterface { }D. class MyInterface { }答案:B2. 在Java中,以下哪个关键字用于定义一个方法?A. classB. interfaceC. methodD. function答案:B3. Java程序中的main方法的返回类型是什么?A. voidB. intC. StringD. boolean答案:B4. 以下哪个选项不是Java中的访问修饰符?A. publicB. protectedC. privateD. static答案:D5. 在Java中,以下哪个关键字用于捕获异常?A. tryB. catchC. throwD. finally答案:B6. Java中,以下哪个关键字用于定义一个类?A. classB. interfaceC. structD. type答案:A7. 在Java中,以下哪个关键字用于强制类型转换?A. castB. convertC. typeD. (Type)答案:D8. Java中,以下哪个关键字用于声明一个变量?A. varB. letC. defineD. declare答案:A9. 在Java中,以下哪个关键字用于实现接口?A. implementsB. extendsC. inheritD. override答案:A10. Java中,以下哪个关键字用于继承一个类?A. extendsB. implementsC. inheritD. override答案:A11. 在Java中,以下哪个关键字用于定义一个枚举?A. enumB. listC. setD. map答案:A12. Java中,以下哪个关键字用于定义一个方法的重载?A. overloadB. overloadsC. overloadingD. overload答案:D13. 在Java中,以下哪个关键字用于定义一个方法的重写?A. overrideB. extendsC. implementsD. overload答案:A14. Java中,以下哪个关键字用于声明一个静态方法?A. staticB. publicC. privateD. protected答案:A15. 在Java中,以下哪个关键字用于声明一个静态变量?A. staticB. finalC. constD. volatile答案:A。
SCJP题库

yModule 1-JAVA 基础一、选择题:Question 1Given:35. String #name = "Jane Doe";36. int $age=24;37. Double _height = 123.5;38. double ~temp = 37.5;Which two are true? (Choose two.)A. Line 35 will not compile.B. Line 36 will not compile.C. Line 37 will not compile.D. Line 38 will not compile.Answer: AD 标识符以字母,下划线,或者$开始Question 2Given:11. public class Test {12. public static void main(String [] args) {13. int x =5;14. boolean b1 = true;15. boolean b2 = false;16.17.if((x==4) && !b2)18. System.out.print("l ");19. System.out.print("2 ");20. if ((b2 = true) && b1)21. System.out.print("3");22. }23. }What is the result?A. 2B. 3C. 1 2D. 2 3E. 1 2 3F. Compilation fails.G. An exceptional is thrown at runtime.Answer: D 注意20行,=为赋值,不要被骗Question 3Given:42. public class ClassA {43. public int getValue() {44. int value=0;45. boolean setting = true;46. String title="Hello";47. if (value || (setting && title == "Hello")) { return 1; }48. if (value == 1 & title.equals("Hello")) { return 2; }49. }50. }And:70. ClassA a = new ClassA();71. a.getValue();What is the result?A. 1B. 2C. Compilation fails.D. The code runs with no output.E. An exception is thrown at runtime.Answer: C 编译不通过,47行value为int类型不是booleanQuestion 4Given:11. public void testIfA() {12. if(testIfB("True")) {13. System.out.println("True");14. } else {15. System.out.println("Not true");16. }17. }18. public Boolean testIfB(String str) {19. return Boolean.valueOf(str);20. }What is the result when method testIfA is invoked?A. TrueB. Not trueC. An exception is thrown at runtime.D. Compilation fails because of an error at line 12.E. Compilation fails because of an error at line 19. Answer: A 19行,如果str为true则返回ture,否则返回falseQuestion 5Given:11. public static void main(String[] args) {12. Integer i = new Integer(1) + new Integer(2);13. switch(i) {14. case 3: System.out.println("three"); break;15. default: System.out.println("other"); break;16. }17. }What is the result?A. threeB. otherC. An exception is thrown at runtime.D. Compilation fails because of an error on line 12.E. Compilation fails because of an error on line 13.F. Compilation fails because of an error on line 15. Answer: A 就是两个Integer类型相加Question 6Given:11. public static void main(String[] args) {12. String str = "null";13. if (str == null) {14. System.out.println("null");15. } else (str.length() == 0) {16. System.out.println("zero");17. } else {18. System.out.println("some");19. }20. }‘What is the result?A. nullB. zeroC. someD. Compilation fails.E. An exception is thrown at runtime. Answer: D 这题真恶心 15行少个ifQuestion 7Given:10.int x=0;11.int y=10;12. do {l3. y--;14. ++x;15. } while (x < 5);16. System.out.print(x + "," + y);What is the result?A. 5,6B. 5,5C. 6,5D. 6,6Answer: B (91,82,73,64,55)没啥争议Question 8Given:25.int x=12;26. while (x < 10) {27. x--;28. }29. System.out.print(x);What is the result?A. 0B. 10C. 12D. Line 29 will never be reached. Answer: C 12>10,所以直接跳出循环,输出x=12 Question 9Given:35. int x= 10;36. do {37. x--;38. } while(x< 10);How many times will line 37 be executed?A. ten timesB. zero timesC. one to me timesD. more than ten timesAnswer: D 死循环Question 10Given:11. public static void main(String[] args) {12. for (int i=0;i<= 10;i++){13. if( i>6) break;14. }15. System.out.println(i);16. }What is the result?A. 6B. 7C. 10D. 11E. Compilation fails.F. An exception is thrown at runtime.Answer: E 15行i超出了作用域Question 11Given:55. int []x= {1, 2,3,4, 5};56. int y[] =x;57. System.out.println(y[2]);Which is true?A. Line 57 will print the value 2.B. Line 57 will print the value 3.C. Compilation will fail because of an error in line 55.D. Compilation will fail because of an error in line 56.Answer: B 没争议,考察数组下标是从0开始Question 12Which two code fragments(片段) correctly(正确) create and initialize a static array of int elements? (Choose two.)A. static final int[] a = { 100,200 };B. static final int[] a;static { a=new int[2]; a[0]=100; a[1]=200; }C. static final int[] a = new int[2] { 100,200 };D. static final int[] a;static void init() { a = new int[3]; a[0]=100; a[1]=200; }Answer: AB c不能指定长度,d不能在init方法中赋值,要么在static代码块中Question 13Given:11. public static void main(String[] args) {12. Object obj = new int[] { 1,2,3 };13. int[] someArray = (int[])obj;14. for (int i: someArray) System.out.print(i +" ")15. }‘What is the result?A. 1 2 3B. Compilation fails because of an error in line 12.C. Compilation fails because of an error in line 13.D. Compilation fails because of an error in line 14.E. A ClassCastException is thrown at runtime.Answer: A 没争议,foeach循环遍历数组Question 14Given:11. String[] elements = { "for", "tea", "too" };12. String first = (elements.length > 0)? elements[0] : null;What is the result?A. Compilation fails.B. An exception is thrown at runtime.C. The variable first is set to null.D. The variable first is set to elements[0].Answer: DQuestion 15Given:10. public class Bar {11.static void foo(int...x) {12. // insert code here13. }14. }Which two code fragments, inserted independently(独立的) at line 12, will allow the class to compile? (Choose two.)A. foreach(x) System.out.println(z);B. for(int z : x) System.out.println(z);C. while( x.hasNext()) System.out.println( x.next());D. for( int i=0; i< x.length; i++ ) System.out.println(x[i]); Answer: BD x相当于一个数组,a明显错没有foreach,c中x没有hadNext方法Question 16A programmer(程序员) needs to create a logging method that can accept (接受) an arbitrary(随意任意) number of arguments. For example, it may be called in theseways:logIt("log message 1 ");logIt("log message2”,”log message3");logIt("log message4", "log message5", "log message6");Which declaration(说明) satisfies(符合) this requirement(需求)?A. public void logIt(String * msgs)B. public void logIt(String [] msgs)C. public void logIt(String... msgs)D. public void logIt(String msg1, String msg2, String msg3)Answer: C 可变长参数Question 171. public class A {2. public String doit(int x, int y) {3. return "a";4. }5.6. public String doit(int... vals) {7. return "b";8. }9. }Given:25. A a=new A();26. System.out.println(a.doit(4, 5));What is the result?A. Line 26 prints "a" to System.out.B. Line 26 prints "b" to System.out.C. An exception is thrown at line 26 at runtime.D. Compilation of class A will fail due to an error in line 6. Answer: A 确定参数和可变长参数同时存在的时候,优先考虑确定参数的Question 18Given a file GrizzlyBear.java:1. package animals.mammals;2.3. public class GrizzlyBear extends Bear {4. void hunt() {5. Salmon s = findSalmon();6. s.consume();7. }8. }and another file, Salmon.java:1. package animals.fish;2.3. public class Salmon extends Fish {4. void consume() { /* do stuff */ }5. }Assume(假定) both classes are defined in the correct directories for theft packages, and that the Mammal class correctly defines the findSalmon() method. Which two changes allow this code to compile correctly? (Choose two.)A. add public to the start of line 4 in Salmon.javaB. add public to the start of line 4 in GrizzlyBear.javaC. add import animals.mammals.*; at line 2 in Salmon.javaD. add import animals.fish.*; at line 2 in GrizzlyBear.javaE. add import animals.fish.Salmon.*; at line 2 in GrizzlyBear.javaF. add import animals.mammals.GrizzlyBear.*;at line 2 in Salmon.java Answer: AD 调用不同包下的类,要先导入,方法权限要设置成publicQuestion 19Given:10. package com.sun.scjp;11. public class Geodetics {12. public static final double DIAMETER = 12756.32; // kilometers13. }Which two correctly access(访问) the DIAMETER member of the Geodetics class? (Choose two.)A. import com.sun.scjp.Geodetics;public class TerraCarta {public double halfway(){ return Geodetics.DIAMETER/2.0; } }B. import static com.sun.scjp.Geodetics;public class TerraCarta {public double halfway() { return DIAMETER/2.0; } }C. import static com.sun.scjp.Geodetics. *;public class TerraCarta {public double halfway() { return DIAMETER/2.0; } }D. package com.sun.scjp;public class TerraCarta {public double halfway() { return DIAMETER/2.0; } }Answer: AC b中不能静态导入类,c中静态导入类属性,正确,d访问错误很明显Question 20Given classes defined in two different files:1. package util;2. public class BitUtils {3. private static void process(byte[] b) { }4. }1. package app;2. public class SomeApp {3. public static void main(String[] args) {4. byte[] bytes = new byte[256];5. // insert code here6. }7. }What is required(必需的) at line 5 in class SomeApp to use the process methodof BitUtils?A. process(bytes);B. BitUtils.process(bytes);C. app.BitUtils.process(bytes);D. util.BitUtils.process(bytes);E. import util.BitUtils. *; process(bytes);F. SomeApp cannot use the process method in BitUtils.Answer: F 私有的,不能被访问Question 21Given a class Repetition(重复):1. package utils;2.3. public class Repetition {4. public static String twice(String s) { return s + s; }5. }and given another class Demo:1. // insert code here2.3. public class Demo {4. public static void main(String[] args) {5. System.out.println(twice("pizza"));6. }7. }Which code should be inserted at line 1 of Demo.java to compile and run Demo to print “pizzapizza”?A. import utils.*;B. static import utils.*;C. import utils.Repetition.*;D. static import utils.Repetition. *;E. import utils.Repetition.twice();F. import static utils.Repetition.twice;G. static import utils.Repetition.twice;Answer: F 静态导入Question 22Given:1. package test;2.3. class Target(目标) {4. public String name = "hello";5. }What can directly(直接的) access and change the value of the variable (变量) name?A. any classB. only the Target classC. any class in the test packageD. any class that extends TargetAnswer: C default类型的类本包访问权限Question 23Given:11. rbo = new ReallyBigObject();12. // more code here13. rbo = null;14. /* insert code here */Which statement(语句) should be placed at line 14 to suggest(促成) that the virtual machine(虚拟机) expend(消耗) effort(努力) toward recycling (回收) the memory used by the object rbo?A. System.gc();B. Runtime.gc();C. System.freeMemory();D. Runtime.getRuntime().growHeap();E. Runtime.getRuntime().freeMemory();Answer: A 题很简单。
SCJP试题集及解析

SCJP试题集及解析1. Which of the following range of short is correct?A. -27 -- 27-1B. 0 – 216-1C. 215 – 215-1D. 231 – 231-1翻译:下面哪些是short型的取值范围。
答案::C解析:短整型的数据类型的长度是16 bits,有符号。
另外需要说明的是java中所有的整(Integral)数(包括byte,short,int,long)全是有符号的。
2. Which declarations of identifiers are legal?A. $personsB. TwoUsersC. *pointD. thisE. _endline翻译:下面哪些是合法的标识符。
答案:A,B,E解析:Java的标识符可以以一个Unicode字符,下滑线(_),美元符($)开始,后续字符可以是前面的符号和数字,没有长度限制,大小写敏感,不能是保留字。
3. Which statement of assigning a long type variable to a hexadecimal valueis correct?A. long number = 345L;B. long number = 0345;C. long number = 0345L;D. long number = 0x345L翻译:哪些是将一个十六进制值赋值给一个long型变量。
答案D解析:十六进制数以0x开头,long型数以L(大小写均可,一般使用大写,因为小写的l和数字1不易区分)。
4. Which of the following fragments might cause errors?A. String s = "Gone with the wind";String t = " good ";String k = s + t;B. String s = "Gone with the wind";String t;t = s[3] + "one";C. String s = "Gone with the wind";String standard = s.toUpperCase();D. String s = "home directory";String t = s - "directory";翻译:下面的哪些程序片断可能导致错误。
SCJP 6.0认证教战手册考题1

public void bar(int x){}
public int bar(String x){return 1;}
public void bar(int x, int y){} } 參考:6-5 繼承
第13題
Given: 1. 2.
參考:4-1 條件控制
4
SCJP 6.0 認證教戰手冊 黃彬華著 碁峰出版
第9題 Given:
11. String[] elements = {"for", "tea", "too"}; 12. String first = (elements.length>0) ? elements[0] : null; What is the result? A. Compilation fails. B. An exception is thrown at runtime. C. The variable first is set to null. D. The variable first is set to elements[0]. 答案:D 參考:4-1 條件控制、5-2 1 維陣列介紹
6
SCJP 6.0 認證教戰手冊 黃彬華著 碁峰出版
3.
new Barn.go("hi", 1);
4.
new Barn.go("hi", "world", 2);
5.
}
6.
public void go(String... y, int x){
7.
System.out.print(y[y.length-1] + " ");
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
转载对题目和答案谨做参考Q1A method is ...1) an implementation of an abstraction.2) an attribute defining the property of a particular abstraction.3) a category of objects.4) an operation defining the behavior for a particular abstraction.5) a blueprint for making operations.Q2An object is ...1) what classes are instantiated from.2) an instance of a class.3) a blueprint for creating concrete realization of abstractions.4) a reference to an attribute.5) a variable.Q3Which line contains a constructor in this class definition?public class Counter { // (1)int current, step;public Counter(int startValue, int stepValue) { // (2)set(startValue);setStepValue(stepValue);}public int get() { return current; } // (3)public void set(int value) { current = value; } // (4)public void setStepValue(int stepValue) { step = stepValue; } // (5) }1) Code marked with (1) is a constructor2) Code marked with (2) is a constructor3) Code marked with (3) is a constructor4) Code marked with (4) is a constructor5) Code marked with (5) is a ConstructorQ4Given that Thing is a class, how many objects and reference variables are created by the following code?Thing item, stuff;item = new Thing();Thing entity = new Thing();1) One object is created2) Two objects are created3) Three objects are created4) One reference variable is created5) Two reference variables are created6) Three reference variables are created.Q5An instance member…1) is also called a static member2) is always a variable3) is never a method4) belongs to a single instance, not to the class as a whole5) always represents an operationQ6How do objects pass messages in Java?1) They pass messages by modifying each other's member variables2) They pass messages by modifying the static member variables of each other's classes3) They pass messages by calling each other's instance member methods4) They pass messages by calling static member methods of each other's classes.Q7Given the following code, which statements are true?class A {int value1;}class B extends A {int value2;}1) Class A extends class B.2) Class B is the superclass of class A.3) Class A inherits from class B.4) Class B is a subclass of class A.5) Objects of class A have a member variable named value2.Q8If this source code is contained in a file called SmallProg.java, what command should be used to compile it using the JDK?public class SmallProg {public static void main(String args[]) { System.out.println("Good luck!"); }}1) java SmallProg2) avac SmallProg3) java SmallProg.java4) javac SmallProg.java5) java SmallProg mainQ9Given the following class, which statements can be inserted at position 1 without causing the code to fail compilation?public class Q6db8 {int a;int b = 0;static int c;public void m() {int d;int e = 0;// Position 1}}1) a++;2) b++;3) c++;4) d++;5) e++;Q10Which statements are true concerning the effect of the >> and >>> operators?1) For non-negative values of the left operand, the >> and >>> operators will have the same effect.2) The result of (-1 >> 1) is 0.3) The result of (-1 >>> 1) is -1.4) The value returned by >>> will never be negative as long as the value of the right operand is equal to or greater than 1.5) When using the >> operator, the leftmost bit of the bit representation of the resulting value will always be the same bit value as the leftmost bit of the bit representation of the left operand.Q11What is wrong with the following code?class MyException extends Exception {}public class Qb4ab {public void foo() {try {bar();} finally {baz();} catch (MyException e) {}}public void bar() throws MyException {throw new MyException();}public void baz() throws RuntimeException {throw new RuntimeException();}}1) Since the method foo() does not catch the exception generated by the method baz(), it must declare the RuntimeException in its throws clause.2) A try block cannot be followed by both a catch and a finally block.3) An empty catch block is not allowed.4) A catch block cannot follow a finally block.5) A finally block must always follow one or more catch blocks.Q12What will be written to the standard output when the following program is run?public class Qd803 {public static void main(String args[]) {String word = "restructure";System.out.println(word.substring(2, 3));}}1) est2) es3) str4) st5) sQ13Given that a static method doIt() in a class Work represents work to be done, what block of code will succeed in starting a new thread that will do the work?CODE BLOCK A:Runnable r = new Runnable() { public void run() {Work.doIt();}};Thread t = new Thread(r);t.start();CODE BLOCK B:Thread t = new Thread() {public void start() {Work.doIt();}};t.start();CODE BLOCK C:Runnable r = new Runnable() { public void run() {Work.doIt();}};r.start();CODE BLOCK D:Thread t = new Thread(new Work()); t.start();CODE BLOCK E:Runnable t = new Runnable() { public void run() {Work.doIt();}};t.run();1) Code block A.2) Code block B.3) Code block C.4) Code block D.5) Code block E.Q14Write a line of code that declares a variable named layout of type LayoutManager and initializes it with a new object, which when used with a container can lay out components in a rectangular grid of equal-sized rectangles, 3 components wide and 2 components high.Q15public class Q275d {static int a;int b;public Q275d() {int c;c = a;a++;b += c;}public static void main(String args[]) {new Q275d();}}1) The code will fail to compile, since the constructor is trying to access static members.2) The code will fail to compile, since the constructor is trying to use static member variable a before it has been initialized.3) The code will fail to compile, since the constructor is trying to use member variable b before it has been initialized.4) The code will fail to compile, since the constructor is trying to use local variable c before it has been initialized.5) The code will compile and run without any problems.Q16What will be written to the standard output when the following program is run?public class Q63e3 {public static void main(String args[]) {System.out.println(9 ^ 2);}}1) 812) 73) 114) 05) falseQ17Which statements are true concerning the default layout manager for containers in the java.awt package?1) Objects instantiated from Panel do not have a default layout manager.2) Objects instantiated from Panel have FlowLayout as default layout manager.3) Objects instantiated from Applet have BorderLayout as default layout manager.4) Objects instantiated from Dialog have BorderLayout as default layout manager.5) Objects instantiated from Window have the same default layout manager as instances of Applet.Q18Which declarations will allow a class to be started as a standalone program?1) public void main(String args[])2) public void static main(String args[])3) public static main(String[] argv)4) final public static void main(String [] array)5) public static void main(String args[])Q19Under which circumstances will a thread stop?1) The method waitforId() in class MediaTracker is called.2) The run() method that the thread is executing ends.3) The call to the start() method of the Thread object returns.4) The suspend() method is called on the Thread object.5) The wait() method is called on the Thread object.Q20When creating a class that associates a set of keys with a set of values, which of these interfaces is most applicable?1) Collection2) Set3) SortedSet4) MapQ21What does the value returned by the method getID() found in class java.awt.AWTEvent uniquely identify?1) The particular event instance.2) The source of the event.3) The set of events that were triggered by the same action.4) The type of event.5) The type of component from which the event originated.Q22What will be written to the standard output when the following program is run?class Base {int i;Base() {add(1);}void add(int v) {i += v;}void print() {System.out.println(i);}}class Extension extends Base {Extension() {add(2);}void add(int v) {i += v*2;}}public class Qd073 {public static void main(String args[]) {bogo(new Extension());}static void bogo(Base b) {b.add(8);b.print();}}1) 92) 183) 204) 215) 22Q23Which lines of code are valid declarations of a native method when occurring within the declaration of the following class?public class Qf575 {// insert declaration of a native method here}1) native public void setTemperature(int kelvin);2) private native void setTemperature(int kelvin);3) protected int native getTemperature();4) public abstract native void setTemperature(int kelvin);5) native int setTemperature(int kelvin) {}Q24How does the weighty property of the GridBagConstraints objects used in grid bag layout affect the layout of the components?1) It affects which grid cell the components end up in.2) It affects how the extra vertical space is distributed.3) It affects the alignment of each component.4) It affects whether the components completely fill their allotted display area vertically.Q25Which statements can be inserted at the indicated position in the following code to make the program write 1 on the standard output when run?public class Q4a39 {int a = 1;int b = 1;int c = 1;class Inner {int a = 2;int get() {int c = 3;// insert statement herereturn c;}}Q4a39() {Inner i = new Inner();System.out.println(i.get());}public static void main(String args[]) {new Q4a39();}}1) c = b;2) c = this.a;3) c = this.b;4) c = Q4a39.this.a;5) c = c;Q26Which is the earliest line in the following code after which the object created on the line marked (0) will be a candidate for being garbage collected, assuming no compiler optimizations are done?public class Q76a9 {static String f() {String a = "hello";String b = "bye"; // (0)String c = b + "!"; // (1)String d = b;b = a; // (2)d = a; // (3)return c; // (4)}public static void main(String args[]) {String msg = f();System.out.println(msg); // (5)}}1) The line marked (1).2) The line marked (2).3) The line marked (3).4) The line marked (4).5) The line marked (5).Q27Which methods from the String and StringBuffer classes modify the object on which they are called?1) The charAt() method of the String class.2) The toUpperCase() method of the String class.3) The replace() method of the String class.4) The reverse() method of the StringBuffer class.5) The length() method of the StringBuffer class.Q28Which statements, when inserted at the indicated position in the following code, will cause a runtime exception when attempting to run the program?class A {}class B extends A {}class C extends A {}public class Q3ae4 {public static void main(String args[]) {A x = new A();B y = new B();C z = new C();// insert statement here}}1) x = y;2) z = x;3) y = (B) x;4) z = (C) y;5) y = (A) y;Q29Which of these are keywords in Java?1) default2) NULL3) String4) throws5) longQ30It is desirable that a certain method within a certain class can only be accessed by classes that are defined within the same package as the class of the method. How can such restrictions be enforced?1) Mark the method with the keyword public.2) Mark the method with the keyword protected.3) Mark the method with the keyword private.4) Mark the method with the keyword package.5) Do not mark the method with any accessibility modifiers.Q31Which code fragments will succeed in initializing a two-dimensional array named tab with a size that will cause the expression tab[3][2] to access a valid element?CODE FRAGMENT A:int[][] tab = {{ 0, 0, 0 },{ 0, 0, 0 }};CODE FRAGMENT B:int tab[][] = new int[4][];for (int i=0; iCODE FRAGMENT C:int tab[][] = {0, 0, 0, 0,0, 0, 0, 0,0, 0, 0, 0,0, 0, 0, 0};CODE FRAGMENT D:int tab[3][2];CODE FRAGMENT E:int[] tab[] = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0} };1) Code fragment A.2) Code fragment B.3) Code fragment C.4) Code fragment D.5) Code fragment E.Q32What will be the result of attempting to run the following program?public class Qaa75 {public static void main(String args[]) {String[][][] arr = {{ {}, null },{ { "1", "2" }, { "1", null, "3" } },{},{ { "1", null } }};System.out.println(arr.length + arr[1][2].length);}}1) The program will terminate with an ArrayIndexOutOfBoundsException.2) The program will terminate with a NullPointerException.3) 4 will be written to standard output.4) 6 will be written to standard output.5) 7 will be written to standard output.Q33Which expressions will evaluate to true if preceded by the following code? String a = "hello";String b = new String(a);String c = a;char[] d = { 'h', 'e', 'l', 'l', 'o' };1) (a == "Hello")2) (a == b)3) (a == c)4) a.equals(b)5) a.equals(d)Q34Which statements concerning the following code are true?class A {public A() {}public A(int i) { this(); }}class B extends A {public boolean B(String msg) { return false; }}class C extends B {private C() { super(); }public C(String msg) { this(); }public C(int i) {}}1) The code will fail to compile.2) The constructor in A that takes an int as an argument will never be called as a result of constructing an object of class B or C.3) Class C has three constructors.4) Objects of class B cannot be constructed.5) At most one of the constructors of each class is called as a result of constructing an object of class C.Q35Given two collection objects referenced by col1 and col2, which of these statements are true?1) The operation col1.retainAll(col2) will not modify the col1 object.2) The operation col1.removeAll(col2) will not modify the col2 object.3) The operation col1.addAll(col2) will return a new collection object,containing elements from both col1 and col2.4) The operation col1.containsAll(Col2) will not modify the col1 object.Q36Which statements concerning the relationships between the following classes are true?class Foo {int num;Baz comp = new Baz();}class Bar {boolean flag;}class Baz extends Foo {Bar thing = new Bar();double limit;}1) A Bar is a Baz.2) A Foo has a Bar.3) A Baz is a Foo.4) A Foo is a Baz.5) A Baz has a Bar.Q37Which statements concerning the value of a member variable are true, when no explicit assignments have been made?1) The value of an int is undetermined.2) The value of all numeric types is zero.3) The compiler may issue an error if the variable is used before it is initialized.4) The value of a String variable is "" (empty string).5) The value of all object variables is null.Q38Which statements describe guaranteed behavior of the garbage collection and finalization mechanisms?1) Objects are deleted when they can no longer be accessed through any reference.2) The finalize() method will eventually be called on every object.3) The finalize() method will never be called more than once on an object.4) An object will not be garbage collected as long as it is possible for an active part of the program to access it through a reference.5) The garbage collector will use a mark and sweep algorithm.Q39Which code fragments will succeed in printing the last argument given on the command line to the standard output, and exit gracefully with no output if no arguments are given?CODE FRAGMENT A:public static void main(String args[]) {if (args.length != 0)System.out.println(args[args.length-1]);}CODE FRAGMENT B:public static void main(String args[]) {try { System.out.println(args[args.length]); }catch (ArrayIndexOutOfBoundsException e) {}}CODE FRAGMENT C:public static void main(String args[]) {int ix = args.length;String last = args[ix];if (ix != 0) System.out.println(last);}CODE FRAGMENT D:public static void main(String args[]) {int ix = args.length-1;if (ix > 0) System.out.println(args[ix]);}CODE FRAGMENT E:public static void main(String args[]) {try { System.out.println(args[args.length-1]); }catch (NullPointerException e) {}}1) Code fragment A.2) Code fragment B.3) Code fragment C.4) Code fragment D.5) Code fragment E.Q40Which of these statements concerning the collection interfaces are true?1) Set extends Collection.2) All methods defined in Set are also defined in Collection.3) List extends Collection.4) All methods defined in List are also defined in Collection.5) Map extends Collection.Q41What is the name of the method that threads can use to pause their execution until signalled to continue by another thread?Fill in the name of the method (do not include a parameter list).Q42Given the following class definitions, which expression identifies whether the object referred to by obj was created by instantiating class B rather than classes A, C and D?class A {}class B extends A {}class C extends B {}class D extends A {}1) obj instanceof B2) obj instanceof A && ! (obj instanceof C)3) obj instanceof B && ! (obj instanceof C)4) obj instanceof C || obj instanceof D5) (obj instanceof A) && ! (obj instanceof C) && ! (obj instanceof D)Q43What will be written to the standard output when the following program is run?public class Q8499 {public static void main(String args[]) {double d = -2.9;int i = (int) d;i *= (int) Math.ceil(d);i *= (int) Math.abs(d);System.out.println(i);}}1) 122) 183) 84) 125) 27Q44What will be written to the standard output when the following program is run?public class Qcb90 {int a;int b;public void f() {a = 0;b = 0;int[] c = { 0 };g(b, c);System.out.println(a + " " + b + " " + c[0] + " ");}public void g(int b, int[] c) {a = 1;b = 1;c[0] = 1;}public static void main(String args[]) {Qcb90 obj = new Qcb90();obj.f();}}1) 0 0 02) 0 0 13) 0 1 04) 1 0 05) 1 0 1Q45Which statements concerning the effect of the statement gfx.drawRect(5, 5, 10, 10) are true, given that gfx is a reference to a valid Graphics object?1) The rectangle drawn will have a total width of 5 pixels.2) The rectangle drawn will have a total height of 6 pixels.3) The rectangle drawn will have a total width of 10 pixels.4) The rectangle drawn will have a total height of 11 pixels.Q46Given the following code, which code fragments, when inserted at the indicated location, will succeed in making the program display a button spanning the whole window area?import java.awt.*;public class Q1e65 {public static void main(String args[]) {Window win = new Frame();Button but = new Button("button");// insert code fragment herewin.setSize(200, 200);win.setVisible(true);}}1) win.setLayout(new BorderLayout()); win.add(but);2) win.setLayout(new GridLayout(1, 1)); win.add(but);3) win.setLayout(new BorderLayout()); win.add(but, BorderLayout.CENTER);4) win.add(but);5) win.setLayout(new FlowLayout()); win.add(but);Q47Which method implementations will write the given string to a file named "file", using UTF8 encoding?IMPLEMENTATION A:public void write(String msg) throws IOException {FileWriter fw = new FileWriter(new File("file"));fw.write(msg);fw.close();}IMPLEMENTATION B:public void write(String msg) throws IOException {OutputStreamWriter osw =new OutputStreamWriter(new FileOutputStream("file"), "UTF8");osw.write(msg);osw.close();}IMPLEMENTATION C:public void write(String msg) throws IOException { FileWriter fw = new FileWriter(new File("file"));fw.setEncoding("UTF8");fw.write(msg);fw.close();}IMPLEMENTATION D:public void write(String msg) throws IOException { FilterWriter fw = FilterWriter(new FileWriter("file"), "UTF8"); fw.write(msg);fw.close();}IMPLEMENTATION E:public void write(String msg) throws IOException { OutputStreamWriter osw = new OutputStreamWriter(new OutputStream(new File("file")), "UTF8");osw.write(msg);osw.close();}1) Implementation A.2) Implementation B.3) Implementation C.4) Implementation D.5) Implementation E.Q48Which are valid identifiers?1) _class2) $value$3) zer@4) ¥ngstr5) 2muchuqQ49What will be the result of attempting to compile and run the following program?public class Q28fd {public static void main(String args[]) {int counter = 0;l1:for (int i=10; i<0; i--) {l2:int j = 0;while (j < 10) {if (j > i) break l2;if (i == j) {counter++;continue l1;}}counter--;}System.out.println(counter);}}1) The program will fail to compile.2) The program will not terminate normally.3) The program will write 10 to the standard output.4) The program will write 0 to the standard output.5) The program will write 9 to the standard output.Q50Given the following interface definition, which definitions are valid?interface I {void setValue(int val);int getValue();}DEFINITION A:(a) class A extends I {int value;void setValue(int val) { value = val; }int getValue() { return value; }}DEFINITION B:(b) interface B extends I {void increment();}DEFINITION C:(c) abstract class C implements I {int getValue() { return 0; }abstract void increment();}DEFINITION D:(d) interface D implements I {void increment();}DEFINITION E:(e) class E implements I {int value;public void setValue(int val) { value = val; } }1) Definition A.2) Definition B.3) Definition C.4) Definition D.5) Definition E.Q51Which statements concerning the methods notify() and notifyAll() are true?1) Instances of class Thread have a method called notify().2) A call to the method notify() will wake the thread that currently owns the monitor of the object.3) The method notify() is synchronized.4) The method notifyAll() is defined in class Thread.5) When there is more than one thread waiting to obtain the monitor of an object, there is no way to be sure which thread will be notified by the notify() method.Q52Which statements concerning the correlation between the inner and outer instances of non-static inner classes are true?1) Member variables of the outer instance are always accessible to inner instances, regardless of their accessibility modifiers.2) Member variables of the outer instance can never be referred to using only the variable name within the inner instance.3) More than one inner instance can be associated with the same outer instance.4) All variables from the outer instance that should be accessible in the inner instance must be declared final.5) A class that is declared final cannot have any inner classes.Q53What will be the result of attempting to compile and run the following code?public class Q6b0c {public static void main(String args[]) {int i = 4;float f = 4.3;double d = 1.8;int c = 0;if (i == f) c++;if (((int) (f + d)) == ((int) f + (int) d)) c += 2;System.out.println(c);}}1) The code will fail to compile.2) 0 will be written to the standard output.3) 1 will be written to the standard output.4) 2 will be written to the standard output.5) 3 will be written to the standard output.Q54Which operators will always evaluate all the operands?1) ||2) +3) &&4) ? :5) %Q55Which statements concerning the switch construct are true?1) All switch statements must have a default label.2) There must be exactly one label for each code segment in a switch statement.3) The keyword continue can never occur within the body of a switch statement.4) No case label may follow a default label within a single switch statement.5) A character literal can be used as a value for a case label.Q56Which modifiers and return types would be valid in the declaration of a working main() method for a Java standalone application?1) private2) final3) static4) int5) abstractQ57What will be the appearance of an applet with the following init() method?public void init() {add(new Button("hello"));}1) Nothing appears in the applet.2) A button will cover the whole area of the applet.3) A button will appear in the top left corner of the applet.4) A button will appear, centered in the top region of the applet.5) A button will appear in the center of the applet.Q58Which statements concerning the event model of the AWT are true?1) At most one listener of each type can be registered with a component.2) Mouse motion listeners can be registered on a List instance.3) There exists a class named ContainerEvent in package java.awt.event.4) There exists a class named MouseMotionEvent in package java.awt.event.5) There exists a class named ActionAdapter in package java.awt.event.Q59Which statements are true, given the code new FileOutputStream("data", true) for creating an object of class FileOutputStream?1) FileOutputStream has no constructors matching the given arguments.2) An IOExeception will be thrown if a file named "data" already exists.3) An IOExeception will be thrown if a file named "data" does not already exist.4) If a file named "data" exists, its contents will be reset and overwritten.5) If a file named "data" exists, output will be appended to its current contents.Q60Given the following code, write a line of code that, when inserted at the indicated location, will make theoverriding method in Extension invoke the overridden method in class Base on the current object.class Base {public void print() {System.out.println("base");}}class Extention extends Base {public void print() {System.out.println("extension");// insert line of implementation here}}public class Q294d {public static void main(String args[]) {Extention ext = new Extention();ext.print();}}Fill in a single line of implementation.Q61Given that file is a reference to a File object that represents a directory, which code fragments will succeed in obtaining a list of the entries in the directory?1) Vector filelist = ((Directory) file).getList();2) String[] filelist = file.directory();3) Enumeration filelist = file.contents();4) String[] filelist = file.list();5) Vector filelist = (new Directory(file)).files();Q62What will be written to the standard output when the following program is run?。