JAVA认证历年真题:SCJP考试真题和解析(2)
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(。
SCJP考题

1.import java.io.*;public class Forest implements Serializable {private Tree tree = new Tree();public static void main(String[] args) {Forest f = new Forest();try {FileOutputStream fs = new FileOutputStream("Forest.ser");ObjectOutputStream os = new FileOutputStream(fs);os.writerObject(f);os.close();} catch(Exception ex) {ex.printStackTrace();}}}class Tree() {}Q: 运行结果是:A: B)在运行过程中抛出一个错误E: 因为class Tree没有被序列化,Forest要序列化的话,它里面包含的类对象都要被序列化2.import java.io.*;public class Foo implements Serializable {public int x,y;public Foo(int x,int y) {this.x = x;this.y = y;}private void writeObject(ObjectOutputStream s) throws IOException {s.writeInt(x);s.writeInt(y);}private void readObject(ObjectInputStream s) throws IOException,ClassNotFoundException {// insert code here 14}}Q: 哪些代码插入第14行,能够让class正确的完成序列化和反序列化?A: D) x = s.readInt(); y = s.readInt();3.String test = "This is a test";String[] tokens = test.split("\s");System.out.println(tokens.length);Q: 给出上面代码,执行结果如何?A: D) 编译出错E: 因为"\s"是个错误的转义字符,正确的只有"\b,\t,\n,\f,\r,\",\',\\"4.Date date = new Date();df.setLocale(Local.Ialy); // 13String s = df.format(date);Q: df是一个DateFormat对象并已经初始化完成,问将“December 14,2000”参与运行是什么结果A: D)在第13行编译出错,DateFormat没有setLocale()方法5.Q: 给定一个集合,里面存放的是路径名的分节,如何用代码实现判断这个路径或文件是否存在A: [String path = "";]for(String dir: directories) {[path = path + File.separator + dir;]}[File file = new File(path,filename);][return file.exists();]E: File.separator表示不区分操作系统的分隔符,exists()方法测试该对象表示的路径或文件是否存在6.Q: 给出下面代码,问运行结果System.out.printf("Pi is %f and E is %b",Math.PI,Math.E);A: Pi is 3.14593 and E is true7. Q: 当比较java.io.BufferedWriter和java.io.FileWriter,下面哪些说法是两者共有的A: E) 写一条线分离的流8.Q: 给出下面代码,如何实现打印出“4247”(2个答案)public class Certkiller3 {public static void main(String[] args) {// insert code hereSystem.out.println(s);}}A: B) StringBuffer s = new StringBuffer("123456789");s.delete(0,3).replace(1,3,"24").delete(4,6);E) StringBuffer s = new StringBuffer("123456789");s.delete(0,3).replace(1,3,).delete(2,5).insert(1,"24");9.Q: 下面关于java.io.Realizable接口说法正确的三项是A: B)一个对象被一个JVM序列化后能被另一个JVM反序列化D)一个被transient修饰的属性不能被序列化和反序列化E)一个能被序列化的对象他的超类不用实现java.io.Serialiation接口10.public class Certkiller {public static void go(short n) {System.out.println("short");}public static void go(short n) {System.out.println("SHORT");}public static void go(long n) {System.out.println("long");}public static void main(String[] args) {short y = 6;int z = 7;go(y);go(z);}}Q: 问执行结果A: C) 编译失败E: go(short n) 方法已经存在11.Q: d是有效的,非空的Date对象,df是有效的,非空的DateFormat对象并被设置为本地格式下面的代码如何输出本地国家名字和当前时间A: B) Locale loc = Locale.getDefault();System.out.println(loc.getDisplayCountry()+" "+df.foramt(d));12.public class Certkiller3 implements Runnable {public void run() {System.out.print("running");}public static void main(String[] args) {Thread t = new Thread(new Certkiller3());t.run();t.run();t.start();}}Q: 问执行结果A: 代码执行成功并打印“runningrunningrunning”13.public class Threads1 {int x = 0;public class Runner implements Runnable {public void run() {int current = 0;for(int i = 0; i<4; i++) {current = x;System.out.println(current + ",");x = current + 2;}}}public static void main(String[] args) {new Threads1().go();}public void go() {Runnable r1 = new Runner();new Thread(r1).start();new Thread(r1).start();}}Q: 下面哪两个是可能的运行结果A: A) 0,2,4,4,6,8,10,6C) 0,2,4,6,8,10,12,14E: 多个线程共用一个资源14.void waitForSignal() {Object obj = new Object();synchronized (Thread.currentThread()) {obj.wait();obj.notify();}}Q: 那个说法是正确的A: B) 这段代码会抛出一个IllegalStateExceptionE: IllegalStateException在非法或不适当的时间调用方法时产生的信号15public class TestOne implements Runnable {public static void main(String[] args) throws Exception {Thread t = new Thread(new TestOne());t.start();System.out.println("Started");t.join();System.out.println("Complete");}public void run() {for(int i = 0;i<4;i++) {System.out.println(i);}}}Q: 执行结果A: E) 代码执行成功并打印“Started0123Complete”16.Q: 下面哪两种写法能让doStuff()方法运行在一个线程中A: D) new Thread() {public void run(){doStuff();}}.start();F) new Thread(new Runnable() {public void run(){doStuff();}}.start();17.Q: 下面哪三种写法不会出错A: C) public synchronized void go() {/*code here*/}E) void go() {synchronized(Object.class) {/*code here*/}}F) void go() {synchronized(o) {/*code here*/}}18.class Computation extends Thread {private int num;private boolean isComplete;private int result;public Computation(int num) {this.num = num;}public synchronized void run() {result = num * 2;isComplete = true;notify();}public synchronized int getResult() {while(!isComplete) {try {wait();} catch(InterruptedException e) {}}return result;}public static void main(String[] args) {Computation[] computations = new Computation[4];for(int i = 0; i < computations.length; i++) {computations[i] = new Computation(i);computations[i].start();}for(Computation c : computations)System.out.print(c.getResult() + " ");}}Q: 执行结果A: F) 代码运行并打印“0 2 4 6”19.public class Certkiller {public static void main(String[] args) throws Exception { Thread.sleep(3000);System.out.println("sleep");}}Q: 执行结果A: C)代码正常执行并打印“sleep”20.?Q: 下面说法正确的2个是A: A)继承是一种关系D)实例变量时可以使用创造了一个关系E: is-a 表示类的继承关系has-a表示对象和成员的从属关系he is a people ;he has a head21.package certkiller;class Target {public String name = "hello";}Q: 什么情况下可以直接访问和修改变量nameA: C) 任何在certkiller包下的类E: public是任何类都能访问的,但class Target只能被同包下的类访问22.Q: 下面哪三项是正确的A: B) 一个class X中的protected方法能被任何一个X的子类所重写E) 一个class X中的public static的方法被一个没有明确参照X的子类所调用F) 在class X的子类中存在一个方法,该方法与class X中一个private final方法同名E: 因为private方法是无法被继承的,所以在子类中可以存在同名方法23.Q: 选择填空,区分is-a和has-aA: [Dog] [is-a] AnimalForest [has-a] [Tree]Rectangle [has-a] [Side][Java Book] [is-a] Programming BookE: 狗是一种动物,森林有树,矩形有边,java书籍是一种编程书籍24. ?public class Single {[private] [static] Single instance;[public] [static] Single getInstance() {if(instance == null) instance = create();return instance;}[private] Single() {} // 1.[protected] Single create() {return new Single();} // 2.}Q: 替换两个修饰符来修饰方法让代码编译通过A: 将//1. 处替换为[protected],将//2. 处替换为[static]25.public class SimpleCale {public int value;public void calculate() {value += 7;}}public class MultiCalc extends SimpleCalc {public void calculate() {value -= 3;}public void calculate(int multiplier) {calculate();super.calculate();value *= multiplier;}public staic void main(String[] args) {MultiCalc calculator = new MultiCalc();calculator.calculate(2);System.out.println("Value is: " + calculator.value);}}Q: 执行结果A: A) Value is : 8;26.public class CertkillerCard {private String cardID;private Integer limit;public String ownerName;public void setCardInformation(String cardID,String ownerName,Integer limit) { this.cardID = cardID;this.ownerName = ownerName;this.limit = limit;}}Q: 下面说法哪个是对的A: C) ownerName改变了封装(翻译不准确)E: 这道题目主要考察类的封装特性,ownerName属性是公共的27.class Animal {public String noise() {return "peep";}}class Dog extends Animal {public String noise() {return "back";}}class Cat extends Animal {public String noise() {return "move";}}...Animal animal = new Dog();Cat cat = (Cat) animal;System.out.println(cat.noise());Q: 执行结果A: E) 在运行时会抛出一个错误E: 编译时可以通过,但运行时将出现类型转化错误28.public class Car {private int wheelCount;private String vin;public Car(String vin) {this.vin = vin;this.wheelCount = 4;}public String extend() {return "zoom zoom";}public String getInfo() {return "vin: " + vin + " wheels: " + wheelCount;}}public class MeGo extends Car {public MeGo(String vin) {this.wheelCount = 3;}}Q: 要改哪两个地方来避免编译错误A: D) 在MeGo的构造中加入super(vin);E) 更改Car中的wheelCount属性的修饰符为protected E: 考察构造函数和继承29.interface A {public int getValue();}class B implements A {public int getValue() {return 1;}}class C extends B {// insert code here,Line 15}Q: 哪三段代码可以插入第15行,利用多态性A: 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: 因为题目规定要利用多态,那么参数只能是C类的超类30.certkiller = new ReallyBigObject();// more code herecertkiller = null;/* insert code here */ // Line 14Q: 在第14行插入什么代码实现垃圾回收A: A) System.gc();31.class Foo {private int x;public Foo(int x) {this.x = x;}public void setX(int x) {this.x = x;}public int getX() {return x;}}public class Submit {static Foo fooBar(Foo foo) {foo = new Foo(100);return foo;}public static void main(String[] args) {Foo foo = new Foo(300);System.out.print(foo.getX() + ".");Foo fooFoo = fooBar(foo);System.out.print(foo.getX() + ".");System.out.print(fooFoo.getX() + ".");foo = fooBar(fooFoo);System.out.print(foo.getX() + ".");System.out.print(fooFoo.getX());}}Q: 执行结果A: B) 300.300.100.100.100E: 注意对象传递是引用传递,形参32.Q: 创建一个类Book,需要用到类Paper,而类Paper在myLib.jar中。
java认证考试试题及答案

java认证考试试题及答案java认证考试试题及答案1. What gets printed when the following programis 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 programis 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. 0B. 1C. 2D. 3E. 4答案:C3. 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;C. d = i;D. b1 = i;解析:A 从子类型到父类型的转换是扩展引用转换,不需要在运行时采取特殊的动作,不会在运行时抛出异常。
2024年等级考试-计算机二级-Java语言程序设计考试历年真题常考点试题2带答案

2024年等级考试-计算机二级-Java语言程序设计考试历年真题常考点试题带答案(图片大小可任意调节)第1卷一.单选题(共20题)1.编译JavaApplet源程序文件产生的字节码文件的扩展名为()A.javaB.classC.htmlD.exe2.获取 InetAddress 对象的 IP 地址所用到的方法是A.etHostlPAddress()B.getHostlP()C.getHostAddress()D. getHost()3.下列叙述中正确的是哪一个( ) 。
A.在面向对象的程序设计中,各个对象之间具有密切的关系B.在面向对象的程序设计中,各个对象都是公用的C.在面向对象的程序设计中,各个对象之间相对独立,相互依赖性小D.上述 3种说法都不对4.有整型数组: int[] x={12,35,8,7,2};, 则调用方法 Arrays.sort(x)后,数组 x 中的元素值依次是 ( ).A.2 7 8 12 35B.12 35 8 7 2C.35 12 8 7 2D.8 7 12 35 25.定义类头时能使用的修饰符是A. privateB.staticC.abstractD.protected6.开发软件时对提高开发人员工作效率至关重要的是 ( ) 。
A.操作系统的资源管理功能B.先进的软件开发工具和环境C.程序员的数量D.计算机的并行处理能力7.下列有关Java的叙述错误的是A.是—种强类型语言B.与平台无关C.可以使用汉字变量名D.不检查数组下标越界8.下述概念中不属于面向对象方法的是 () 。
A.对象、消息B.继承、多态C.类、封装D.过程调用9.设 int 型变量 a、b,float 型变量 x、y,char 型变量 ch 均已正确定义并赋值,正确的 switch 语句是A.switch (x + y) { ...... }B.switch ( ch + 1 ) { ...... }C. switch ch D) { ...... }D.switch ( a + b ) { ...... }10.关于包的描述错误的是A.包可以将相关的类和接口组织在一起,便于识别和管理B.包中的类可以访问同一包的其它类的私有成员C.不同包中的相同命名,不会产生冲突D.用修饰的顶级类和接口对包外代码可见11.在 Java 中, 表示换行符的转义字符是 () 。
java二级考试真题题库及答案

java二级考试真题题库及答案1. 在Java中,下列哪个关键字用于声明一个类?A. classB. interfaceC. structD. enum答案:A2. Java中,哪个方法用于获取字符串的长度?A. length()B. size()C. count()D. length答案:A3. 在Java中,下列哪个选项是正确的继承方式?A. 多重继承B. 单一继承C. 多级继承D. 混合继承答案:B4. Java中,下列哪个关键字用于捕获异常?A. tryB. catchC. throwD. throws答案:B5. 在Java中,下列哪个选项是正确的关于接口的描述?A. 接口可以包含方法的实现B. 接口可以包含变量C. 接口不能包含构造方法D. 接口可以包含静态方法答案:C6. Java中,下列哪个关键字用于声明一个方法?A. functionB. methodC. procedureD. void答案:D7. 在Java中,下列哪个选项是正确的关于泛型的说法?A. 泛型只能在类中使用B. 泛型只能在接口中使用C. 泛型可以在类和接口中使用D. 泛型只能在方法中使用答案:C8. Java中,下列哪个关键字用于声明一个枚举类型?A. enumB. enumarateC. enumerationD. enumtype答案:A9. 在Java中,下列哪个选项是正确的关于多线程的描述?A. Java不支持多线程B. Java使用Thread类来实现多线程C. Java使用Runnable接口来实现多线程D. Java不支持线程的同步答案:B10. Java中,下列哪个关键字用于声明一个内部类?A. innerB. nestedC. innerclassD. static答案:B结束语:以上是Java二级考试真题题库及答案的一部分,希望对您的学习和复习有所帮助。
一些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试题库及答案

java试题库及答案Java是一种广泛使用的高级编程语言,因其简洁、高效和跨平台性而备受程序员们的青睐。
为了帮助学习Java的同学更好地备战考试,我们特别整理了一份Java试题库及答案,希望对大家有所帮助。
一、基础知识题1. Java中基本数据类型有哪些?请简要说明各自的特点。
答:Java中的基本数据类型包括整型(byte, short, int, long)、浮点型(float, double)、字符型(char)和布尔型(boolean)。
其中整型用于存储整数,浮点型用于存储小数,字符型用于存储字符,布尔型用于存储真假值。
2. Java中如何进行输入输出操作?答:在Java中,可以使用Scanner类进行输入操作,System.out.println()进行输出操作。
二、面向对象题1. 请简要说明面向对象编程的三大特性是什么?答:面向对象编程的三大特性是封装、继承和多态。
封装指的是将数据和方法封装到一个类中,通过访问修饰符来控制对外部的访问权限;继承指的是子类可以继承父类的属性和方法;多态指的是同一个方法在不同的对象下有不同的实现。
2. Java中如何实现继承?请编写一个简单的代码示例。
答:在Java中,可以通过extends关键字来实现继承。
示例代码如下:```javaclass Animal {public void eat() {System.out.println("Animal is eating");}}class Dog extends Animal {public void bark() {System.out.println("Dog is barking");}}public class Main {public static void main(String[] args) {Dog myDog = new Dog();myDog.eat();myDog.bark();}```三、异常处理题1. Java中如何处理异常?请简要说明try-catch-finally语句的作用。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1. Which of the following range of short is correct?A. -27 -- 27-1B. 0 -- 216-1C. ?215 -- 215-1D. ?231 -- 231-1翻译下面哪些是short型的取值范围。
答案 C解析短整型的数据类型的长度是16 bits,有符号。
另外需要说明的是java中所有的整(Integral)数(包括byte,short,int,long)全是有符号的。
2. Which declarations of identifiers are legal?A. $personsB. TwoUsersC. *pointD. thisE. _endline翻译下面哪些是合法的标识符。
答案A,B,E解析Java的标识符可以以一个Unicode字符,下滑线(_),美元符($)开始,后续字符可以是前面的符号和数字,没有长度限制,大小写敏感,不能是保留字。
3. Which statement of assigning a long type variable to a hexadecimal value is correct?A. long number = 345L;B. long number = 0345;C. long number = 0345L;D. long number = 0x345L翻译哪些是将一个十六进制值赋值给一个long型变量。
答案 D解析十六进制数以0x开头,long型数以L(大小写均可,一般使用大写,因为小写的l和数字1不易区分)。
4.Which of the following fragments might cause errors?A. String s = "Gone with the wind";String t = " good ";String k = s + t;B. String s = "Gone with the wind";String t;t = s[3] + "one";C. String s = "Gone with the wind";String standard = s.toUpperCase();D. String s = "home directory";String t = s - "directory";翻译下面的哪些程序片断可能导致错误。
答案B,D解析A:String类型可以直接使用+进行连接运算。
B:String是一种Object,而不是简单的字符数组,不能使用下标运算符取其值的某个元素,错误。
C:toUpperCase()方法是String对象的一个方法,作用是将字符串的内容全部转换为大写并返回转换后的结果(String类型)。
D:String类型不能进行减(-)运算,错误。
5. Which are syntactically valid statement at// point x?class Person {private int a;public int change(int m){ return m; }}public class Teacher extends Person {public int b;public static void main(String arg[]){Person p = new Person();Teacher t = new Teacher();int i;// point x}}A. i = m;B. i = b;C. i = p.a;D. i = p.change(30);E. i = t.b.翻译在// point x处的哪些申明是句法上合法的。
答案D,E解析A:m没有被申明过,不能使用。
B:虽然b是类Teacher的public成员变量,但是在静态方法中不能使用类中的非静态成员。
C:a是类Person的private成员,在类外不能直接引用。
D:change(int m)方法是public方法,并且返回一个int型值,可以通过类的实例变量p引用并赋值给一个int型变量。
E:b是类Teacher的public成员变量,且是int型,可以通过类的实例变量t引用并赋值给一个int型变量。
6. Which layout manager is used when the frame is resized the buttons's position in the Frame might be changed?A. BorderLayoutB. FlowLayoutC. CardLayoutD. GridLayout翻译当Frame的大小被改变时Frame中的按钮的位置可能被改变时使用的哪一个布局管理器。
答案 B解析A:该布局管理器将容器划分为五个部分,容器大小的改变不会影响其中的组件的位置而是影响他们的大小。
B:该布局管理器根据放入其中的组件的最合适大小调整组件的位置,根据组件放入的顺序安排,一行不能容纳时放入下一行,因此容器的大小改变可能改变组件的位置。
C:该布局管理器显示放入该容器的当前页中的组件,一次显示一个,容器大小的改变不能影响其中组件的位置。
D:该布局管理器将容器划分为固定的网格,组件加入后占据一个单元,各组件的相对位置不会因为容器的大小变化而变化,改变的只是组件的大小。
7. Given the following code fragment:1) public void create() {2) Vector myVect;3) myVect = new Vector();4) }Which of the following statements are true?A. The declaration on line 2 does not allocate memory space for the variable myVect.B. The declaration on line 2 allocates memory space for a reference to a Vector object.C. The statement on line 2 creates an object of class Vector.D. The statement on line 3 creates an object of class Vector.E. The statement on line 3 allocates memory space for an object of class Vector翻译给出下面的代码片断。
下面的哪些陈述为true(真)?A. 第二行的声明不会为变量myVect分配内存空间。
B. 第二行的声明分配一个到Vector对象的引用的内存空间。
C. 第二行语句创建一个Vector类对象。
D. 第三行语句创建一个Vector类对象。
E. 第三行语句为一个Vector类对象分配内存空间。
答案A,D,E解析SL-275中指出:要为一个新对象分配空间必须执行new Xxx()调用,new调用执行以下的操作:1.为新对象分配空间并将其成员初始化为0或者null。
2.执行类体中的初始化。
(例如在类中有一个成员声明int a=10;在第一步后a=0 ,执行到第二步后a=10)3.执行构造函数。
4.变量被分配为一个到内存堆中的新对象的引用。
8. Which of the following answer is correct to express the value 8 in octal number?A. 010B. 0x10C. 08D. 0x8翻译下面的哪些答案可以用以表示八进制值8。
答案 A解析八进制值以0开头,以0x开头的为十六进制值,八进制中不能出现数字8,最大只有7。
9. Which are not Java keywords?A. TRUEB. sizeofC. constD. superE. void翻译哪些不是Java关键字。
答案A,B解析A:不是,Java中有true,但是这也不是关键字而是字面量(literal)。
B:不是,Java中不需要这个操作符,所有的类型(原始类型)的大小都是固定的。
C、D、E都是,需要说明的是const是java中未被使用的关键字。
10. Which of the following statements are true?A. The equals() method determines if reference values refer to the same object.B. The == operator determines if the contents and type of two separate objects match.C. The equals() method returns true only when the contents of two objects match.D. The class File overrides equals() to return true if the contents and type of two separate objects match.翻译下面的哪些叙述为真。
A. equals()方法判定引用值是否指向同一对象。
B. == 操作符判定两个分立的对象的内容和类型是否一致。
C. equals()方法只有在两个对象的内容一致时返回true。
D. 类File重写方法equals()在两个分立的对象的内容和类型一致时返回true。
答案A,D解析严格来说这个问题的答案是不确定的,因为equals()方法是可以被重载的,但是按照java语言的本意来说:如果没有重写(override)新类的equals(),则该方法和== 操作符一样在两个变量指向同一对象时返回真,但是java推荐的是使用equals()方法来判断两个对象的内容是否一样,就像String类的equals()方法所做的那样:判定两个String对象的内容是否相同,而==操作符返回true的唯一条件是两个变量指向同一对象。
从这个意义上来说选择给定的答案。
从更严格的意义来说正确答案应该只有d11. Which statements about inheritance are true?A. In Java programming language only allows single inheritance.B. In Java programming language allows a class to implement only oneinterface.C. In Java programming language a class cannot extend a class and implementa interface together.D. In Java programming language single inheritance makes code morereliable.翻译下面关于继承的哪些叙述是正确的。