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

合集下载

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

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

JAVA认证历年真题:SCJP考试真题和解析[1]例题1: Choose the three valid identifiers from those listed beloeClassB.$byteC・ constD._okE.3_case解答:A, B, D点评:Java中的标示符必须是字母、美元符($)或下划线(_)开头。

关键字与保留字不能作为标示符。

选项C中的const是Java的保留字,所以不能作标示符。

选项E中的3_case以数字开头,违反了Java的规则。

例题2:Ho.gc()・C.Call System.gc(), passing in a reference to the object to be garbage collected・D.Call Runtime.gc().E.Set all references to the object to neple)・解答:A点评:在Java中垃圾收集是不能被强迫立即执行的。

调用System.gc()或Runtime.gc()静态方法不能保证垃圾收集器的立即执行,因为,也许存在着更高优先级的线程。

所以选项B、D不正确。

选项C的错误在于,System.gc()方法是不接受参数的。

选项E 中的方法可以使对象在下次垃圾收集器运行时被收集。

例题3:Consider the follo.out.println( "I am an int.v );4.}5.void test(String s) {6.System.out.println( “I am a string.v );7.}&9.public static void main(String argsf]) {10.Test t=neents beloethods cannot be overridden.B.Line 12 ent.C.The code an int.E. The code a String.解答:D点评:在第12行,16位长的char型变量ch在编译时会自动转化为一个32位长的int型,并在运行时传给void test(int i)方法。

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

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

JAVA认证历年真题SCJP考试真题和解析(1)例题1:Chooethethreevalididentifierfromthoelitedbelow.A.IDoLikeTheL ongNameClaB.$byteC.contD._okE.3_cae解答:A,B,D点评:Java中的标示符必须是字母、美元符($)或下划线(_)开头。

关键字与保留字不能作为标示符。

选项C中的cont是Java的保留字,所以不能作标示符。

选项E中的3_cae以数字开头,违反了Java的规则。

例题2:HowcanyouforcegarbagecollectionofanobjectA.Garbagecollection cannotbeforcedB.CallSytem.gc().E.Setallreferencetotheobjecttonewvalue(null,fore某ample).解答:A例题3:Coniderthefollowingcla:1.claTet(inti){2.voidtet(inti){3.Sytem.out.println(“Iamanint.”);4.}5.voidtet(String){6.Sytem.out.println(“Iamatring.”);7.}8.9.publictaticvoidmain(Stringarg){10.Tett=newTet();11.charch=“y”;12.t.tet(ch);13.}14.}Whichofthetatementbelowitrue(Chooeone.)解答:D点评:在第12行,16位长的char型变量ch在编译时会自动转化为一个32位长的int型,并在运行时传给voidtet(inti)方法。

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

Java高级程序设计认证试卷

Java高级程序设计认证试卷

Java高级程序设计认证试卷(答案见尾页)一、选择题1. Java语言的特性包括哪些?A. 封装B. 多态C. 抽象D. 动态代理2. 在Java中,以下哪个关键字用于定义常量?A. finalB. staticC. constD. var3. Java中的集合框架包含以下哪些接口?A. CollectionB. ListC. SetD. Map4. Java的异常处理机制包括以下哪些关键字?A. tryB. catchC. finallyD. throw5. 以下哪个是Java反射机制中用于获取类信息的方法?A. getDeclaredMethods()B. getGenericSuperclass()C. getAnnotations()D. getComponentType()6. Java的泛型支持以下哪种类型转换?A. 自动装箱/拆箱B. 自动类型转换C. 强制类型转换D. 隐式类型转换7. Java的注解处理器用于执行哪些任务?A. 代码重构B. 类文件生成C. 性能优化D. 错误检查8. 在Java中,以下哪个关键字用于实现接口?A. implementsB. extendsC. implementsD. extends9. Java的序列化机制用于以下哪个目的?A. 恢复内存中的对象状态B. 实现跨平台的数据交换C. 提高数据安全性D. 降低数据存储效率10. Java的线程同步机制使用的关键字是?A. synchronizedB. volatileC. lockD. await11. Java语言有哪些基本数据类型?A. byteB. shortC. intD. long12. 在Java中,以下哪个关键字用于定义方法?A. privateB. staticC. finalD. abstract13. Java中的集合框架包括哪些接口和实现类?A. ListB. SetC. QueueD. Map14. Java中,哪个关键字用于实现继承?A. extendsB. implementsC. interfaceD. override15. 在Java中,什么是垃圾回收机制(Garbage Collection)?A. 一种自动内存管理技术B. 一种手动内存管理技术C. 一种动态数组技术D. 一种静态数组技术16. Java中,哪个关键字用于导入其他包或类库?A. importB. includeC. requireD. uses17. 在Java中,什么是异常处理机制?请简述。

java认证考试试题及答案

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 从子类型到父类型的转换是扩展引用转换,不需要在运行时采取特殊的动作,不会在运行时抛出异常。

JAVA认证历年真题:SCJP认证套题解析[2]

JAVA认证历年真题:SCJP认证套题解析[2]

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的错误在于在父类型的构造函数被调用前不能引用类的成员。

2024年等级考试-计算机二级-Java语言程序设计考试历年真题常考点试题2带答案

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认证历年真题:SCJP认证套题解析(3)

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开发工程师试卷及答案解析

Java开发工程师试卷及答案解析Java开发工程师试卷及答案解析一、单选题 (共19道题,每题5分)1.下面有关java的一些细节问题,描述错误的是?A.构造方法不需要同步化B.一个子类不可以覆盖掉父类的同步方法C.定义在接口中的方法默认是public的D.容器保存的是对象的引用2.在Java中,以下关于方法重载和方法重写描述正确的是()A.方法重载和方法的重写实现的功能相同B.方法重载出现在父子关系中,方法重写是在同一类中C.方法重载的返回值类型必须一致,参数项必须不同D.方法重写的返回值类型必须相同或相容。

(或是其子类)3.在JAVA中,下面关于String类和StringBuffer类的描述正确的是那一个?A.StringBuffer类的对象调用toString()方法将转换为String类型B.两个类都有append()方法C.可以直接将字符串“test”赋值给声明的Stirng类和StringBuffer类的变量D.两个类的实例的值都能够被改变4.下面有关List接口、Set接口和Map接口的描述,错误的是?A.他们都继承自Collection接口B.List是有序的Collection,使用此接口能够精确的控制每个元素插入的位置C.Set是一种不包含重复的元素的CollectionD.Map提供key到value的映射。

一个Map中不能包含相同的key,每个key只能映射一个value5.下面有关spring的依赖注入,说法错误的是?A.依赖注入通常有如下两种:设值注入和构造注入:B.构造注入可以在构造器中决定依赖关系的注入顺序,优先依赖的优先注入C.当设值注入与构造注入同时存在时,先执行构造注入,再执行设值注入D.设值注入是指IoC容器使用属性的setter方法来注入被依赖的实例。

这种注入方式比较简单、直观6.下面不属于HttpServletRequest接口完成功能的是?A.读取cookieB.读取HTTP头C.设定响应的content类型D.读取路径信息7.从以下哪一个选项中可以获得Servlet的初始化参数?A.ServletB.ServletContextC.ServletConfigD.GenericServlet8.下列关于java抽象类的'说法哪个正确?A.某个抽象类的父类是抽象类,则这个子类必须重载父类的所有抽象方法B.接口和抽象类是同一回事C.可以用抽象类直接去实例化创建对象D.一个类只能继承一个抽象类9.下面关于spring和struts2的描述,错误的是?A.spring mvc的入口是filter,而struts2是servletB.spring mvc是基于方法的设计,而struts2是基于类的设计C.struts2有以自己的interceptor机制,spring mvc用的是独立的AOP方式D.spring mvc的方法之间基本上独立的,独享request response 数据,struts2所有Action变量是共享的10.关于JAVA的垃圾回收机制,下面哪些结论是正确?A.程序可以任意指定释放内存的时间B.JAVA程序不能依赖于垃圾回收的时间或者顺序C.程序可明确地标识某个局部变量的引用不再被使用D.程序可以显式地立即释放对象占有的内存11.一般用()创建InputStream对象,表示从标准输入中获取数据,用()创建OutputStream对象,表示输出到标准输出设备中。

SCJP认证考试题库2

SCJP认证考试题库2

SCJP认证考试题库2What is the result?A. n ullB. zeroC. s omeD. C ompilation failsE. An exception is thrown at runtimeAnswer: ( D )13行会报错,应在15行使用else if 参考大纲:流程控制QUESTION 63Given the exhibit:What is the result?A. testB. ExceptionC. Compilation failsD. NullPointerExceptionAnswer: ( C )18行出错,应该先catch子异常,再catch Exception;13行把args赋null ,14行会报NullPointerException如果没有第13行运行时14行会报ArrayIndexOutOfBoundsException异常。

参考大纲:异常处理QUESTION 64Given the exhibit:What is the result?A. Compilation failsB. aAaA aAa AAaa AaAC. AAaa AaA aAa aAaAD. AaA AAaa aAaA aAaE. aAa AaA aAaA AAaaF. An exception is thrown at runtimeAnswer: ( C )第10行将对strings这个集合做自然排序(ASCII小到大,一个一个比较)Collections.sort(List list) 对list进行排序,对set 不能排序!List里可以放对象,所以当list里面存放的是对象的时候就不能用Collections.sort(List list)去排序了。

因为JVM不知道用什么规则去排序!!只有把对象类实现Comparable接口,然后改写compareTo()参考大纲:集合QUESTION 65Given the exhibit:What is the result?A. 0B. 1C. 2D. 3E. 4F. Compilation fails.G. An exception is thrown at runtimeAnswer: ( D )Set中存放的元素是无序不重复的。

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

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

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

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

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

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

一些SCJP考试题含答案

一些SCJP考试题含答案

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

java考试题及答案

java考试题及答案

java考试题及答案Java考试题及答案一、选择题(每题2分,共20分)1. Java语言属于以下哪类编程语言?A. 过程式编程语言B. 面向对象编程语言C. 函数式编程语言D. 逻辑编程语言答案:B2. Java程序的执行入口是以下哪个方法?A. main()B. init()C. start()D. run()答案:A3. 下列哪个关键字用于定义类?A. classB. interfaceC. enumD. struct答案:A4. Java中,哪个关键字用于定义一个方法?A. methodB. functionC. procedureD. void答案:D5. 在Java中,哪个关键字用于实现继承?A. extendsB. inheritC. derivedD. subclass答案:A6. 下列哪个是Java中的访问修饰符?A. publicB. privateC. protectedD. All of the above答案:D7. Java中,哪个关键字用于抛出异常?A. tryB. catchC. throwD. finally答案:C8. Java中,哪个类是所有Java类的父类?A. ObjectB. ClassC. SystemD. Thread答案:A9. 在Java中,哪个关键字用于定义接口?A. classB. interfaceC. abstractD. package答案:B10. 下列哪个是Java集合框架中的接口?A. ListB. SetC. MapD. All of the above答案:D二、简答题(每题10分,共30分)1. 简述Java的垃圾回收机制。

答案:Java的垃圾回收机制是一种自动内存管理功能,它通过垃圾回收器定期检查不再被引用的对象,并释放它们占用的内存。

垃圾回收器运行在后台,开发者不需要手动释放对象内存。

2. 描述Java中多态的概念及其实现方式。

SCJP考试真题和解析-Read

SCJP考试真题和解析-Read

SCJP考试真题和解析Choose the three valid identifiers from those listed below.A. IDoLikeTheLongNameClassB. $byteC. constD. _okE. 3_case解答:A, B, D点评:Java中的标示符必须是字母、美元符($)或下划线(_)开头。

关键字与保留字不能作为标示符。

选项C中的const是Java的保留字,所以不能作标示符。

选项E中的3_case以数字开头,违反了Java的规则。

例题2:How can you force garbage collection of an object?A. Garbage collection cannot be forcedB. Call System.gc().C. Call System.gc(), passing in a reference to the object to be garbage collected.D. Call Runtime.gc().E. Set all references to the object to new values(null, for example).解答:A点评:在Java中垃圾收集是不能被强迫立即执行的。

调用System.gc()或Runtime.gc()静态方法不能保证垃圾收集器的立即执行,因为,也许存在着更高优先级的线程。

所以选项B、D不正确。

选项C的错误在于,System.gc()方法是不接受参数的。

选项E中的方法可以使对象在下次垃圾收集器运行时被收集。

例题3:Consider the following class:1. class Test(int i) {2. void test(int i) {3. System.out.println(“I am an int.”);4. }5. void test(String s) {6. System.out.println(“I am a string.”);7. }8.9. public static void main(String args[]) {10. Test t=new Test();11. char ch=“y”;12. t.test(ch);13. }14. }Which of the statements below is true?(Choose one.)A. Line 5 will not compile, because void methods cannot be overridden.B. Line 12 will not compile, because there is no version of test() that rakes a char argument.C. The code will compile but will throw an exception at line 12.D. The code will compile and produce the following output: I am an int.E. The code will compile and produce the following output: I am a String.解答:D点评:在第12行,16位长的char型变量ch在编译时会自动转化为一个32位长的int型,并在运行时传给void test(int i)方法。

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

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

JAVA认证历年真题:SCJP考试真题和解析[2]1. Which of the following range of short is correct?A. -27 -- 27-1B. 0 -- 216-1C. ?215 -- 215-1D. ?231 -- 231-1翻译下面哪些是short型的取值范围。

答案 C解析短整型的数据类型的长度是16 bits,有符号。

另外需要说明的是java中所有的整(Integral)数(包括byte,short,int,long)全是有符号的。

2. Which declarations of identifiers are legal?A. $personsB. TwoUsersC. *pointD. thisE. _endline翻译下面哪些是合法的标识符。

答案A,B,E解析Java的标识符可以以一个Unicode字符,下滑线(_),美元符($)开始,后续字符可以是前面的符号和数字,没有长度限制,大小写敏感,不能是保留字。

3. Which statement of assigning a long type variable to a hexadecimal value is correct?A. long number = 345L;B. long number = 0345;C. long number = 0345L;D. long number = 0x345L翻译哪些是将一个十六进制值赋值给一个long型变量。

答案 D解析十六进制数以0x开头,long型数以L(大小写均可,一般使用大写,因为小写的l和数字1不易区分)。

4.Which of the following fragments might cause errors?A. String s = "Gone with the wind";String t = " good ";String k = s + t;B. String s = "Gone with the wind";String t;t = s[3] + "one";C. String s = "Gone with the wind";String standard = s.toUpperCase();D. String s = "home directory";String t = s - "directory";翻译下面的哪些程序片断可能导致错误。

SCJP题库

SCJP题库

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

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

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

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

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

更重要的一点是。

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

一种全新的思维模式。

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

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

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

SCJP 6.0认证教战手册考题1

SCJP 6.0认证教战手册考题1
} public class Beta extends Alpha{
public void bar(int x){}
public int bar(String x){return 1;}
public void bar(int x, int y){} } 參考:6-5 繼承
第13題
Given: 1. 2.
參考:4-1 條件控制
4
SCJP 6.0 認證教戰手冊 黃彬華著 碁峰出版
第9題 Given:
11. String[] elements = {"for", "tea", "too"}; 12. String first = (elements.length>0) ? elements[0] : null; What is the result? A. Compilation fails. B. An exception is thrown at runtime. C. The variable first is set to null. D. The variable first is set to elements[0]. 答案:D 參考:4-1 條件控制、5-2 1 維陣列介紹
6
SCJP 6.0 認證教戰手冊 黃彬華著 碁峰出版
3.
new Barn.go("hi", 1);
4.
new Barn.go("hi", "world", 2);
5.
}
6.
public void go(String... y, int x){
7.
System.out.print(y[y.length-1] + " ");

SCJP题库 带达内考点分析⑤_⑧答案

SCJP题库 带达内考点分析⑤_⑧答案

ANSWERModule 51.BCD2. E3.BDE4.C5.D6.D7.D8.B拖拽题1. Answer:String path = "";for(String dir : directories){path = path + File.separator + dir;}File file = new File(path, filename);return file.exists();2. Answer: reader=new BufferedReader(new FileReader("in"));writer=new BufferedWriter(new PrintWriter(new FileWriter("out")));或 writer=new PrintWriter(new BufferedWriter(new FileWriter("out")));3. Answer:try{String temp;while((temp=buffReader.readLine())!=null){System.out.println(temp);}}catch(IOException e){e.printStackTrace();}4. Answer:import java.io.*;public class ReadFile {public static void main(String[] args) {try{File x1 = new File("MyText.txt");feredReader x4 = new BufferedReader(x2);String x3 = null;while((x3 = x4.readLine()) != null){System.out.println(x3);}x4.close();}catch(Exception ex){ex.printStackTrace();}}}Module 61.D2.BC3.A4.D5.C6.D7.C8.B9.A 10.C 11.BE 12.D 13.A 14.E 15.CF 16.B 17.FG 18.D 19.B 20.C 21.D 22.B 23.D拖拽题1. Answer:Pi is approximately 3.141593 and E is approximately true2. Answer:while(scanner.hasNext()){if(scanner.hasNextBoolean()){System.out.println(scanner.nextBoolean() + " ");} else scanner.next();}Module 71.A2.B3.A4.C5.D6.D7.D8.F9.B 10.B 11.B 12.B 13.AD 14.B 15.A 16.CE 17.A 18.B 19.AC 20.B 21.D 22.G 23.C 24.C 25.C 26.ACF 27.CDG 28.D 29.ABDE 30.ADE 31.DF 32.A拖拽题1. Answer:allows access to elements by their integer index--------------------------java.util.List defines the method V get(Object key)--------------------------------------java.util.Map is designed for holding elements prior to processing---------------------java.util.Queue contains no pair of elements e1 and e2, such that e1.equals(e2)--------java.util.Set 2. Answer:public class NumberNames{private HashMap<String,Integer>map=new HashMap<String,Integer>;public void put(String name,int value){map.put(name,value);}public Set<String> getNames(){return map.keySet();}}3. Answer: m1(listA); Compiles and runs without errorm2(listA); Compiles and runs without errorm1(listB); Compiles and runs without errorm2(listB); Compilation failsm1(listO); Compilation failsm2(listO); Compilation fails4. Answer: import java.util.*;public class MyInt implements Comparable{public static void main(String[] args) {ArrayList<MyInt> list=new ArrayList<MyInt>();list.add(new MyInt(2));list.add(new MyInt(1));Collections.sort(list);System.out.println(list);}private int i;public MyInt(int i){this.i=i;}public String toString(){return Integer.toString(i);}public int compareTo(Object o) {MyInt i2=(MyInt)o;return i-i2.i;}}5. Answer:public void takeList(ArrayList list){} -----------------------------Compilation succeeds public void takeList(ArrayList<Dog> list) {}---------------------Compilation succeeds public void takeList(ArrayList<Animal> list) {}-----------------Compilation fails public void takeList(ArrayList<? extends Animal> list){}------Compilation succeeds public void takeList(ArrayList<?> list){}-------------------------Compilation succeeds public void takeList(ArrayList<Object> list){} ------------------Compilation fails6. Answer:public class GenericB<T extends Pet>{public T foo;public void setFoo(T foo){this.foo = foo;}public T getFoo(){return foo;}}7. Answer:ArrayList<String> x1=new ArrayList<String>();foo(x1); //Compilation of the first statement succeeds, but compilation failsdue to an error in the second statementArrayList<Object> x2=new ArrayList<String>();foo(x2); //Compilation fails due to an error in the first statement.ArrayList<Object> x3=new ArrayList<Object>();foo(x3); //Compilation succeedsArrayList x4=new ArrayList();foo(x4); //Compilation succeeds8. Answer:public class Gen<T>{private T object;public Gen(T object){this.object = object;}public T getObject(){return object;}}9. Answer:list.add("Foo"); Compilation failslist = new ArrayList<String>(); Compilation succeedslist = new ArrayList<Object>(); Compilation failsString s = list.get(0); Compilation succeedsObject o = list; Compilation succeeds10. Answer:import java.util.*;public class _166 {public static void main(String[] args) {List<String> list=new LinkedList<String>();list.add("one");list.add("two");System.out.println(list.get(0).length());}}Module 81.DF2.B3.E4.AC5.B6.C7.DE8.D9.C 10.E 11.F 12.A 13.E 14.G 15.ACE 16.EG 17.AD 18.CEF 19.E 20.ABE拖拽题1. Answer:startedraninterruptingendedno more output2. Answer:t.run();t.join();t.doIt();3. Answer:public class Flags2 {private boolean isReady=false;public synchronized void produce(){ isReady=true;notifyAll();}public synchronized void consume(){ while(!isReady){try{wait();}catch(Exception ex){}}isReady=false;}}4. Answer:run()ng.Thread wait()ng.Object notify()ng.Object sleep()ng.Thread start()ng.Thread join()ng.Thread。

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

JA V A认证历年真题SCJP考试真题和解析
1. Which of the following range of short is correct?
A. -27 -- 27-1
B. 0 -- 216-1
C. ?215 -- 215-1
D. ?231 -- 231-1
翻译下面哪些是short型的取值范围。

答案 C
解析短整型的数据类型的长度是16 bits,有符号。

另外需要说明的是java中所有的整(Integral)数(包括byte,short,int,lo ng)全是有符号的。

2. Which declarations of identifiers are legal?
A. $persons
B. TwoUsers
C. *point
D. this
E. _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类型不能进行减(-)运算,错误。

相关文档
最新文档