JAVA认证历年真题:SCJP考试真题和解析(2)

合集下载

JAVA认证历年真题-SCJP考试真题和解析[1].doc

JAVA认证历年真题-SCJP考试真题和解析[1].doc

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)方法。

JAVA认证历年真题SCJP考试真题和解析(1)

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(。

java认证考试试题及答案

java认证考试试题及答案

java认证考试试题及答案 1. What gets printed when the following program is compiled and run? class Test { public static void main(String args[]) { int i; do { i++; } while (i < 0); System.out.println(i); } } Select 1 correct answer: A. The program does not compile as i is not initialized. B. The program compiles but does not run. C. The program compiles and runs but does not print anything. D. The program prints 0. E. The program prints 1. 答案:A:如果没有初始化便使⽤基本变量类型,会导致编译时异常,程序不能编译。

2. What gets printed when the following program is compiled and run? public class XYZ { public static void main(String args[]) { int i,j,k; for (i = 0; i < 3; i++) { for(j=1; j < 4; j++) { for(k=2; k<5; k++) { if((i == j) && (j==k)) System.out.println(i); } } } } } Select 1 correct answer: A. 0 B. 1 C. 2 D. 3 E. 4 答案:C 3. Given the following code : class Base{} public class MyCast extends Base{ static boolean b1=false; static int i = -1; static double d = 10.1; public static void main(String argv[]){ MyCast m = new MyCast(); Base b = new Base(); //Here } } Which of the following, if inserted at the comment //Here will allow the code to compile and run without error? Select 2 correct answers: A. b = m; B. m = b; C. d = i; D. b1 = i; 解析:A 从⼦类型到⽗类型的转换是扩展引⽤转换,不需要在运⾏时采取特殊的动作,不会在运⾏时抛出异常。

java考试试题及答案解析

java考试试题及答案解析

java考试试题及答案解析一、单选题(每题2分,共20分)1. Java中,下列哪个关键字用于声明一个类?A. classB. publicC. staticD. void答案:A解析:在Java中,关键字class用于声明一个类。

public、static 和void分别是访问修饰符、修饰符和返回类型,不用于声明类。

2. 下列哪个选项是Java中的保留字?A. finalB. StringC. SystemD. main答案:A解析:final是Java中的保留字,用于声明一个变量、方法或类不可被修改。

String是类名,System是类名,main是方法名。

3. 在Java中,下列哪个选项是正确的方法声明?A. public void myMethod();B. public int myMethod();C. public myMethod();D. public void myMethod(int a);答案:D解析:在Java中,方法声明需要指定返回类型和参数列表。

选项A和B缺少参数列表,选项C缺少返回类型。

选项D是正确的方法声明。

4. 下列哪个选项是Java中的合法变量名?A. 2variableB. _variableC. $variableD. variable2答案:D解析:在Java中,变量名必须以字母、下划线或美元符号开头,不能以数字开头。

选项A以数字开头,选项B和C包含非法字符。

选项D是合法的变量名。

5. 在Java中,下列哪个选项是正确的数组声明?A. int[] myArray;B. int myArray[];C. int[] myArray = new int[5];D. int myArray = new int[5];答案:C解析:在Java中,数组声明需要指定数组类型和变量名,然后使用new关键字创建数组实例。

选项A和B缺少数组实例化,选项D将数组赋值给非数组类型的变量。

SUN认证Java2程序员考试(SCJP) 试题解析(2)

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考试真题和解析

JAVA认证历年真题_SCJP考试真题和解析

JAVA认证历年真题:SCJP考试真题和解析[2]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 value is 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认证考试题库2

SCJP认证考试题库2

QUESTION 61GIVEN THE EXHIBIT:Which statement is true?A. All of the assert statements are used appropriately.B. Only the assert statement on line 31 is used appropriatelyC. The assert statements on lines 29 and 31 are used appropriatelyD. The assert statements on lines 26 and 29 are used appropriatelyE. The assert statements on lines 29 and 33 are used appropriatelyF. The assert statements on lines 29 ,31and 33 are used appropriatelyG. The assert statements on lines 26,29 and 31 are used appropriately断言应该用在“你认为”你的程序不可能产生错误的地方,而且有没有启用断言,都不会影响程序的正常运行。

断言使用限制:1.不要在public方法中,用断言来检查参数的正确性;2.不要让断言语句去处理一些程序必须的流程。

原因:1.public方法会被别人调用,你不能保证他一定启用断言;如果没有启用,那么用断言来做参数的检查也就没有意义了。

所以不要用断言来检查参数,公共方法的参数一定要用代码执行检查; 2.如果用断言来控制程序执行流程,如果没有启用断言,那么程序就不能正确执行下去。

另外,断言语句不可以有任何边界效应,不要使用断言语句去修改变量和改变方法的返回值,如果这样当启动断言和不启动断言执行的结果会截然不同。

断言的使用时机:1.检查流程的不变性:在if-else switch-case 的预期结果之外可以加上断言做额外的检查。

SUN认证Java2程序员考试(SCJP) 试题解析(2)

SUN认证Java2程序员考试(SCJP) 试题解析(2)

SUN认证Java2程序员考试(SCJP) 试题解析(2)SUN认证Java2程序员考试(SCJP) 试题解析(2)SUN认证Java2程序员考试(SCJP) 试题解析(2)whichofthefollowinglinesofcodewillcompilewithouterror?a.inti=0;if(i){system.out.println( hi );}b.booleanb=true;booleanb2=true;if(b==b2){system.out.println(whichtwodemonstratea"hasa"relationship?(choosetwo)a.publicinterfaceperson{}publicclassemployeeextendsperson{}b.publicinterfaceshape{}publicinterfacerectandleextendsshape{}c.publicinterfacecolorable{}publicclassshapeimplementscolorable{}d.publicclassspecies{}publicclassanimal{privatespeciesspecies;}e.interfacecomponent{}classcontainerimplementscomponent{privatecomponent[]children;}解答:d,e点评:在java中代码重用有两种可能的方式,即组合(hasa 关系)和继承(isa 关系)。

hasa 关系是通过定义类的属性的方式实现的;而isa 关系是通过类继承实现的。

本例中选项a、b、c体现了isa 关系;选项d、e体现了hasa 关系。

例题6:whichtwostatementsaretruefortheclassjava.util.treeset?(ch oosetwo)a.theelementsinthecollectionareordered.b.thecollectionisguaranteedtobeimmutable.c.theelementsinthecollectionareguaranteedtobeunique.d.theelementsinthecollectionareaccessedusingauniquekey.e.theelementsinthecollectionareguaranteedtobesynchroni zed解答:a,c点评:treeset类实现了set接口。

一些SCJP考试题含答案

一些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&gt;++j) &amp;&amp; (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&gt;4B. 16/2C. 16*4D. 16&gt;&gt;2E. 16/2^2F. 16&gt;&gt;&gt;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&lt;&lt;=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&lt;2C. 3*4D. 3&lt;&lt;2E. 3*2^2F. 3&lt;&lt;&lt;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 &gt; --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历年考题

SCJP历年考题

Question No: 1Given:1. public class test (2. public static void main (String args[]) {3. int i = 0xFFFFFFF1;4. int j = ~i;5.6. }7. )What is the decimal value of j at line 5?A. 0B. 1C. 14D. –15E. An error at line 3 causes compilation to fail.F. An error at line 4 causes compilation to fail. Answer: DQuestion No: 2Given:Integer i = new Integer (42);Long 1 = new Long (42);Double d = new Double (42.0);Which two expressions evaluate to True? (Choose Two)A. (i ==1)B. (i == d)C. (d == 1)D. (i.equals (d))E. (d.equals (i))F. (i.equals (42))Answer: D, EQuestion No: 3Exhibit :1. public class test (2. private static int j = 0;3.4. private static boolean methodB(int k) (5. j += k;6. return true;6. )7.8. public static void methodA(int i) {9. boolean b:10. b = i < 10 | methodB (4);11. b = i < 10 || methodB (8); 12. )13.14. public static void main (String args[] } (15. methodA (0);16. system.out.printIn(j);17. )18. )What is the result?A. The program prints “0”B. The program prints “4”C. The program prints “8”D. The program prints “12”E. The code does not complete.Answer: BQuestion No: 4Given1. Public class test (2. Public static void main (String args[]) (3. System.out.printIn (6 ^ 3);4. )5. )What is the output?Answer: 5Question No: 5Given:1. public class Foo {2. public static void main (String [] args) {3. StringBuffer a = new StringBuffer (“A”);4. StringBuffer b = new StringBuffer (“B”);5. operate (a,b);6. system.out.printIn{a + “,”+b};7. )8. static void operate (StringBuffer x, StringBuffer y) {9. x.append {y};10. y = x;11. )12. }What is the result?A. The code compiles and prints “A,B”.B. The code compiles and prints “A,A”.C. The code compiles and prints “B,B”.D. The code compiles and prints “AB,B”.E. The code compiles and prints “AB,AB”.F. The code does not compile because “+”cannot beoverloaded for StringBuffer.Answer: DQuestion No: 6Exhibit:1. Public class test (2. Public static void stringReplace (String text) (3. Text = text.replace (‘j' , ‘i');4. )5.6. public static void bufferReplace (StringBuffer text) (7. text = text.append (“C”)8. )9.10. public static void main (String args[]} (11. String textString = new String (“java”);12. StringBuffer text BufferString = new StringBuffer (“java”);13.14. stringReplace (textString);15. BufferReplace (textBuffer);16.17. System.out.printIn (textString + textBuffer);18. }19. )What is the output?Answer: javajavaCQuestion No: 7Exhibit:1. public class test {2. public static void add3 (Integer i) }3. int val = i.intValue ( );4. val += 3;5. i = new Integer (val);6. }7.8. public static void main (String args [ ] ) {9. Integer i = new Integer (0);10. add3 (i);11. system.out.printIn (i.intValue ( ) );12. }13. )What is the result?A. Compilation will fail.B. The program prints “0”.C. The program prints “3”.D. Compilation will succeed but an exception will be thrown at line 3.Answer: BQuestion No: 8Given:1. public class ConstOver {2. public ConstOver (int x, int y, int z) {3. }4. }Which two overload the ConstOver constructor? (Choose Two)A. ConstOver ( ) { }B. Protected int ConstOver ( ) { }C. Private ConstOver (int z, int y, byte x) { }D. Public Object ConstOver (int x, int y, int z) { }E. Public void ConstOver (byte x, byte y, byte z) { } Answer: A, CQuestion No: 9Given:1. public class MethodOver {2. public void setVar (int a, int b, float c) {3. }4. }Which two overload the setVar method? (Choose Two)A. Private void setVar (int a, float c, int b) { }B. Protected void setVar (int a, int b, float c) { }C. Public int setVar (int a, float c, int b) (return a;)D. Public int setVar (int a, int b, float c) (return a;)E. Protected float setVar (int a, int b, float c) (return c;)Answer: A, CQuestion No: 10Given:1. class BaseClass {2. Private float x = 1.0f ;3. protected float getV ar ( ) ( return x;)4. }5. class Subclass extends BaseClass (6. private float x = 2.0f;7. //insert code here8. )Which two are valid examples of method overriding? (Choose Two)A. Float getVar ( ) { return x;}B. Public float getVar ( ) { return x;}C. Float double getVar ( ) { return x;}D. Public float getVar ( ) { return x;}E. Public float getVar (float f ) { return f;} Answer: B, DQuestion No: 11Which two demonstrate an “is a”relationship? (Choose Two)A. public interface Person { }public class Employee extends Person { }B. public interface Shape { }public class Employee extends Shape { }C. public interface Color { }public class Employee extends Color { }D. public class Species { }public class Animal (private Species species;)E. interface Component { }Class Container implements Component (Private Component[ ] children;)Answer: D, EQuestion No: 12Which statement is true?A. An anonymous inner class may be declared as final.B. An anonymous inner class can be declared as private.C. An anonymous inner class can implement multiple interfaces.D. An anonymous inner class can access final variables in any enclosing scope.E. Construction of an instance of a static inner class requires an instance of the enclosing outer class. Answer: DQuestion No 13Given:1. package foo;2.3. public class Outer (4. public static class Inner (5. )6. )Which statement is true?A. An instance of the Inner class can be constructed with “new Outer.Inner ()”B. An instance of the inner class cannot be constructed outside of package foo.C. An instance of the inner class can only be constructed from within the outer class.D. From within the package bar, an instance of the inner class can be constructed with “new inner()”Answer: AQuestion No 14Exhibit:1. public class enclosingone (2. public class insideone{}3. )4. public class inertest(5. public static void main (string[]args)(6. enclosingone eo= new enclosingone ();7. //insert code here8. )9. )Which statement at line 7 constructs an instance of the inner class?A. InsideOnew ei= eo.new InsideOn();B. Eo.InsideOne ei = eo.new InsideOne();C. InsideOne ei = EnclosingOne.new InsideOne();D. EnclosingOne.InsideOne ei = eo.new InsideOne(); Answer: DQuestion No 15Exhibit:1. interface foo {2. int k = 0;3. ]4.5. public class test implements Foo (6. public static void main(String args[]) (7. int i;8. Test test = new test ();9. i= test.k;10.i= Test.k;11.i= Foo.k;12.)13.)14.What is the result?A. Compilation succeeds.B. An error at line 2 causes compilation to fail.C. An error at line 9 causes compilation to fail.D. An error at line 10 causes compilation to fail.E. An error at line 11 causes compilation to fail. Answer: AQuestion No 16Given:1. //point X2. public class foo (3. public static void main (String[]args) throws Exception {4. printWriter out = new PrintWriter (new5. 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.PrintWriter;B. Include java.io.PrintWriter;C. Import java.io.OutputStreamWriter;D. Include java.io.OutputStreamWriter;E. No statement is needed.Answer: AQuestion No 17Which two statements are reserved words in Java? (Choose Two)A. RunB. ImportC. DefaultD. ImplementAnswer: B, CQuestion No 18Which three are valid declarations of a float? (Choose Three)A. Float foo = -1;B. Float foo = 1.0;C. Float foo = 42e1;D. Float foo = 2.02f;E. Float foo = 3.03d;F. Float foo = 0x0123;Answer: A, D, FQuestion No 19Given:8. int index = 1;9. boolean[] test = new Boolean[3]; 10. boolean foo= test [index];What is the result?A. Foo has the value of 0.B. Foo has the value of null.C. Foo has the value of true.D. Foo has the value of false.E. An exception is thrown.F. The code will not compile. Answer: DQuestion No 20Given:1. public class test(2. public static void main(string[]args){3. string foo = args [1];4. string foo = args [2];5. string foo = args [3];6. }7. }And command line invocation:Java Test red green blueWhat is the result?A. Baz has the value of “”B. Baz has the value of nullC. Baz has the value of “red”D. Baz has the value of “blue”E. Bax has the value of “green”F. The code does not compile.G. The program throws an exception. Answer: GQuestion No 21Given:8. int index = 1;9. int [] foo = new int [3];10.int bar = foo [index];11.int baz = bar + index;What is the result?A. Baz has the value of 0B. Baz has the value of 1C. Baz has the value of 2D. An exception is thrown.E. The code will not compile. Answer: BQuestion No 22Given:1. public class foo {2. public static void main (String[]args) {3. String s;4. system.out.printIn (“s=”+ s);5. }6. }What is the result?A. The code compiles and “s=”is printed.B. The code compiles and “s=null”is printed.C. The code does not compile because string s is not initialized.D. The code does not compile because string s cannot be referenced.E. The code compiles, but a NullPointerException is thrown when toString is called.Answer: CQuestion No 23Which will declare a method that forces a subclass to implement it?A. Public double methoda();B. Static void methoda (double d1) {}C. Public native double methoda();D. Abstract public void methoda();E. Protected void methoda (double d1){} Answer: DQuestion No 24You want subclasses in any package to have access to members of a superclass. Which is the most restrictive access modifier that will accomplish this objective?A. PublicB. PrivateC. ProtectedD. TransientE. No access modifier is qualifiedAnswer: CQuestion No 25Given:1. abstract class abstrctIt {2. abstract float getFloat ();3. )4. public class AbstractTest extends AbstractIt {5. private float f1= 1.0f;6. private float getFloat () {return f1;}7. }What is the result? A. Compilation is successful.B. An error on line 6 causes a runtime failure.C. An error at line 6 causes compilation to fail.D. An error at line 2 causes compilation to fail. Answer: CQuestion No 26Exhibit:1. public class test(2. public int aMethod()[3. static int i=0;4. i++;5. return I;6. )7. public static void main (String args[]){8. test test = new test();9. test.aMethod();10.int j = test.aMethod();11.System.out.printIn(j);12.]13.}What is the result?A. Compilation will fail.B. Compilation will succeed and the program will print “0”C. Compilation will succeed and the program will print “1”D. Compilation will succeed and the program will print “2”Answer: DQuestion No 27Given:1. class super {2. public float getNum() {return3.0f;}3. )4.5. public class Sub extends Super {6.7. )Which method, placed at line 6, will cause a compiler error?A. Public float getNum() {return 4.0f; }B. Public void getNum () { }C. Public void getNum (double d) { }D. Public double getNum (float d) {retrun 4.0f; } Answer: BQuestion No 28Which declaration prevents creating a subclass of an outer class?A. Static class FooBar{}B. Private class FooBar{}C. Abstract public class FooBar{}D. Final public class FooBar{}E. Final abstract class FooBar{}Answer: DQuestion No 29Given:1. byte [] arry1, array2[];2. byte array3 [][];3. byte[][] array4;If each array has been initialized, which statement will cause a compiler error?A. Array2 = array1;B. Array2 = array3;C. Array2 = array4;D. Both A and BE. Both A and CF. Both B and CAnswer: FQuestion No 30Exhibit:1. class super (2. public int I = 0;3.4. public super (string text) (5. I = 16. )7. )8.9. public class sub extends super (10. public sub (string text) (11. i= 212. )13.14. public static void main (straing args[]) (15. sub sub = new sub (“Hello”);16. system.out. PrintIn(sub.i);17. )18. )What is the result?A. Compilation will fail.B. Compilation will succeed and the program will print “0”C. Compilation will succeed and the program will print “1”D. Compilation will succeed and the program will print “2”Answer: AQuestion No 31Given:1. public class returnIt (2. returnType methodA(byte x, double y) (3. return (short) x/y * 2;4. )5. )What is the valid returnType for methodA in line 2?A. IntB. ByteC. LongD. ShortE. FloatF. DoubleAnswer: FQuestion No 32Given the ActionEvent, which method allows you to identify the affected component?A. GetClass.B. GetTarget.C. GetSource.D. GetComponent.E. GetTargetComponent.Answer: CQuestion No 33Which is a method of the MouseMotionListener interface?A. Public void mouseMoved(MouseEvent)B. Public boolean mouseMoved(MouseEvent)C. Public void mouseMoved(MouseMotionEvent)D. Public boolean MouseMoved(MouseMotionEvent)E. Public boolean mouseMoved(MouseMotionEvent) Answer: AQuestion No 34Exhibit: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 GridLayout (2,2));12.13. Panel p1 = new panel();14. Add(p1);15. Button b1= new Button (“One”);16. P1.add(b1);17.18. Panel p2 = new panel();19. Add(p2);20. Button b2= new Button (“Two”);21. P2.add(b2);22.23. Button b3= new Button (“Three”);24. add(b3);25.26. Button b4= new Button (“Four”);27. add(b4);28. )29. )Which two statements are true? (Choose Two)A. All the buttons change height if the frame height is resized.B. All the buttons change width if the Frame width is resized.C. The size of the button labeled “One”is constant even if the Frame is resized.D. Both width and height of the button labeled “Three”might change if the Frame is resized. Answer: C, DQuestion No 35You are assigned the task of building a panel containing a TextArea at the top, a label directly below it,and a button directly below the label. If the three components are added directly to the panel. Which layout manager can the panel use to ensure that the TextArea absorbs all of the free vertical space when the panel is resized?A. GridLayout.B. CardLayout.C. FlowLayout.D. BorderLayout.E. GridBagLayout.Answer: EQuestion No 36Which gets the name of the parent directory file “file.txt”?A. String name= File.getParentName(“file.txt”);B. String name= (new File(“file.txt”)).getParent();C. String name = (newFile(“file.txt”)).getParentName();D. String name= (newFile(“file.txt”)).getParentFile();E. Directory dir=(new File(“file.txt”)).getParentDir();String name= dir.getName();Answer: BQuestion No 37Which can be used to encode charS for output?A. Java.io.OutputStream.B. Java.io.OutputStreamWriter.C. Java.io.EncodeOutputStream.D. Java.io.EncodeWriter.E. Java.io.BufferedOutputStream.Answer: BQuestion No 38The file “file.txt”exists on the file system and contsins ASCII text.Given:38. try {39. File f = new File(“file.txt”);40. OutputStream out = new FileOutputStream(f, true);41. }42. catch (IOException) {}What is the result?A. The code does not compile.B. The code runs and no change is made to the file.C. The code runs and sets the length of the file to 0.D. An exception is thrown because the file is not closed.E. The code runs and deletes the file from the file system.Answer: AQuestion No 39Which constructs a DataOutputStream?A. New dataOutputStream(“out.txt”);B. New dataOutputStream(new file(“out.txt”));C. New dataOutputStream(new writer(“out.txt”));D. New dataOutputStream(newFileWriter(“out.txt”));E. New dataOutputStream(newOutputStream(“out.txt”));F. New dataOutputStream(new FileOutputStream(“out.txt”));Answer: FQuestion No 40What writes the text “”to the end of the file “file.txt”?A. OutputStream out= new FileOutputStream (“file.txt”);Out.writeBytes (“/n”);B. OutputStream os= new FileOutputStream (“file.txt”, true);DataOutputStream out = new DataOutputStream(os); out.writeBytes (“/n”);C. OutputStream os= new FileOutputStream (“file.txt”);DataOutputStream out = new DataOutputStream(os); out.writeBytes (“/n”);D. OutputStream os= new OutputStream (“file.txt”, true);DataOutputStream out = new DataOutputStream(os); out.writeBytes (“/n”);Answer: BQuestion No 41Given: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. return oa[0];8. }9. }When is the float object created in line 3, eligible for garbage collection? A. Just after line 5B. Just after line 6C. Just after line 7 (that is, as the method returns)D. Never in this method.Answer: DQuestion No 42Given:3. string foo = “ABCDE”;4. foo.substring(3);5. foo.concat(“XYZ”);6.Type the value of foo at line 6.Answer: ABCDEQuestion No 43Which method is an appropriate way to determine the cosine of 42 degrees?A. Double d = Math.cos(42);B. Double d = Math.cosine(42);C. Double d = Math.cos(Math.toRadians(42));D. Double d = Math.cos(Math.toDegrees(42));E. Double d = Math.cosine(Math.toRadians(42)); Answer: CQuestion No 44You need to store elements in a collection that guarantees that no duplicates are stored and all elementscan be accessed in natural order. Which interface provides that capability?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: DQuestion No 45Which statement is true for the classjava.util.HashSet?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: CQuestion No 46Given:1. public class IfTest (2. public static void main(string[]args) {3. int x = 3;4. int y = 1;5. if (x = y)6. system.out.printIn(“Not equal”);7. else8. system.out.printIn(“Equal”);9. }10. )What is the result?A. The output is “Equal”B. The output in “Not Equal”C. An error at line 5 causes compilation to fall.D. The program executes but does not print a message.Answer: CQuestion No 47Exhibit:1. public class test (2. public static void main(string args[]) {3. int 1= 0;4. while (i) {5. if (i==4) {6. break;7. )8. ++i;9. )10.11. )12. )What is the value of i at line 10?A. 0B. 3C. 4D. 5E. The code will not compile.Answer: EQuestion No 48Given: 3. int i= 1, j= 10 ;4. do (5. if (i++> --j) continue;6. ) while (i<5);After execution, what are the values for I and j?A. i = 6 and j= 5B. i = 5 and j= 5C. i = 6 and j= 4D. i = 5 and j= 6E. i = 6 and j= 6Answer: DQuestion No 49Given:1. switch (i) {2. default:310-025Leading the way in IT testing and certification tools, - 27 -3. System.out.printIn(“Hello”);4. )What are the two acceptable types for the variable i? (Choose Two)A. CharB. ByteC. FloatD. DoubleE. ObjectAnswer: A, BQuestion No 50Given:1. public class foo {2. public static void main (string[]args)3. try {return;}4. finally {system.out.printIn(“Finally”);}5. }6. )What is the result?A. The program runs and prints nothing.B. The program runs and prints “Finally”C. The code compiles, but an exception is thrown at runtime.D. The code will not compile because the catch block is missing.Answer: BQuestion No 51Exhibit:1. import java.io.IOException;2. public class ExceptionTest(3. public static void main (String[]args)4. try (5. methodA();6. ) catch (IOException e) (7. system.out.printIn(“Caught IOException”);8. ) catch (Exception e) (9. system.out.printIn(“Caught Exception”);10. )11. )12. public void methodA () {13. throw new IOException ();14. )15. )What is the result?A. The code will not compile.B. The output is caught exception.C. The output is caught IOException.D. The program executes normally without printing a message.Answer: AQuestion No 52Exhibit:1. public class test {2. public static string output = “”3.4. public static void foo(int i) {5. try {6. if(i= =1) {7. throw new Exception ();8. }9. output += “1”;10. )11. catch(Exception e) {12. output += “2”;13. return;14. )15. finally (16. output += “3”;17. )18. output += “4”;19. )20. 21. public static void main (string args[]) (22. foo(0);23. foo(1);24.25. )26. )What is the value of the variable output at line 24? Answer: 13423Question No 53Given: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 2 causes the compilation to fail.E. “Running”is printed and the program exits. Answer: DQuestion No 54Which statement is true?A. If only one thread is blocked in the wait method of an object, and another thread executes themodify on that same object, then the first thread immediately resumes execution.B. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, it is still possible that the first thread might never resume execution.C. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, then the first thread definitely resumes execution as a direct and sole consequence of the notify call.D. If two threads are blocked in the wait method of one object, and another thread executes the notify method on the same object, then the first thread that executed the wait call first definitely resumes execution as a direct and sole consequence of thenotify call.Answer: BQuestion No 55Which two CANNOT directly cause a thread to stop executing? (Choose Two)A. Calling the yield method.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 start method on another Thread object. Answer: C, DQuestion No 56Which two can be used to create a new Thread? (Choose Two)A. Extend ng.Thread and override the run method.B. Extend ng.Runnable and override the start method.C. Implement ng.thread and implement the run method.D. Implement ng.Runnable and implement the run method.E. Implement ng.Thread and implement the start method.Answer: A, DQuestion No 54Which statement is true?A. If only one thread is blocked in the wait method of an object, and another thread executes themodify on that same object, then the first thread immediately resumes execution.B. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, it is still possible that the first thread might never resume execution.C. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, then the first thread definitely resumes execution as a direct and sole consequence of the notify call.D. If two threads are blocked in the wait method of one object, and another thread executes the notify method on the same object, then the first thread that executed the wait call first definitely resumes notify call.Answer: BQuestion No 55Which two CANNOT directly cause a thread to stop executing? (Choose Two)A. Calling the yield method.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 start method on another Thread object. Answer: C, DQuestion No 56Which two can be used to create a new Thread? (Choose Two)A. Extend ng.Thread and override the run method.B. Extend ng.Runnable and override the start method.C. Implement ng.thread and implement the run method.D. Implement ng.Runnable and implement the run method.E. Implement ng.Thread and implement the start method.Answer: A, DQuestion No 57Given:1. public class SyncTest (2. private int x;3. private int y;4. private synchronized void setX (int i) (x=1;)5. private synchronized void setY (int i) (y=1;)6. public void setXY(int 1)(set X(i); setY(i);)7. public synchronized Boolean check() (returnx !=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.to allow x and y to be set separately.Answer: BQuestion No 58Exhibit:1. class A implements runable (2. int i;3. public void run () (4. try (5. thread.sleep(5000);6. i= 10;7. ) catch(InterruptedException e) {}8. )9. )10.11. public class Test {12. public static void main (string args[]) (13. try (14. A a = new A ();15. Thread t = new Thread (a);16. t.start();17.18. int j= a.i;19.20. ) catch (Exception e) {}21. )22. )Which statement al line 17 will ensure that j=10 at line 19?A. a.wait();B. t.wait();C. t.join();D. t.yield();E. t.notify();F. a.notify();G. t.interrupt();Answer: CQuestion No 59Exhibit: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 synchronized void run( ) (12. for (;;) (13. x++;14. y++;15. System.out.printIn(“x = “+ x + “, y = “+ y);16. )17. )18. )What is the result?A. An error at line 11 causes compilation to fail.B. Errors at lines 7 and 8 cause compilation to fail.C. 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”)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 twice (for example, “x=1, y=1”followed by“x=1, y=1”)E. 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=2s, y=2”)Answer: EQUESTION NO: 60Which two CANNOT directly cause a thread to stop executing? (Choose Two)A. Existing from a synchronized block.B. Calling the wait method on an object.C. Calling notify method on an object.D. Calling read method on an InputStream object.E. Calling the SetPriority method on a Thread object. Answer: A, CQUESTION NO: 61Exhibit1. public class SyncTest{2. public static void main(String[] args) {3. final StringBuffer s1= new StringBuffer();4. final StringBuffer s2= new StringBuffer();5. new Thread () {6. public void run() {。

SCJP官方题库

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试题分析2

SCJP试题分析2

B. The application compiles and print “DONE WAITING”
C. The d print “FINALLY”
D. The application compiles and print “ALL DONE”
例题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) {
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.
3. new Z();
4. }
5.
6. Z() {
7. Z alias1 = this;
8. Z alias2 = this;
9. synchronized(alias1) {
10. try {
11. alias2.wait();
12. System.out.println(“DONE WAITING”);
2. g.drawString(“Any question”, 10, 0);

SCJP考试真题和解析-Read

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)方法。

java工程师认证2023考卷

java工程师认证2023考卷

Java工程师认证2023考卷一、选择题(每题5分,共50分)A. JVMB. JDKC. JRED. GC2. 在Java中,下列哪个关键字可以用来定义接口?()A. interfaceB. classC. extendsD. implementsA. reverse()B. reverseOrder()C. reverseString()D. reverseOrderString()A. Date.now()B. Calendar.getInstance()C. LocalDate.now()D. LocalDateTime.now()A. constB. staticC. finalD. defineA. equals()B. ==A. ThreadB. RunnableC. ProcessD. ExecutorA. extendsB. implementsC. interfaceD. classA. abstractB. interfaceC. extendsD. classA. length()B. size()C. lengthD. getSize()二、填空题(每题5分,共25分)1. Java中的基本数据类型包括______、______、______、______、______、______、______和______。

2. 在Java中,______关键字用于定义一个类的成员变量或方法为静态的。

3. Java中的集合框架包括______、______、______、______等接口。

4. Java中的异常处理包括______和______两个关键字。

5. 在Java中,______类用于实现文件的读写操作。

三、简答题(每题10分,共30分)1. 请简要说明Java中的封装、继承和多态的概念。

2. 请简述Java中的垃圾收集器的作用及工作原理。

3. 请举例说明如何在Java中使用Lambda表达式。

scjp认证试题及答案

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。

SUN认证Java2程序员考试(SCJP)试题解析

SUN认证Java2程序员考试(SCJP)试题解析

SUN认证Java2程序员考试(SCJP)试题解析
佚名
【期刊名称】《软件》
【年(卷),期】2003(000)012
【摘要】前言无论你是个新手.还是程序设计方面的专家.你都会惊异于Sun公司、Java的无穷魅力。

Java带给你的并不仅仅是面向对象、开放、平台无关、易用、安全和“Write once,run anywhere“等软件开发方面的优势。

更重要的一点是。

它提供了一种新颖的表达思想的方式。

一种全新的思维模式。

随着待解决问题的规模不断膨胀.Java彻底的面向对象思想的灵活性就会凸现出来。

毋庸置疑、Java是你开发大型软件时最得心应手的利器或是你转行IT的入门首选。

【总页数】5页(P83-87)
【正文语种】中文
【中图分类】TP311.1
【相关文献】
1.2003年全国程序员考试上午试题评析 [J], 张锦祥
2.程序员资格(水平)考试题例分析 [J], 包红香
3.浅析网络程序员考试中的JavaScript试题 [J], 张锦祥
4."节约型社会"引领"节约型"中考试题——近期节能型中考试题解析 [J], 朱云
5.“节约型社会”引领“节约型”中考试题——近期节能型中考试题解析 [J], 朱云
因版权原因,仅展示原文概要,查看原文内容请购买。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

JAVA认证历年真题:SCJP考试真题和解析(2)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 value is 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";翻译下面的哪些程序片断可能导致错误。

答案B,D解析A:String类型可以直接使用+进行连接运算。

B:String是一种Object,而不是简单的字符数组,不能使用下标运算符取其值的某个元素,错误。

C:toUpperCase()方法是String对象的一个方法,作用是将字符串的内容全部转换为大写并返回转换后的结果(String类型)。

D:String类型不能进行减(-)运算,错误。

5. Which are syntactically valid statement at// point x?class Person {private int a;public int change(int m){ return m; }}public class Teacher extends Person {public int b;public static void main(String arg[]){Person p = new Person();Teacher t = new Teacher();int i;// point x}}A. i = m;B. i = b;C. i = p.a;D. i = p.change(30);E. i = t.b.翻译在// point x处的哪些申明是句法上合法的。

答案D,E解析A:m没有被申明过,不能使用。

B:虽然b是类Teacher的public成员变量,但是在静态方法中不能使用类中的非静态成员。

C:a是类Person的private成员,在类外不能直接引用。

D:change(int m)方法是public方法,并且返回一个int型值,可以通过类的实例变量p引用并赋值给一个int型变量。

E:b是类Teacher的public成员变量,且是int型,可以通过类的实例变量t引用并赋值给一个int型变量。

6. Which layout manager is used when the frame is resized the buttons's position in the Frame might be changed?A. BorderLayoutB. FlowLayoutC. CardLayoutD. GridLayout翻译当Frame的大小被改变时Frame中的按钮的位置可能被改变时使用的哪一个布局管理器。

答案 B解析A:该布局管理器将容器划分为五个部分,容器大小的改变不会影响其中的组件的位置而是影响他们的大小。

B:该布局管理器根据放入其中的组件的最合适大小调整组件的位置,根据组件放入的顺序安排,一行不能容纳时放入下一行,因此容器的大小改变可能改变组件的位置。

C:该布局管理器显示放入该容器的当前页中的组件,一次显示一个,容器大小的改变不能影响其中组件的位置。

D:该布局管理器将容器划分为固定的网格,组件加入后占据一个单元,各组件的相对位置不会因为容器的大小变化而变化,改变的只是组件的大小。

7. Given the following code fragment:1) public void create() {2) Vector myVect;3) myVect = new Vector();4) }Which of the following statements are true?A. The declaration on line 2 does not allocate memory space for the variable myVect.B. The declaration on line 2 allocates memory space for a reference to a Vector object.C. The statement on line 2 creates an object of class Vector.D. The statement on line 3 creates an object of class Vector.E. The statement on line 3 allocates memory space for an object of class Vector翻译给出下面的代码片断。

下面的哪些陈述为true(真)?A. 第二行的声明不会为变量myVect分配内存空间。

B. 第二行的声明分配一个到Vector对象的引用的内存空间。

C. 第二行语句创建一个Vector类对象。

D. 第三行语句创建一个Vector类对象。

E. 第三行语句为一个Vector类对象分配内存空间。

答案A,D,E解析SL-275中指出:要为一个新对象分配空间必须执行new Xxx()调用,new调用执行以下的操作:1.为新对象分配空间并将其成员初始化为0或者null。

2.执行类体中的初始化。

(例如在类中有一个成员声明int a=10;在第一步后a=0 ,执行到第二步后a=10)3.执行构造函数。

4.变量被分配为一个到内存堆中的新对象的引用。

8. Which of the following answer is correct to express the value 8 in octal number?A. 010B. 0x10C. 08D. 0x8翻译下面的哪些答案可以用以表示八进制值8。

答案 A解析八进制值以0开头,以0x开头的为十六进制值,八进制中不能出现数字8,最大只有7。

9. Which are not Java keywords?A. TRUEB. sizeofC. constD. superE. void翻译哪些不是Java关键字。

答案A,B解析A:不是,Java中有true,但是这也不是关键字而是字面量(literal)。

B:不是,Java中不需要这个操作符,所有的类型(原始类型)的大小都是固定的。

C、D、E都是,需要说明的是const是java中未被使用的关键字。

10. Which of the following statements are true?A. The equals() method determines if reference values refer to the same object.B. The == operator determines if the contents and type of two separate objects match.C. The equals() method returns true only when the contents of two objects match.D. The class File overrides equals() to return true if the contents and type of two separate objects match.翻译下面的哪些叙述为真。

A. equals()方法判定引用值是否指向同一对象。

B. == 操作符判定两个分立的对象的内容和类型是否一致。

C. equals()方法只有在两个对象的内容一致时返回true。

D. 类File重写方法equals()在两个分立的对象的内容和类型一致时返回true。

答案A,D解析严格来说这个问题的答案是不确定的,因为equals()方法是可以被重载的,但是按照java语言的本意来说:如果没有重写(override)新类的equals(),则该方法和 == 操作符一样在两个变量指向同一对象时返回真,但是java推荐的是使用equals()方法来判断两个对象的内容是否一样,就像String类的equals()方法所做的那样:判定两个String对象的内容是否相同,而==操作符返回true的唯一条件是两个变量指向同一对象。

从这个意义上来说选择给定的答案。

从更严格的意义来说正确答案应该只有d11. Which statements about inheritance are true?A. In Java programming language only allows single inheritance.B. In Java programming language allows a class to implement only oneinterface.C. In Java programming language a class cannot extend a class and implementa interface together.D. In Java programming language single inheritance makes code morereliable.翻译下面关于继承的哪些叙述是正确的。

相关文档
最新文档