JAVA认证历年真题:SCJP认证套题解析(3)
JAVA认证历年真题-SCJP考试真题和解析[1].doc
![JAVA认证历年真题-SCJP考试真题和解析[1].doc](https://img.taocdn.com/s3/m/9e603510b9f3f90f77c61b20.png)
JAVA认证历年真题:SCJP考试真题和解析[1]例题1: Choose the three valid identifiers from those listed beloeClassB.$byteC・ constD._okE.3_case解答:A, B, D点评:Java中的标示符必须是字母、美元符($)或下划线(_)开头。
关键字与保留字不能作为标示符。
选项C中的const是Java的保留字,所以不能作标示符。
选项E中的3_case以数字开头,违反了Java的规则。
例题2:Ho.gc()・C.Call System.gc(), passing in a reference to the object to be garbage collected・D.Call Runtime.gc().E.Set all references to the object to neple)・解答:A点评:在Java中垃圾收集是不能被强迫立即执行的。
调用System.gc()或Runtime.gc()静态方法不能保证垃圾收集器的立即执行,因为,也许存在着更高优先级的线程。
所以选项B、D不正确。
选项C的错误在于,System.gc()方法是不接受参数的。
选项E 中的方法可以使对象在下次垃圾收集器运行时被收集。
例题3:Consider the follo.out.println( "I am an int.v );4.}5.void test(String s) {6.System.out.println( “I am a string.v );7.}&9.public static void main(String argsf]) {10.Test t=neents beloethods cannot be overridden.B.Line 12 ent.C.The code an int.E. The code a String.解答:D点评:在第12行,16位长的char型变量ch在编译时会自动转化为一个32位长的int型,并在运行时传给void test(int i)方法。
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认证考试试题及答案 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认证历年真题:SCJP认证套题解析[2]
![JAVA认证历年真题:SCJP认证套题解析[2]](https://img.taocdn.com/s3/m/012b841d3968011ca300914f.png)
JAVA认证历年真题:SCJP认证套题解析[2]JAVA认证历年真题:SCJP认证套题解析[2]JAVA认证历年真题:SCJP认证套题解析[2]21、which of the following assignment is not correct?a. float f = 11.1;b. double d = 5.3e12;c. double d = 3.14159;d. double d = 3.14d.(a)题目:下面的哪些赋值语句是不对的。
浮点数的赋值是带有小数点的数字缺省是double型的,如果在浮点数后面加f或者f则是float,后面加d或者d则是double,科学计数法形式的浮点数也是double型的,而double的精度比float 高,将一个高精度的double赋值给一个低精度的float时需要进行强制类型转换,反之则不需要。
22、given the uncompleted code of a class:class person {string name, department;int age;public person(string n){ name = n; }public person(string n, int a){ name = n; age = a; }public person(string n, string d, int a) {// doing the same as two arguments version of constructor// including assignment name=n,age=adepartment = d;}}which expression can be added at the "doing the same as..." part of the constructor?a. person(n,a);b. this(person(n,a));c. this(n,a);d. this(name,age).(c)题目:给出下面的不完整的类代码:下面的哪些表达式可以加到构造方法中的"doing the same as..."处?在同一个类的不同构造方法中调用该类的其它构造方法需要使用this( )的形式,而且必须是在构造方法的第一行调用,这个和普通的方法重载调用的方式不同,普通的方法可以直接使用方法名加参数来调用,而且调用位置没有限制,因此答案a是不行的,b的语法就是错误的,d的错误在于在父类型的构造函数被调用前不能引用类的成员。
SCJP题库 带达内考点分析③

Module03-面向对象编程一、选择题:Question1Given:20.public class CreditCard{21.22.private String cardlD;23.private Integer limit;24.public String ownerName;25.26.public void setCardlnformation(String cardlD,27.String ownerName,28.Integer limit){29.this.cardlD=cardlD;30.this.ownerName=ownerName;31.this.limit=limit;32.}33.}Which is true?A.The class is fully encapsulated.B.The code demonstrates polymorphism.C.The ownerName variable breaks encapsulation.D.The cardlD and limit variables break polymorphism.E.The setCardlnformation method breaks encapsulation.Question2Which two are true?(Choose two.)A.An encapsulated,public class promotes re-use.B.Classes that share the same interface are always tightly encapsulated.C.An encapsulated class allows subclasses to overload methods,but does NOT allow overriding methods.D.An encapsulated class allows a programmer to change an implementation without affecting outside code.Question3Assume that country is set for each class.Given:10.public class Money{11.private String country,name;12.public String getCountry(){return country;}13.}and:24.class Yen extends Money{25.public String getCountry(){return super.country;}26.}27.28.class Euro extends Money{29.public String getCountry(String timeZone){30.return super.getCountry();31.}32.}Which two are correct?(Choose two.)A.Yen returns correct values.B.Euro returns correct values.C.An exception is thrown at runtime.D.Yen and Euro both return correct values.pilation fails because of an error at line25.pilation fails because of an error at line30.Question4Given:10.interface A{void x();}11.class B implements A{public void x(){}public void y(){}}12.class C extends B{public void x(){}}And:20.java.util.List<A>list=new java.util.ArrayList<A>();21.list.add(new B());22.list.add(new C());23.for(A a:list){24.a.x();25.a.y();26.}What is the result?A.The code runs with no output.B.An exception is thrown at runtime.pilation fails because of an error in line20.pilation fails because of an error in line21.pilation fails because of an error in line23.pilation fails because of an error in line25.Given:1.class SuperClass{2.public A getA(){3.return new A();4.}5.}6.class SubClass extends SuperClass{7.public B getA(){8.return new B();9.}10.}Which is true?pilation will succeed if A extendsB.pilation will succeed if B extends A.pilation will always fail because of an error in line7.pilation will always fail because of an error in line8. Question6Given:1.interface A{public void aMethod();}2.interface B{public void bMethod();}3.interface C extends A,B{public void cMethod();}4.class D implements B{5.public void bMethod(){}6.}7.class E extends D implements C{8.public void aMethod(){}9.public void bMethod(){}10.public void cMethod(){}11.}What is the result?pilation fails because of an error in line3.pilation fails because of an error in line7.pilation fails because of an error in line9.D.If you define D e=new E(),then e.bMethod()invokes the version of bMethod()defined in Line5.E.If you define D e=(D)(new E()),then e.bMethod()invokes the version of bMethod()defined in Line5.F.If you define D e=(D)(new E()),then e.bMethod()invokes the version of bMethod()defined in Line9.Given:1.public class Base{2.public static final String FOO="foo";3.public static void main(String[]args){4.Base b=new Base();5.Sub s=new Sub();6.System.out.print(Base.FOO);7.System.out.print(Sub.FOO);8.System.out.print(b.FOO);9.System.out.print(s.FOO);10.System.out.print(((Base)s).FOO);11.}}12.class Sub extends Base{public static final String FOO="bar";} What is the result?A.foofoofoofoofooB.foobarfoobarbarC.foobarfoofoofooD.foobarfoobarfooE.barbarbarbarbarF.foofoofoobarbarG.foofoofoobarfooQuestion8Given:1.class Pizza{2.java.util.ArrayList toppings;3.public final void addTopping(String topping){4.toppings.add(topping);5.}6.}7.public class PepperoniPizza extends Pizza{8.public void addTopping(String topping){9.System.out.println("Cannot add Toppings");10.}11.public static void main(String[]args){12.Pizza pizza=new PepperoniPizza();13.pizza.addTopping("Mushrooms");14.}15.}What is the result?pilation fails.B.Cannot add ToppingsC.The code runs with no output.D.A NullPointerException is thrown in Line4.Question9Given:10.public class Foo{11.public int a;12.public Foo(){a=3;}13.public void addFive(){a+=5;}14.}and:20.public class Bar extends Foo{21.public int a;22.public Bar(){a=8;}23.public void addFive(){this.a+=5;}24.}invoked with:30.Foo foo=new Bar();31.foo.addFive();32.System.out.println("Value:"+foo.a);What is the result?A.Value:3B.Value:8C.Value:13pilation fails.E.The code runs with no output.F.An exception is thrown at runtime.Question10Given:10.public class SuperCalc{11.protected static int multiply(int a,int b){return a*b;}12.}and:20.public class SubCalc extends SuperCalc{21.public static int multiply(int a,int b){22.int c=super.multiply(a,b);23.return c;24.}25.}and:30.SubCalc sc=new SubCalc();31.System.out.println(sc.multiply(3,4));32.System.out.println(SubCalc.multiply(2,2));What is the result?A.124B.The code runs with no output.C.An exception is thrown at runtime.pilation fails because of an error in line21.pilation fails because of an error in line22.pilation fails because of an error in line31.Question11Given:1.public class Team extends java.util.LinkedList{2.public void addPlayer(Player p){3.add(p);4.}5.public void compete(Team opponent){/*more code here*/}6.}7.class Player{/*more code here*/}Which two are true?(Choose two.)A.This code will compile.B.This code demonstrates proper design of an is-a relationship.C.This code demonstrates proper design of a has-a relationship.D.A Java programmer using the Team class could remove Player objects from a Team object.Question12Given:11.class ClassA{}12.class ClassB extends ClassA{}13.class ClassC extends ClassA{}and:21.ClassA p0=new ClassA();22.ClassB p1=new ClassB();23.ClassC p2=new ClassC();24.ClassA p3=new ClassB();25.ClassA p4=new ClassC();Which three are valid?(Choose three.)A.p0=p1;B.p1=p2;C.p2=p4;D.p2=(ClassC)p1;E.p1=(ClassB)p3;F.p2=(ClassC)p4;Question13Given:11.class Animal{public String noise(){return"peep";}}12.class Dog extends Animal{13.public String noise(){return"bark";}14.}15.class Cat extends Animal{16.public String noise(){return"meow";}17.}.....30.Animal animal=new Dog();31.Cat cat=(Cat)animal;32.System.out.printIn(cat.noise());What is the result?A.peepB.barkC.meowpilation fails.E.An exception is thrown at runtime.Question14Given:11.class Cup{}12.class PoisonCup extends Cup{}21.public void takeCup(Cup c){22.if(c instanceof PoisonCup){23.System.out.println("Inconceivable!");24.}else if(c instanceof Cup){25.System.out.println("Dizzying intellect!");26.}else{27.System.exit(0);28.}29.}And the execution of the statements:Cup cup=new PoisonCup();takeCup(cup);What is the output?A.Inconceivable!B.Dizzying intellect!C.The code runs with no output.D.An exception is thrown at runtime.pilation fails because of an error in line22. Question15Click the Exhibit button.1.public class SimpleCalc{2.public int value;3.public void calculate(){value+=7;}4.}And:1.public class MultiCalc extends SimpleCalc{2.public void calculate(){value-=3;}3.public void calculate(int multiplier){4.calculate();5.super.calculate();6.value*=multiplier;7.}8.public static void main(String[]args){9.MultiCalc calculator=new MultiCalc();10.calculator.calculate(2);11.System.out.println("Value is:"+calculator.value);12.}13.}What is the result?A.Value is:8pilation fails.C.Value is:12D.Value is:-12E.The code runs with no output.F.An exception is thrown at runtime.Question16Given:1.public class Blip{2.protected int blipvert(int x){return0;}3.}4.class Vert extends Blip{5.//insert code here6.}Which five methods,inserted independently at line5,will compile? (Choose five.)A.public int blipvert(int x){return0;}B.private int blipvert(int x){return0;}C.private int blipvert(long x){return0;}D.protected long blipvert(int x){return0;}E.protected int blipvert(long x){return0;}F.protected long blipvert(long x){return0;}G.protected long blipvert(int x,int y){return0;}Question17Given:11.abstract class Vehicle{public int speed(){return0;}}12.class Car extends Vehicle{public int speed(){return60;}}13.class RaceCar extends Car{public int speed(){return150;}} ......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,0pilation fails.D.150,150,150E.An exception is thrown at runtime.Question18Given:10.interface A{public int getValue()}11.class B implements A{12.public int getValue(){return1;}13.}14.class C extends B{15.//insert code here16.}Which three code fragments,inserted individually at line15,make use of polymorphism?(Choose three.)A.public void add(C c){c.getValue();}B.public void add(B b){b.getValue();}C.public void add(A a){a.getValue();}D.public void add(A a,B b){a.getValue();}E.public void add(C c1,C c2){c1.getValue();}Question19Which three statements are true?(Choose three.)A.A final method in class X can be abstract if and only if X is abstract.B.A protected method in class X can be overridden by any subclass of X.C.A private static method can be called only within other static methods in class X.D.A non-static public final method in class X can be overridden in any subclass of X.E.A public static method in class X can be called by a subclass of X without explicitly referencing the class X.F.A method with the same signature as a private final method in class X can be implemented in a subclass of X.G.A protected method in class X can be overridden by a subclass of A only if the subclass is in the same package as X.Question20Given:10.abstract class A{11.abstract void al();12.void a2(){}13.}14.class B extends A{15.void a1(){}16.void a2(){}17.}18.class C extends B{void c1(){}}and:A x=new B();C y=new C();A z=new C();Which four are valid examples of polymorphic method calls?(Choose four.)A.x.a2();B.z.a2();C.z.c1();D.z.a1();E.y.c1();F.x.a1();Question21Click the Exhibit button.1.public class GoTest{2.public static void main(String[]args){3.Sente a=new Sente();a.go();4.Goban b=new Goban();b.go();5.Stone c=new Stone();c.go();6.}7.}8.9.class Sente implements Go{10.public void go(){System.out.println("go in Sente.");}11.}12.13.class Goban extends Sente{14.public void go(){System.out.println("go in Goban");}15.}16.17.class Stone extends Goban implements Go{}18.19.interface Go{public void go();}What is the result?A.go in Gobango in Sentego in SenteB.go in Sentego in Sentego in GobanC.go in Sentego in Gobango in GobanD.go in Gobango in Gobango in Sentepilation fails because of an error in line17. Question22Given:1.class ClassA{2.public int numberOfinstances;3.protected ClassA(int numberOfinstances){4.this.numberOflnstances=numberOfinstances;5.}6.}7.public class ExtendedA extends ClassA{8.private ExtendedA(int numberOfInstances){9.super(numberOfiInstances);10.}11.public static void main(String[]args){12.ExtendedA ext=new ExtendedA(420);13.System.out.print(ext.numberOfInstances);14.}15.}Which is true?A.420is the output.B.An exception is thrown at runtime.C.All constructors must be declared public.D.Constructors CANNOT use the private modifier.E.Constructors CANNOT use the protected modifier.Question23Given: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 line2to:public int a;B.Change line2to:protected int a;C.Change line13to:public Sub(){this(5);}D.Change line13to:public Sub(){super(5);}E.Change line13to:public Sub(){super(a);} Question24Given:10.public class Hello{11.String title;12.int value;13.public Hello(){14.title+="World";15.}16.public Hello(int value){17.this.value=value;18.title="Hello";19.Hello();20.}21.}and:30.Hello c=new Hello(5);31.System.out.println(c.title); What is the result?A.HelloB.Hello Worldpilation fails.D.Hello World5E.The code runs with no output.F.An exception is thrown at runtime. Question25Click the Exhibit button.1.public class Car{2.private int wheelCount;3.private String vin;4.public Car(String vin){5.this.vin=vin;6.this.wheelCount=4;7.}8.public String drive(){9.return"zoom-zoom";10.}11.public String getInfo(){12.return"VIN:"+vin+"wheels:"+wheelCount;13.}14.}And:1.public class MeGo extends Car{2.public MeGo(String vin){3.this.wheelCount=3;4.}5.}What two must the programmer do to correct the compilation errors? (Choose two.)A.insert a call to this()in the Car constructorB.insert a call to this()in the MeGo constructorC.insert a call to super()in the MeGo constructorD.insert a call to super(vin)in the MeGo constructorE.change the wheelCount variable in Car to protectedF.change line3in the MeGo class to super.wheelCount=3; Question26Click the Exhibit button.1.public class Employee{2.String name;3.double baseSalary;4.Employee(String name,double baseSalary){=name;6.this.baseSalary=baseSalary;7.}8.}And:1.public class Salesperson extends Employee{2.double commission;3.public Salesperson(String name,double baseSalary,4.double commission){5.//insert code here6.}7.}Which code,inserted at line7,completes the Salesperson constructor?mission=commission;B.superb();commission=commission;mission=commission;superb();D.super(name,baseSalary);mission=commission;E.super();mission=commission;mission=commission;super(name,baseSalary);Question27Which 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>}Question28Which four are true?(Choose four.)A.Has-a relationships should never be encapsulated.B.Has-a relationships should be implemented using inheritance.C.Has-a relationships can be implemented using instance variables.D.Is-a relationships can be implemented using the extends keyword.E.Is-a relationships can be implemented using the implements keyword.F.The relationship between Movie and Actress is an example of an is-a relationship.G.An array or a collection can be used to implement a one-to-many has-a relationship.Question29Which two are true about has-a and is-a relationships?(Choose two.)A.Inheritance represents an is-a relationship.B.Inheritance represents a has-a relationship.C.Interfaces must be used when creating a has-a relationship.D.Instance variables can be used when creating a has-a relationship.Question30Given:10.interface Jumper{public void jump();}......20.class Animal{}......30.class Dog extends Animal{31.Tail tail;32.}......40.class Beagle extends Dog implements Jumper{41.public void jump(){}42.}.......50.class Cat implements Jumper{51.public void jump(){}52.}Which three are true?(Choose three.)A.Cat is-a AnimalB.Cat is-a JumperC.Dog is-a AnimalD.Dog is-a JumperE.Cat has-a AnimalF.Beagle has-a TailG.Beagle has-a JumperQuestion31Given:1.package geometry;2.public class Hypotenuse{3.public InnerTriangle it=new InnerTriangle();4.class InnerTriangle{5.public int base;6.public int height;7.}8.}Which is true about the class of an object that can reference the variable base?A.It can be any class.B.No class has access to base.C.The class must belong to the geometry package.D.The class must be a subclass of the class Hypotenuse.二、拖拽题:Question1:Question2:Question3:Question4:Question5:Copyright Tarena Corporation,2009.All rights reserved。
JAVA认证历年真题:SCJP认证套题解析(3)

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

Java 论证复习资料1 在Java中,对象在何种状态下会被回收?( A )A 当没有引用变量再指向该对象时B 当对象关系的引用变量消失时C 当没有任何程序再访问一个对象或对象的成员变量时D 当对象的所有成员函数都执行一遍以后2:如果catch块中包括多个异常类,这些异常类的匹配原则是什么?( C )A 接try块中程序执行的顺序,寻找最通用的异常类B 接try块中程序执行的顺序,寻找能够最精确匹配的类C 接catch块中异常类的排列顺序,寻找第一个能够匹配(也就是做出的异常对象属于catch块的异常类,或是catch块中异常类的)D 在catch块中寻找能够最精确匹配的类3 小程序的生命周期包括哪些阶段?( A )A 载入,运行,离开,返回,卸载,等阶段B 载入,运行,函数阶段C 运行阶段,停止阶段D 下载,载入,运行阶段4Jbuilder是什么?( C )A 是一种新的语言B 是一种通用的集成化软件开发环境C 是用于Java程序设计的一套集成化软件开发环境D 是一种Java平台5简单变量应当如何初始化?(B )A 简单变量需要单独进行初始化,之后才能使用B 对于简单变量,只需要给它赋值就完成了初始化C 引用变量和简单变量都需要用new关键字进行初始化了D 只有引用变量需要初始化,简单变量可以不初始化6在Java中如何保证简单变量在使用前一定被初始化过?( D )A Java程序运行时会自动判断,如果变量在使用时尚未初始化,则自动进行初始化,然后再使用B Java编译器会自动判断,如果一个变量在使用前可能尚未初始化,则编译题会提出警告,编译人员最好能够修改程序,避免此C 编程人员要确保在使用前一定初始化过,否则会得到不可预料的结果D Java编译器会自动判断,如果一个变量在使用前可能尚未初始化,则编译题会报错,要求程序必须修改7如何定义类的继承关系?( A )A 在类的定义部分使用extends关键字B 在类的定义部分使用inherited关键字C 在类的定义部分使用parent关键字D 在类的定义部分使用implement关键字8在Java中,一个类最多允许有几个直接父类?(A )A 一个B 二个C 四个D 无现制9每一个类,它是所有Java类的直接或间接的父类,这个类是( C )A Class类B System类C Object类D ng类10(有图)对下面的UML图的描述,错误的是(D )A 接口没有构造函数,因此也没有空心矩形B 虚线空心箭头表示实现接口的类C 接口用深色方框表示D 接口用浅色方框表示11Java系统如何区分字符串连接的“+”号和算术运算的加法“+”号?(D )A 在“+”号两边只要存在数字,就一定是算术加法符号B 在表达式中只要存在字符串,“+”号就是字符串连接符C 字符串之间,字符串和数字之间的“+”号是字符串连接符,数字之间的“+”号是算术加法D 表达式中如果以字符串开头,那么其后的“+”号都是字符串连接符12设置线程的优先级时需要注意哪些问题?(B )A 一个程序中至少要有一个线程设置成低优先级B 如果程序员将他的线程设为最高优先级,他就有责任保证不干扰其他应用程序的正常执行C 一个程序中最多只能有一个线程设置成高优先级D 所有的线程都要设置成最高优先级,以加快执行速度13在二进制文件的读写中,以下注意事项中错误的是(D )A 二进制文件的文件对象不能用File类,而需要用FileInputStrean和FileOutputStrean类B 在利用DataInputStrean读出文件数据的时候,并不能判断数据类型,它仅仅是根据函数的要求读入相应长度的二进制字节,再C 数据的写入和读出必须严格按照相同的顺序,否则会出现错误D 二进制文件只能读写数值,不能读写字符串14Jbuild产生的可执行程序有什么优点?( D )A 可以利用Visual Studio等其它集成平台设计Java程序B 对于没有装Java虚拟机的操作系统,也可以运行C 可执行程序可以跨平台运行D 可以直接双击程序运行,运行方便15顶级Swing容器的作用是什么?(C )A 作为其它一切组件显示的基础B 必须是入口类,作为图形界面程序的载体C 为其它Swing组件在屏幕上的绘制和处理事件提供支持D 必须是入口类,作为程序的数据存储的载体16在Java的图形界面程序中,为便于排列,组件一般放在哪里?( B )A 对话框上B 面板上C 直接放在框架上D 标签上17如何在框架中加入各种组件?( C )A 用框架的add函数直接加入组件B 将组件作为框架对象的成员变量即可C 用getContent函数获取内容窗格,在内容窗格中用add函数加入各种组件D 将组件作为入口类的成员变量即可18如何在框架中加入菜单栏?( C )A 通过框架的add函数将菜单栏直接放到框架上B 通过内容窗格的add函数将菜单栏放到内容窗格上C 通过框架的setJMenuBar函数加入菜单栏D 将菜单栏作为框架的一个成员变量19如何调整框架的大小?(A )A 利用setSize函数调整框架的大小B 框架的大小是由内部的组件大小决定的,不能直接调整框架大小C 在初始化文件(int文件)中设置D 在注册表中设置20关于卡片式布局,以下描述中错误的是(D )A 它所管理的不是组件,而是面板B 卡片式布局中一般都有好几个相同的面板,每次只能显示其中的一个面板C 作用类似于摆在一起的卡片,每次只能显示最顶上的一张D 可以一次只显示一张卡片,也可以水平、垂直排列所有卡片21关于卡片布局的面板与标签页面板的对比,以下描述中错误的是(D )A 标签页面板的灵活性不如卡片式的布局高B标签页面板有自己的图行界面,使用里起来比卡片式布局简单一些C卡片式布局没有顶端的标签页D卡片式布局与标签页面面板的一回事22如何创建一个卡片式布局的面板?( C )A 设置框架的布局管理器为卡片式布局B 创建一个CardPand类型的面板C创建一个CardLayout的对象,利用setLayout函数将布局管理器设置为该对象D创建一个CardLayout对象,将面板作为参数传递给该对象23在网络程序中,是否需要使用线程技术?(D )A 不需要,由于网络连接采用中断方式,因此不需要采用线程B 不需要,由于网络连接采用事件方式,因此不需要采用线程C 需要,由于网络连接采用事件方式,需使用独立的线程处理事件D 需要,因为网络线程中存在很多等待过程,因为需要独立的线程来等待网络消息24在Java中,对象在何种状态下被回收?(A )A当没有引用变量在指向该对象时B当对象关联的引用变量消息时C当没有任何程序再访问一个对象或对象成员变量时D当对象的所有成员函数都执行一遍以后25 简单变量和引用变量的初始化有什么区别?( A )A 简单变量的初始化只需要给它赋一个值,而引用变量的初始化需要指向一个存在的对象B 二者都需要初始化,因此它们的初始化也没有区别C 简单变量的初始化需要为它分配一个数值单元,而引用变量的初始化只需要给它赋一个值就可以了D 二者的初始化都需要指向一个存在的单元,但前者需要指向一个数值单元,后者需要指向一个对象26 以下异常中,不属于Runtime Eception的是( D )A IndexoutofaBound Exception数组下标越界异常B NullPointerException 使用未初始化的引用变量C ArithmeticException算术异常D IllegalAccessException 没有足够的权限访问其他类的成员27 如何调用JA V A小程序?( D)A双击小程序文件即可执行B在命令行为方式下键入JA V A命令来调用C在JBuilder中键入JA V A命令来调用D打开HTML文件即可调用,或者利用appletviewer命令调用28 在创建JBuilder工程的步骤中,下面哪一步是错误的?( B )A设置工程类型为“jpx”B选择最终产生的可执行文件运行的操作系统平台C设置JBuilder工程所在的目录位置D输入工程名29 while循环的含义是( C )A 反复执行花括号里的语句,直到条件表达式为真B 反复执行花括号里的语句,执行次数等于条件表达式的值C 当条件表达式为真时,反复执行花括号里的语句D 反复执行花括号里的语句,执行次数等于条件表达式的值,之后再判断条件表达式的值是否正确30 while循环和do while循环有什么区别?( C )A while循环是当条件表达式为真是,反复执行循环语句,而do while循环是反复执行循环语句,直至条件表达式为真B while循环比do while循环要少执行一次C while循环是先判断,再执行,而do while循环是先执行,后判断D while循环至少执行一次,而do while循环可能一次也不执行31 java中是否区分函数和子程序?( D )A区分,带有返回值的是函数,用“function”关键字定义B 不区分,java中的所有函数都必需要有一个返回值C区分,不带有返回值的是子程序,用“procedure”关键字定义D 不区分,没有返回值的函数相当于其它语言中的子程序32 什么是函数的返回值?( C )A 返回值在函数中通过一个与函数名称相同的变量给出B返回值在函数中通过一个特殊的“result”变量给出C返回值是函数传输给外界的数据D返回值在主程序中通过特殊的“funcName.result”变量得到33 调用函数时,如何保证传递给函数的值与函数的参数对应?( C )A 传递给函数的变量名要与函数定义时的变量名相一致B传递给函数的变量值要与函数定义时的变量的值相一致C传递给函数的参数类型、数量、先后顺序有要于函数定义中的一致D只需传递给函数的参数数量一致就可以了34 在接口定义中,不包括的内容是( A )A 实现接口的类列表B 函数定义C “interface”关键字D 接口定义和接口主体35 Java内部如何利用”+”号将字符串连接在一起?( C )A ”+”号相当于append函数,在String对象的后面添加字符串B ”+”号相当于append函数,在StringBuffer对象的后面添加字符串,因此只有StringBuffer对象能用”+”号连接符C java在用”+”号进行字符串连接的时候,是新建一个StringBuffer对象,用它按理连接所有的字符串,最后在转回String对象D ”+”号相当于append函数,在String对象的后面添加字符串,因此只有String对象才能用”+”号连接符,StringBuffer对象36线程间如何实现数据同步?(A )A 通过wait/notify函数和线程间的标志变量来实现B 通过线程间的管道通讯来实现C 通过全局变量来实现D 仅通过wait/notify函数即可37 在JAVA中,绝对路径和规范路径有什么区别?( D )A 绝对路径是按照操作系统的规范命名的路径,而规范路径是按照Java的统一规范所命名的路径B 绝对路径没有盘符,而规范路径有盘符C 绝对路径和规范路径是一致的D 绝对路径是当前路径叠加在相对路径之前,它的格式不一定规范,而规范路径是按照规范的路径格式表示的38 为了用JBuider调试程序,首先需要做什么工作( A )A 需要从菜单中选择"Rnn"--"Debug Project",以调节方式运行B 需要从菜单中选择"Rnn"--"Rnn Project"来运行程序C 需要在JBuider的命令方式下键如java命令来运行程序D 需要在命令方式下键入java命令来运行程序39 框架中包括那些窗格?( C )A 只有根窗格、内容窗格、工具栏B 只有内容窗格、工具栏C 有根窗格、分层窗格、内容窗格、工具栏、玻璃窗格等D 只有内容窗格40 以下关于框架的各窗格之间的关系的描述中,错误的是( D )A 分层窗格和玻璃窗格直属于根窗格B 内容窗格和菜单栏属于分层窗格C 玻璃窗格和内容窗格之间没有隶属于关系D 内容窗格直属于根窗格41 在消息中,常见的图标有哪几种?( D )A 确定图标,取消图标B 运行图标,停止图标C 确定图标,重试图标,取消图标D 消息图标,提问图标,警告图标,错误图标42 利用JOptionPane类可以创建哪几类对话框?( C )A 消息框、确认框、输入框、文件框等B 只能创建消息框和确认值C 消息框、确认狂,选择框、输入框等D 只能创建消息框43 如何创建消息框?( C )A 创建一个JMessageDialog对象B 创建一个类,实现JMessageDialog接口C 用JOptionPane 类的shouMessageDialog函数创建D 创建一个JDialog对象,再在其中放一个确认按钮44 在流式布局中,如果设置组件的对齐方式有对齐,组件横向间隙为18,纵向间隙为12,该用什么语句来实现?( D)A panel.setAlignmentX(JComponent.RIGHT)B layout1. setAlignmentX(JComponent.RIGHT)C button1. setAlignmentX(JComponent.RIGHT)D panel1.setLayout(new FlowLayout.TRAILING,18,12))45 关于表格型布局的特点,以下描述中错误的是( A )A 每一个中可以放一个或多个组件B 表格布局管理器将容器变成一个表格,其中每一格的大小是完全相同的C 每个组件都放在其中一格中D 如果拉大框架,则每一格和格里的组件也会相应变大46 关于表格型布局的特点,以下描述中错误的是(A)A 每一格中可以放一个或多个组件B 表格型布局管理器将容器变成一个表格,其中每一格的大小是完全相同的C 每个组件都放在其中一格中D 如果拉大框架,则每一格和格里的组件也会相应的变大47 建立客户端时需要考虑哪些问题?( C )A 必须用try…catch块捕获IOException异常B 连接客户端会很慢,因此必须单独打开一个线程进行连接C 当连上远程计算机时,会自动触发一个网络连接事件,需要用相应的事件处理函数进行处理D 网络连接采用中断形式,因此需要增加中断处理函数二多项选择题1以下的Java程序代码中,错误的行是( A B)此题与题目录入者的可能的手误有很大关系,要注意原题的大小写等。
一些SCJP考试题含答案.

一些SCJP考试题含答案Leading the way in IT testing and certification tools,QUESTION NO: 92 Given:1. String foo = “blue”;2. Boolean[]bar = new Boolean [1];3. if (bar[0] {4. foo = “green”;5. }What is the result?A. Foo has the value of “”B. Foo has the value of null.C. Foo has the value of “blue”D. Foo has the value of “green”E. An exception is thrown.F. The code will not compile.Answer: FQUESTION NO: 93Exhibit:1. public class X {2. public static void main (String[]args {3. String s1 = new String (“true”;4. Boolean b1 = new Boolean (true;5. if (s2.equals(b1 {6. System.out.printIn(“Equal”;7. }8. }9. }What is the result?A. The program runs and prints nothing.B. The program runs and prints “Equal”C. An error at line 5 causes compilation to fail.D. The program runs but aborts with an exception. Answer: AQUESTION NO: 94Given:1. public class Foo {2. public static void main (String []args {3. int i = 1;4. int j = i++;5. if ((i>++j && (i++ ==j {6. i +=j;7. }9. }What is the final value of i?A. 1B. 2C. 3D. 4E. 5Answer: BQUESTION NO: 95Exhibit:1. public class X {2. public static void main (String[]args {3. string s = new string (“Hello”;4. modify(s;5. System.out.printIn(s;6. }7.8. public static void modify (String s {9. s += “world!”;10. }11. }What is the result?E. The program runs and prints “Hello”F. An error causes compilation to fail.G. The program runs and prints “Hello world!”H. The program runs but aborts with an exception. Answer: A QUESTION NO: 96Which two are equivalent? (Choose TwoA. 16>4B. 16/2C. 16*4D. 16>>2E. 16/2^2F. 16>>>2Answer: D, EQUESTION NO: 97Exhibit:1. public class X {2. public static void main (String[]args {3. int [] a = new int [1]4. modify(a;5. System.out.printIn(a[0];7.8. public static void modify (int[] a {9. a[0] ++;10. }11. }What is the result?A. The program runs and prints “0”B. The program runs and prints “1”C. The program runs but aborts with an exception.D. An error “possible undefined variable” at line 4 causes compilation to fail.E. An error “possible undefined variable” at line 9 causes compilation to fail. Answer: BQUESTION NO: 98Given:13. public class Foo {14. public static void main (String [] args {15. StringBuffer a = new StringBuffer (“A”;16. Strin gBuffer 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. Th e 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 TwoA. 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[]args6. 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(MouseEventB. Public boolean mouseDragged(MouseEventC. Public void mouseDragged(MouseMotionEventD. Public boolean MouseDragged(MouseMotionEventE. Public boolean mouseDragged(MouseMotionEvent Answer: AQUESTION NO: 109Given:1. String foo = “base”;2. foo.substring(0,3;3. foo.concat(“ket”;4. foo += “ball”;5.Type the value of foo at line 8.Answer: BASEBALLQUESTION NO 110Given:1. public class Test {2. public static void leftshift(int i, int j {3. i<<=j;4. }5. public static void main(String args[] {6. int i = 4, j = 2;7. leftshift(i, j;8. System.out.printIn(i;9. }10. }What is the result?A. 2B. 4C. 8D. 16E. The code will not compile. Answer: BQUESTION NO 111Given:1. public class Foo {2. private int val;3. public foo(int v (val = v; }4. public static void main (String [] args {5. Foo a = new Foo (10;6. Foo b = new Foo (10;7. Foo c = a;8. int d = 10;9. double e = 10.0;10. }11. }Which three logical expression evaluate to true? (Choose ThreeA. (a ==cB. (d ==eC. (b ==dD. (a ==bE. (b ==cF. (d ==10.0Answer: 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: B QUESTION NO 114Which two are equivalent? (Choose TwoA. 3/2B. 3<2C. 3*4D. 3<<2E. 3*2^2F. 3<<<2Answer: C, DQUESTION NO 115What is the numerical range of a char?A. 0 . . . 32767B. 0 . . . 65535C. ?256 . . . 255D. ?32768 . . . 32767E. Range is platform dependent. Answer: BQUESTION NO 116Given:1. public class Test {2. public static void main (String []args {3. unsigned byte b = 0;4. b--;5.6. }7. }What is the value of b at line 5?A. -1B. 255C. 127D. Compilation will fail.E. Compilation will succeed but the program will throw an exception at line 4. Answer: DQUESTION NO 117Given:1. public class Foo {2. public void main (String [] args {3. system.out.printIn(“Hello World.”;4. }5. }What is the result?A. An exception is thrown.B. The code does no compile.C. “Hello World.” Is print ed 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 TwoA. 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 labele d “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 TwoA. 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 TwoA. 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 TwoA. 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 = (Fooo;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 TwoA. 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, 3Answer: 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 FourA. ErrorB. EventC. ObjectD. ExceptionE. ThrowableF. RuntimeExceptionAnswer: A, D, E, FQUESTION NO 133Given:1. public class ForBar {2. public static void main(String []args {3. int i = 0, j = 5;4. tp: for (;; {5. i ++;6. for(;;7. if(i > --j break tp;8. }9. system.out.printIn(“i = ” + i + “, j = “+ j;10. }11. }What is the result?A. The program runs and prints “i=1, j=0”B. The program runs and prints “i=1, j=4”C. The program runs and prints “i=3, j=4”D. The program runs and prints “i=3, j=0”E. An error at line 4 causes compilation to fail.F. An error at line 7 causes compilation to fail.Answer: AQUESTION NO 134Which two can directly cause a thread to stop executing? (Choose TwoA. 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: C QUESTION 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: F QUESTION 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 TwoA. 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 TwoA. 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 TwoA. 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 TwoA. 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。
(完整版)Java程序设计习题附答案(三)

第三部分面向对象程序设计1、引用数据种类变量拥有基本属性为( A 、变量名 B、数据种类ABCD )C、储存单元D、变量值。
2、面向对象技术的特征是(ACD )A 、继承性B 、有效性C、多态性3、以下哪个命题为真?(C)D 、封装性。
A、全部类都一定定义一个结构函数。
B、结构函数一定有返回值。
C、结构函数能够接见类的非静态成员。
D、结构函数一定初始化类的全部数据成员。
4、对于子类与父类关系的描绘正确的选项是(ACD )A、子种类的数据能够隐式变换为其父种类的数据;B、父种类的数据能够隐式变换为其子种类的数据;C、父种类的数据一定经过显示种类变换为其子种类的数据;D、子种类实例也是父种类的实例对象。
5、以下哪一项说法最好地描绘了Java 中的对象?( C)A 、对象是经过import 命令引入到程序中的全部事情B、对象是方法的会合,这些方法在小程序窗口或应用程序窗口中产生图形元素,或许计算和返回值C、对象是一种数据结构,它拥有操作数据的方法D、对象是一组拥有共同的结构和行为的类6、下边哪个重点字不是用来控制对类成员的接见的?(C)A 、 public B、 protected C、 default D、 private7、 Java 语言正确的常量修饰符应当是(D)A 、 final B、 static final C、 static D、 public static final ;8、接口的全部成员域都拥有public、static和final属性。
9、接口的全部成员方法都拥有public和abstract属性。
10、编译以下源程序会获得哪些文件?(C)class A1{}class A2{}public class B{public static void main(String args[]){}}A) 只有B)只有 A1.class 和 A2.class 文件C)有、 A2.class 和 B.class 文件D)编译不行功11、以下哪一种说法是正确的?( A )A、私有方法不可以被子类覆盖。
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";翻译下面的哪些程序片断可能导致错误。
JAVA认证真题35道SCJP考试真题精解

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

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

C. static final int[] a = new int[2] { 100,200 };
D. static final int[] a; static void init() { a = new int[3]; a[0]=100; a[1]=200; }
A. Line 57 will print the value 2. B. Line 57 will print the value 3. C. Compilation will fail because of an error in line 55. D. Compilation will fail because of an error in line 56.
13. int[] someArray = (int[])obj; 14. for (int i: someArray) System.out.print(i +" ") 15. } ‘What is the result?
A. 1 2 3 B. Compilation fails because of an error in line 12. C. Compilation fails because of an error in line 13. D. Compilation fails because of an error in line 14. E. A ClassCastException is thrown at runtime.
Question 13 Given: 11. public static void main(String[] args) { 12. Object obj =new int[] { 1,2,3 };
SUN公司SCJP题库讲解学习

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

1、class Scoop{static int thrower() throws Exception { return 42; }public static void main(String[] args) {try{int x = thrower();}catch(Exception e) {x++;}finally {System.out.println(“x = ” + ++x);}What is the result?A. x = 42B. x = 43C. x = 44D. Compilation failsE. The code runs with no output答案:D变量x的作用域只在try块内,而不在catch和finally里2、what is the result when you compil and run the following code? D class Example{static int myArg=1;public static void main(String [] args){Int myArg;System.out.println(myArg);}}Select all right answer:A、this code compiles and displays 0 in the statndard output when runB、t his code compiles and displays 1 in the statndard output when runC、t his code does not compile because you can‟t define a local variable names the same as staticvariableD、this code doesn‟t compile because the local vriable is used before it is initialized局部变量myArg;在使用前必须被初始化3、what is the result when you compile and run the following code? D class Example{static int i;public static void main(String [] args){System.out.println(i);}}Select all right answer:A、Error variable I may not have been initializedB、N ullC、1D、0属性有默认值4、what is the result when you compile and run the following code? B class Example{static boolean Paddy;public static void main(String [] args){System.out.println(Paddy);}}Select all right answer:A、compile time error;B、c ompilation and output of false;C、c ompilation and output of trueD、compilation and output of null属性有默认值5、what is the result when you compile and run the following code? D class Example{public static void main(String [] args){ int i=012;int j=034;int k=056;int l=078;System.out.println(i);System.out.println(j);System.out.println(k);}}Select all right answer:A、p rints 12,34 and 56B、prints 24,68and 112C、prints 10,28and 46D、c ompilation error八进制数前加0,但l表示的数超过八进制数的范围了6、what is the result when you compile and run the following code? Aclass Example{ void fun(){static int i=0;}public static void main(String [] args){ Example obj=new Example();obj.fun();obj.fun();}}Select all right answer:A、compilation errorB.run time errorC、1D、2Static不能修饰局部变量7、what is the result when you compile and run the following code? D class Example{public static void main(String [] args){ String elements[ ]={“for”,”tea”,”too”};String first=(elements.length>0)?elements[0]:null;System.out.println(first);}}Select all right answer:pilation fails;B.an exception thrown at runtimeC.prints:nullD.prints:for考察数组的length属性和条件运算符8、what is the result when you compile and run the following code? A,C,D String s=“hello”;String t=”hello”;char c[]={…h‟,‟e‟,‟l‟,‟l‟,‟o‟};Select all right answer:A s.equals(t);B t.equals(c)C s==tD t.equals(new String (“hello”))E t==c==比较的是两端操作数是否是同一个对象,由于s和t并非用new创建,因此指向内存池中同一字符串常量,故C对,equals比较两个String内容是否相等9、Given the following code: E class Example{public static void main(String [] args){If(args.length==1 | args[1].equals(“test”))System.out.println(“test case”);ElseSystem.out.println(“production ”+arg[0]);}}And the command-line invocation: java Example live2What is the result?select all right answer?A、test caseB、productionC、test case live2D、complilation failsE、An xception is throw at runtime考察逻辑短路运算,但|不属于逻辑短路,尽管args.length==1的结果为true,但后边的仍需计算,但因为数组只接受了一个参数,故arg[1]导致异常10、what is the result when you compile and run the following code? Cclass Example{public static void main(String [] args){ byte B=10;byte D=12;byte I=B*D;}}Select all right answer:A、the code will compile and runB、c ompile time error while declaring variableC、c ompile time error while multiplicationD、none of the above说明:二元运算,若一个为float double 或long,则另一个也转换成对应的,否则都转换成int11、what is the result when you compile and run the following code? Dclass Example{void test(int i){ System.out.println(“I am a Int”);}void test(String s){ System.out.println(“I am a String”);}public static void main(String [] args){ Example t=new Example();char ch=‟y‟;t.test(ch);}}Select all right answer:A not compile,because void methods can‟t be overriddenB not compile,because there is no version of test() that rakes a char argumentC the code will complile but will throw an exceptionD the code will compile and produce the following output: I am an int因为char的表示范围小于int,所以和test(int i)匹配上12、what is the result when you compile and run the following code? Dclass Example{static final long tooth=343L;static long doIt(long tooth){System.out.println(++tooth+””);return ++tooth;}public static void main(String [] args){ System.out.println(tooth+”“);final long tooth=340L;new Example().doIt(tooth);System.out.println(tooth);}}Select all right answer:A 343 340 340B 343 340 342C 343 341 342D 343 341 340E 343 341 343F compilation failsG An exception in thrown at runtime本题考察变量的使用范围:三个tooth同名变量,第一个是类成员,第二个是形参在方法内doIt().第三个是main的局部变量,范围在main内。
SCJP考试真题和解析-Read

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

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。
-【优秀文档】Java认证模考试题及答案.doc

Java认证模考试题及答案Question: 1Given the following code:class Test{private int m;public static void fun() {// some code...}}How can the member variable m be accessible directly in the method fun()?A.change private int m to protected int mB・ change private int m to public int mC.change private int m to static int mD.change private int m to int mExplanation:If the variable m is changed to be a static variable it can be accessible in the method fun() for this method is a static member method. Correct Answer: C 1 of 60Question: 2Which methods are correct overloading methods of the following method: public void example(){..・}A.public void example( intB.public int cxamplc(){...}C.public void example2(){..JD.public int example (int m, float f){・•・}Explanation:The overloading methods must have the same names・ If only the return type of the methods are different it is sufficient tell the methods from each other. The arguments of the methods must be different enough to determine which method to call.Correct Answer: A,D 2 of 60Question: 3中国公务2004-5-27 22:14:08Given the following fragment of code: public class Base{int w, x, y ,z;public Base(int a.int b){ x=a; y=b;}public Base(int a, int b, int c, int d){ // assignment x=a, y=b w=d;Which expressions can be used at the point of// assignment x=a, y=b?A.Basc(a,b);B.x=a, y=b;C.x=a; y=b;D.this(a,b);Explanation:In the second constructor, the call this(a,b) passes control the version of the constructor that takes two int arguments.Correct Answer: C,D 3 of 60Question: 4Given the following definition:String s = story;Which of the following expressions are legal?A.s += books;B.chare = s[l];C.int len = s」ength;D・ String t = s.toLowerCase();Explanation:Answer B is not correct for String is a class and can'T be treated as an array of char. Answer C is not correct for s」cngth() should be used, not s」ength・Correct Answer: A,D 4 of 60Question: 5What is the return value of the main() method in Java?A.StringB.intC・ charD.voidExplanation:The main() method in Java returns void・Correct Answer: D 5 of 60Question: 6Which are the valid identifiers in Java?A.fieldnameB.superC・ 3numberD. #numberE・ SnumberExplanation:Valid identifiers in Java can start with a letter, underscore (_), or dollar sign ($), but not with digits or oth er signs• And identifiers can not be keywords.Correct Answer: A,E 6 of 60Question: 7Which are valid Java keywords?A.constB.NULLC.falseD.thisE.nativeExplanation:All the keywords in Java arc lowercase, goto and const arc keywords that arc not used in Java programming language.Correct Answer: A,C,D,E 7 of 60Question: 8 2005-8-16 3:14:42Which are valid integral expressions in Java?A.22B.0x22C.022D.22HExplanation:In Java integral has three forms: decimal, octal and hexadecimal. Octal values start with a zero and hexadecimal values start with Ox.Correct Answer: A,B,C 8 of 60Question: 9Which one of the following ranges of short is correct?Explanation:The length of the short data is 16 bits. The range of short isThe length of the short data is 16 bits. The range of short isCorrect Answer: D 9 of 60Question: 1()Which one of the following ranges of byte is correct?Correct Answer: B 10 of 60Question: 11 2004-5-27 22:14:08Given the following fragment of code, what arc results of i and j after execution?int i = 1;intj;j = i卄;A.1, 1B.1,2C.2, 1D.2,2Explanation:Pay attention to the position of the operator ++・ In this question, first j is assigned to 1, then the value of i is added to 2. Correct Answer: C 11 of 60Question: 12Which of the following statements are true?A.>> is the arithmetic right shift operator.B.» is the logical right shift operator.C.»> is the arithmetic right shift operator.D・ >>> is the logical right shift operator.Explanation:There are two right shift operators in Java. They are » and »>. » is the arithmetic(signed) right shift operator and »> is the logical(unsigncd) right shift opcrato匚Correct Answer: A,D 12 of 60Question: 13Which of the following assignments are legal?A.float a = 2.0B.double b = 2.0C.int c = 2D.long d = 2Explanation:In Java the default data type of floating point is double, not float. The assignment from double to float requires an explicit cast. Correct Answer: B,C,D 13 of 60Question: 14Which one of the following arguments is the correct argument of the main() method?A.char args[]B.char args[][]C・ String arg [JD.String argsExplanation:The argument of the main() method is an array of String. Then only answer C is an array of String・Correct Answer: C 14 of 60Question: 15Which one of the following is correct to create an array?A.float f[][] = new float[6][6J;B.float [Jf[J = new float[6][6];C.float ff][] = newD.float [][]f = new float[6][6];E.float [][]f = new float[6][];Explanation:In Java the declaration format allows the square brackets to be at the left or right of the variable name・ But the new float[][6] is illegal.Correct Answer: A,BQ,E 15 of 60Question: 16Given the following expression: int mLJ 二{0, 1,2, 3, 4, 5, 6 };Which result of the following expressions equals to the number of the array elements?A.m」cngth()B.m」engthC.m.length()+lD.m」ength+1Explanation:The number of elements in an array is stored in the length attribute in the array object.Correct Answer: B 16 of 60Question: 17Given the following command to run a correct class: java MyTcst a b cWhich statements are true?A.args[0] = MyTest a b cB.argsfO] = MyTestC.args[0] = aD.args[l]= VExplanation:The three arguments a b c are stored in the args fl array of the main() method. Then args[()]= a, args[ll= b, args[2]= c. Correct Answer: C 17 of 60Question: 18Given the following code:public class Test{long a[] = new long[10];public static void main ( String arg[]) {System.out.println (a[6_|);}}Which statement is true?A.Output is null.B.Output is 0.C.When compile, some error will occu匚D.When running, some error will occu匚Explanation:When an aiTay is created the members of the array is initialized・ In this case all the elements are initialized to be 0. Correct Answer: B 18 of 60ucstion: 19Given the following fragment of code:boolean m = true;if ( m = false )System.out.println(False);elseSystcm.out.println(Truc);What is the result of the execution?A.FalseB.TrueC.NoneD.An error will occur when running・Explanation:=is the assignment operato匚==is the compare operator. In this question the value of false is assigned to the variable m.Correct Answer: A 19 of 60Question: 20Given the following code:public class Test{public static void main(String arg[]){int i = 5;do {System.out.println(i);} while (-i>5)System.out.println( "finished");}}What will be output after execution?A.5B.4C.6D.FinishedE.NoneExplanation:The expressions in the block of do/while loop will be executed at least once• If the condition of this loop is not met the loop will stop after once execution, otherwise, it will continue to loop until the condition is no met.Correct Answer: AQ 20 of 60Question: 21What will be output after execution of the following code:outer: for(int i=0;iv3; i++)inner: for(int j=0;j<2;j++)if(j==l) continue outer;System.out.println(j+ ?and ?+i);A.0 and 0B.0 and 1C.0 and 2D.1 and 0E.1 and 1F. 1 and 2G.2 and 0H.2 and 1I. 2 and 2Explanation:The continue statement is used to skip over and jump to the end of the loop body. Then if j equals to 1 it will jump to the end of the inner loop body.Correct Answer: A,B,C 21 of 60Question: 22Given the following code:switch (m){case 0: System.out.println(Condition 0);case 1: System.out.println(Condition 1);case 2: System.out.println(Condition 2);case 3: System.out.println(Condition 3);brcak;default: System-out.println(Other Condition);}Which values of m will cause Condition 2 is output?A.OB.1C.2D.3E.4F.NoneExplanation:In the block of switch, if there is no break sentence in one case the following sentences will be executed.Correct Answer: A,B,C 22 of 60Question: 23Which method is called when the browser returns to the page containing the applet after moving to another URL?B.start()C.stop()D.destroyOExplanation:The start() runs whenever the applet becomes visible, such as when the browser returns to the page containing the applet after moving to another URL or the browser is restored after being iconizecLCorrect Answer: B 23 of 60Question: 24If a thread calls the wait() method, which methods can make it continue to run?A.join()B.resume()C.notifyOD.notifyAll()E.high priority thread is readyExplanation:If a thread issues a wait() call it will pause execution until another thread issues a notifyO or notifyAll() call. The pair of the methods are provided for thread communication.Correct Answer: C,D 24 of 60Question: 25Which method is used to define the execution body of a thread?A.start()B.init()C.run()D.main()E・ synchronized()Explanation:The threads will always begin executing at the run() method, which contains the definition of the execution body.Correct Answer: C 25 of 60Question: 26Which keyword is used to allow interaction with the lock flag?A.nativeB.staticC.synchronizedD.abstractExplanation:Every object has a lock Hag. The synchronized keyword enables interaction with the flag, which allow exclusive access to that object ・Correct Answer: C 26 of 60Question: 27Which modifiers are legal in Java?A.privateB.publicC.protectedD.protectE.friendExplanation:The public, private, protected and no modifier are legal modifiers. The friend and protect are illegal in Java・Correct Answer: A,B,C 27 of 60Question: 28If a member variable of a class can be accessible only by the same package, which modifier should be used?A.privateB・ publicC・ protectedD.no modifierE.finalExplanation:No modifier is the default access level. The default modifier means to be accessible by the classes in the same package. Correct Answer: D 28 of 60Question: 29Which modifier should be used to define a constant member variable?A.staticB.finalC.abstractD.No modifier can be usedExplanation:If a member variable is marked as final, it is a constant.Correct Answer: B 29 of 60Question: 30Which one of the following is correct to declare a native method?A.public native void test();B・ public native void test(){}C.public void native test();D.public native tcst(){}Explanation:A native method can not have a method body. And the keyword native can't be put in front of the return value of the method・Correct Answer: A 30 of 60Question: 31Given the following definition of a class:public class Test {private float f = 1.0;int m = 12;static int n=l;public static void main(String arg[J) {Test t = new Test();// some code..・}}Which of the following usage are legal?A.t.fB.this.nC.Test.mD.Test.nExplanation:The f and m arc instance variables・ They should be accessed through an object. The n is a class variable and it should be accessed through the class name.Correct Answer: A,D 31 of 60Question: 32Given the following code:1)class Example {2)String str;3)public Example(){4)str= example;5)}6)public Example(String s){7)str=s;8)}9)}10)class Demo extends Example {11)}12)public class Test{13)public void f () {14)Example ex = new Example(Good);15)Demo d = new Dcmo(Good);⑹}Which line will cause an error?A.line 3B.line 6C.line 1()D.line 14E.line 15Explanation:The Demo class doesn't have a constructor that takes one String argument. The call on line 15 will cause an eno匚Correct Answer: E 32 of 60Question: 33Given the following class definition in one source file:class Base {public Base (){ //... }public Base (int m ){ 〃…}protected void fun( int n ){ 〃…}}public class Child extends Base{// member methods}Which methods can be added into the Child class correctly?A.private void fun( int n ){ II...}B.void fun (int n ){ //...}C.protected void fun (int n ) { 〃…}D.public void fun (int n ) { II...]E.public m(){ II... }Explanation:In the subclass Child the overriding methods cannot be less accessible than the method they overrides in the super class Base. Correct Answer: CQ 33 of 60Question: 34Which statements are correct?A.In Java single inheritance is allowed, which makes code more reliable.B・ A subclass inherits all methods (including the constructor ) from the superclass・C・ A class can implement as many interfaces as needed・D. When a class implements an interface, it can define as many methods of the interface as needed. Explanation:A subclass inherits all methods except the constructor from the superclass・ When a class implements an interface, it can define all the methods of the interface.Correct Answer: A,C 34 of 60Question: 35In the Tcst.java source file, which arc correct class definitions?A.public class test {public int x = 0;public test(int x){this.x = x;}}B.public class Test{public int x=0;public Test(int x) {this.x = x;}}C.public class Test extends Tl, T2 {public int x = 0;public Test (int x) {this.x = x;}}D.public class Test extends T1 {public int x=0;public Test(int x){this.x = x;}}E.protected class Test extends T2{public int x=();public Test(int x){this.x=x;}}Explanation:In the Test.java source file the class name should be Test, not test, for it is case-sensitive in Java. One class should have not more than one superclass. The protected modifier can not be put in front of the class・Correct Answer: B,D 35 of 60Question: 36The Person, Student and Teacher are class names・ These classes have the following inheritance relation as shown below: PersonIIStudent TeacherThere is the following expression in a Java source file:Person p = new Student();Which one of the following statements arc true?A.The expression is legal.B・ The expression is illegal.C.Some errors will occur when compile・pile is correct but it will be wrong when running・Explanation:The objects cast up the class hierarchy are always permitted. A reference of superclass can refer to an object of subclass.Correct Answer: A 36 of 60Question: 37The Person, Student and Teacher are class names・ These classes have the following inheritance relation as shown below: PersonIIStudent TeacherIn Java source file a specific method has an argument. In order to handle all these classes in this method which type of argument of this method should be used?A.PersonB.StudentC.TeacherD.ObjectE.None of them can be used.Explanation:The objects of subclasses can pass around using references to their parent classes. The Person and Object arc superclasses of the Teacher and Student classes・ The type of the argument of the method should be Person or Object・Correct Answer: A,D 37 of 60Question: 38The Person, Student and Teacher arc class names・ These classes have the following inheritance relation as shown below: PersonStudent TeacherPerson p = new Tcachcr();Which of the following expressions return true?A.p instanceof TeacherB.p instanceof StudentC.p instanceof PersonD.None of them returns trueExplanation:The instanceof operator is used to test the type of an object. Because the reference p refers to a Teacher object and the Teacher is a subclass of the Person class the expressions in answer A and C will return true.Correct Answer: A,C 38 of 60Question: 39Given the following code:public class Tcst{public static void main(String args[]){String str=new String(World);char ch[]={,H,,,e,,,r,T;o,};changc(str,ch);System.out.println(str + and + ch);}public static void change(String str, char ch[J){str=Changcd; ch[0]=,C';}}What is the result after execution?A.World and HelloB.World and CelloC.Changed and HelloD.Changed and CelloExplanation:Java passes arguments only by value・ When an object instance is passed as an argument to a method, the value of the argument is a reference to the objec匚The contents of the object can be changed in the called method, but the object reference is never changed ・Correct Answer: B 39 of 60Question: 40Given the following fragment of code:Double dl = new Double( 1.0);Double d2 = new Double(l .0);Float f = new Float(l.OF);A.dl == d2B.dl.equals(d2)C.dl =fD.f.equals(dl) Explanation:The == operator determine if reference values refer to the dame object. The equals() method is overridden in the Double, Float, String etc・ class to compare the content of the objects・Correct Answer: B 40 of 60Question: 41Given the following code: public void fun (){int i;try{i=System.in.read ();System.out.println(Location 1);} catch (IOExccption c) {System.out.println(Location 2);} finally {System.out.println(Location 3);}System.out.println(Location 4);}If an lOException occurs, what will be printed?A.Location 1B.Location 2C.Location 3D.Location 4Explanation:When an IOExccption occurs the Location 1 is skipped・ Fist the exception is caught and the Location 2 is printed・ Then the Location 3 in the block of finally is printed. Finally, the Location 4 is printed.Correct Answer: B,C,D41 of 60Question: 42If the method func() is allowed to throw out the lOException, which declaration of this method can used?A.public int func(int i)B.public int func(int i) throw IOExccptionC.public int func(int i) throw ExceptionD.public int func(int i) throws IOExccptionE.public int func(int i) throws ExceptionExplanation:The throws keyword should be used when declaration of a method. In the declaration IOExccption and its superclass Exception can be used.Correct Answer: D,E 42 of 60Question: 43Given the following expression:String f = null;Which of the following expressions will throw an exception?A.f == null I f.length()>10B.f != null I f.length()>10C.f == null II f.lcngth()>10D.f != null II f.length()>10Explanation:The operator II perform short-circuit logical expressions. If the first subexpression is true the second subexpression is skipped, for the entire expression is true when the first subexpression is true. The operator I doesn't perform short-circuit logical expressions. Both of the two subexpressions are performed. Because the f is null the expression f」ength() will cause an exception is thrown・Correct Answer: A,B,D 43 of 60Question: 44Which of the following can be parts of the Java source file Calculation 1 java?A.public class Calculation! {//...}B・ import java.io.*;C.package myPackage;D.import java.awt.*;E.s tatic class Arg{//••・}F.class Calcu{//...}G.public class Calculation2{//..・}Explanation:The static can not be a modifier before the keyword class・ A Java source file can have only one public class.Correct Answer: A,B,C,D,F 44 of 60Question: 45Which one of the following containers must be added to another container?A.WindowB.FrameC.DialogD.PanelExplanation:The Window, Frame and Dialog are free-standing windows. But the Panel is contained within another container, or inside a Web browser's window・Correct Answer: D 45 of 60Question: 46Which of the following classes are layout managers in Java?A.CardLayoutB.BorderLayoutC・ PanelLayoutD.GridLayoutE.BagLayoutExplanation:There are five layout managers in Java・They are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBaglayout. Correct Answer: A,B,D 46 of 60Question: 47A Button is positioned in a Frame. Only height of the Button is affected by the Frame while the width is not. Which layout manager should be used?A.FlowLayoutB.CardLayoutC・ North and South of BorderLayoutD.East and West of BorderLayoutE.GridLayoutExplanation:In the East and West of BorderLayout only the height of the component is affected when the Frame is resized・Correct Answer: D 47 of 60Question: 48A Button is positioned in a Frame. Its size is not affected when the Frame is resized. Which layout manager should be used?A.FlowLayoutB.CardLayoutC.North and South of BorderLayoutD.East and West of BorderLayoutE・ GridLayoutExplanation:The size of the components is not constrained by the FlowLayout manage匚When the area is resized the size of these components is not changed.Correct Answer: A 48 of 60Question: 49Which methods can get the event source in the WindowEvent?A.getFrame()B.getlD()C・ getSource()D. getWindow()Explanation:The methods getSource() and getWindow() can be used to get the event sources of the window events・Correct Answer: CQ 49 of 60Question: 5()Which statements of the event listener are true?A.Multiple listeners can be attached to one component.B.Only one listener can be attached to one component.C.One listener can receive and process the events from multiple components・D・ One listener can receive and process the events from only one component.Explanation:One component can registers one or more listeners・ One listener can be registered by multiple components・ After being registered the listener can receive and process the events from these components.Correct Answer: A,C 50 of 60Question: 51What is the return value of the method in the event listener interface?A.intB.StringC.voidD.ObjectE.AWTEvcntExplanation:All the methods in the event listener interfaces return void.Correct Answer: C 51 of 60Question: 52Which of the following event listeners have event adapters defined in Java?A.MouseListenerB.KeyListenerC.ActionListcncrD.ItemListenerE.WindowListcncrExplanation:Four listeners don't have their corresponding event adapters・ They are ActionListener, ItemListener, AdjustmentListener and TextListene 匚Correct Answer: A,B,E 52 of 60Question: 53Which one of the following methods is not related to the display of the applets?A.updatc()B.draw()C.repaint()D.paint()Explanation:The paint(), update() and repaint() are predefined methods in Java・ They are related to the display of the applets.Correct Answer: B 53 of 60Question: 54Given the following definition:TextArea ta = new TextArea (Hello, 5, 5);Which statements are true?A. The maximum number of chanicters in a line is 5.B・ The displayed height is 5 lines otherwise constrain.C・ The displayed string can use multiple fonts.D.The displayed strings are editable.Explanation:The TextArea is constructed to a 5 row * 5 character text area・ It cannot display multiple fonts・ The strings are editable by default. The displayed width of a line is 5 characters, but the maximum number in a line is more than 5.Correct Answer: BQ 54 of 60Question: 55Which method can be used to add MenuBar to a Frame?A.setMenu()B.setMenuBar()C.add()D.addMenuBar()Explanation:McnuBar is added to a Frame by using the sctMcnuBar() method. The add() method is used to add components to containers. Correct Answer: B 55 of 60Question: 56Which are not containers in Java?A. ScrollPaneB・ CanvasC.ScrollbarD.AppletE.DialogExplanation:Scrollbar and Canvas are not containers・ The following classes are containers in Java: Panel, Window, ScrollPane, Dialog, Frame, Applet.Correct Answer: B.C 56 of 60Question: 57Which of the following method can be used to define a new thread class?A. implement the Runnable interfaceB・ add a run() method in the classC.create an instance of ThreadD.extend the Thread classExplanation:Two methods can define a new thread class: to implement the Runnable interface or to extend the Thread class・Correct Answer: AQ 57 of 60Question: 58Which of the following I/O stream are node streams?A. FilelnputStreamB・ BufferedlnputStreamC・ PushbacklnputStreamD. ByteArraylnputStreamExplanation:The FilelnputStream and ByteArraylnputStream are node streams・ The BufferedlnputStream and PushbacklnputStream are filter streams.Correct Answer: A,D 58 of 60Qucstion:59Which of the following classes can handle the Unicode?InputStrcamRcadcrBufferedReaderWriterPipedlnputStreamExplanation:Java uses Unicode to represent strings and characters and Java provides 16 bit versions of streams to allow characters to be treated similarly. They are Reader, Writer and their subclasses・Correct Answer: A,B,C 59 of 60Question: 60Which classes are used to implement TCP/IP client and servers?A.ServerSocketB.ServerC.SocketD.DatagramPacketE.DatagramSocketExplanation:Use ServerSocket and Socket classes to implement the TCP/IP clients and servers. The DatagramPacket and DatagramSocket are used in the UDP-based network communication.Correct Answer: A,C 60 of 60。
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、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
JAVA认证历年真题:SCJP认证套题解析(3)41、Which of the following statements are legal?A. long l = 4990;B. int i = 4L;C. float f = 1.1;D. double d = 34.4;E. double t = 0.9F.(ade)题目:下面的哪些声明是合法的。
此题的考点是数字的表示法和基本数据类型的类型自动转换,没有小数点的数字被认为是int型数,带有小数点的数被认为是double型的数,其它的使用在数字后面加一个字母表示数据类型,加l或者L是long型,加d或者D是double,加f或者F是float,可以将低精度的数字赋值给高精度的变量,反之则需要进行强制类型转换,例如将int,short,byte赋值给long 型时不需要显式的类型转换,反之,将long型数赋值给byte,short,int型时需要强制转换(int a=(int)123L;)。
42、public class Parent {int change() {…}}class Child extends Parent {}Which methods can be added into class Child?A. public int change(){}B. int chang(int i){}C. private int change(){}D. abstract int chang(){}(ab)题目:哪些方法可被加入类Child。
这个题目的问题在第35题中有详尽的叙述。
需要注意的是答案D的内容,子类可以重写父类的方法并将之声明为抽象方法,但是这引发的问题是类必须声明为抽象类,否则编译不能通过,而且抽象方法不能有方法体,也就是方法声明后面不能带上那两个大括号({}),这些D都不能满足。
43、class Parent {String one, two;public Parent(String a, String b){one = a;two = b;}public void print(){ System.out.println(one); }}public class Child extends Parent {public Child(String a, String b){super(a,b);}public void print(){System.out.println(one + " to " + two);}public static void main(String arg[]){Parent p = new Parent("south", "north");Parent t = new Child("east", "west");p.print();t.print();}}Which of the following is correct?A. Cause error during compilation.B. southeastC. south to northeast to westD. south to northeastE. southeast to west(e)题目:下面的哪些正确。
A. 在编译时出错。
这个题目涉及继承时的多态性问题,在前面的问题中已经有讲述,要注意的是语句t.print();在运行时t实际指向的是一个Child对象,即java在运行时决定变量的实际类型,而在编译时t是一个Parent对象,因此,如果子类Child中有父类中没有的方法,例如printAll(),那么不能使用t.printAll()。
参见12题的叙述。
44、A Button is positioned in a Frame. Only height of the Button is affected by the Frame while the width is not. Which layout manager should be used?A. FlowLayoutB. CardLayoutC. North and South of BorderLayoutD. East and West of BorderLayoutE. GridLayout(d)题目:一个按钮放在一个框架中,在框架改变时只影响按钮的高度而宽度不受影响,应该使用哪个布局管理器?这个还是布局管理器的问题,流布局管理器(FlowLayout)将根据框架的大小随时调整它里面的组件的大小,包括高度和宽度,这个管理器不会约束组件的大小,而是允许他们获得自己的最佳大小,一行满了以后将在下一行放置组件;卡片管理器(CardLayout)一次显式一个加入的组件(根据加入时的关键字);网格管理器(GridLayout)将容器划分为固定的网格,容器大小的改变将影响所有组件的大小,每个组件的大小都会同等地变化;边界管理器(BorderLayout)将容器划分为五个区域,分为东南西北和中间,东西区域的宽度为该区域里面组件的最佳宽度,高度为容器的高度减去南北区域的高度,这是一个可能变化的值,而南北区域的宽度为容器的整个宽度,高度为组件的最佳高度,中间区域的高度为容器的高度减去南北区域的高度,宽度为容器的宽度减去东西区域的宽度。
45、Given the following code:1) class Parent {2) private String name;3) public Parent(){}4) }5) public class Child extends Parent {6) private String department;7) public Child() {}8) public String getValue(){ return name; }9) public static void main(String arg[]) {10) Parent p = new Parent();11) }12) }Which line will cause error?A. line 3B. line 6C. line 7D. line 8E. line 10(d)题目:给出下面的代码:…哪些行将导致错误。
第8行的getValue()试图访问父类的私有变量,错误,参看前面有关变量类型及其作用域的叙述。
46、The variable "result" is boolean. Which expressions are legal?A. result = true;B. if ( result ) { // do something... }C. if ( result!= 0 ) { // so something... }D. result = 1(ab)题目:变量"result"是一个boolean型的值,下面的哪些表达式是合法的。
Java的boolean不同于c或者c++中的布尔值,在java中boolean值就是boolean值,不能将其它类型的值当作boolean处理。
47、Class Teacher and Student are subclass of class Person.Person p;Teacher t;Student s;p, t and s are all non-null.if(t instanceof Person) { s = (Student)t; }What is the result of this sentence?A. It will construct a Student object.B. The expression is legal.C. It is illegal at compilation.D. It is legal at compilation but possible illegal at runtime.(c)题目:类Teacher和Student都是类Person的子类…p,t和s都是非空值…这个语句导致的结果是什么A. 将构造一个Student对象。
B. 表达式合法。
C. 编译时非法。
D. 编译时合法而在运行时可能非法。
instanceof操作符的作用是判断一个变量是否是右操作数指出的类的一个对象,由于java 语言的多态性使得可以用一个子类的实例赋值给一个父类的变量,而在一些情况下需要判断变量到底是一个什么类型的对象,这时就可以使用instanceof了。
当左操作数是右操作数指出的类的实例或者是子类的实例时都返回真,如果是将一个子类的实例赋值给一个父类的变量,用instanceof判断该变量是否是子类的一个实例时也将返回真。
此题中的if语句的判断没有问题,而且将返回真,但是后面的类型转换是非法的,因为t是一个Teacher对象,它不能被强制转换为一个Student对象,即使这两个类有共同的父类。
如果是将t转换为一个Person对象则可以,而且不需要强制转换。
这个错误在编译时就可以发现,因此编译不能通过。
48、Given the following class:public class Sample{long length;public Sample(long l){ length = l; }public static void main(String arg[]){Sample s1, s2, s3;s1 = new Sample(21L);s2 = new Sample(21L);s3 = s2;long m = 21L;}}Which expression returns true?A. s1 == s2;B. s2 == s3;C. m == s1;D. s1.equals(m).(b)题目:给出下面的类:…哪个表达式返回true。
前面已经叙述过==操作符和String的equals()方法的特点,另外==操作符两边的操作数必须是同一类型的(可以是父子类之间)才能编译通过。
49、Given the following expression about List.List l = new List(6,true);Which statements are ture?A. The visible rows of the list is 6 unless otherwise constrained.B. The maximum number of characters in a line will be 6.C. The list allows users to make multiple selectionsD. The list can be selected only one item.(ac)题目:给出下面有关List的表达式:…哪些叙述是对的。