JAVA认证历年真题-SCJP考试真题和解析[1].doc
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 从子类型到父类型的转换是扩展引用转换,不需要在运行时采取特殊的动作,不会在运行时抛出异常。
一些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试题及答案一、选择题1. Java语言属于以下哪一种编程范式?A. 过程式编程B. 面向对象编程C. 函数式编程D. 逻辑式编程答案:B2. 下列哪个关键字用于定义Java接口?A. classB. interfaceC. packageD. enum答案:B3. 在Java中,哪个类是所有Java类的根类?A. ObjectB. SystemC. StringD. Thread答案:A二、填空题4. Java语言的跨平台特性主要得益于______机制。
答案:JVM(Java虚拟机)5. 在Java中,使用______关键字可以定义一个类。
答案:class三、简答题6. 请简述Java中的垃圾回收机制。
答案:Java的垃圾回收机制是指自动回收不再使用的对象所占用的内存。
Java虚拟机(JVM)负责监控对象的使用情况,当确定对象不再被任何引用指向时,就会将其内存回收,以便再次使用。
四、编程题7. 编写一个Java程序,实现计算两个整数的和。
```javapublic class SumCalculator {public static void main(String[] args) {int num1 = 10;int num2 = 20;int sum = num1 + num2;System.out.println("The sum is: " + sum);}}```答案:上述程序定义了一个名为SumCalculator的类,其中包含main方法。
在main方法中,定义了两个整数num1和num2,计算它们的和,并将结果输出到控制台。
五、论述题8. 论述Java异常处理机制的重要性及其基本组成部分。
答案:Java异常处理机制是程序健壮性的关键部分,它允许程序在遇到错误或异常情况时,能够优雅地处理问题,而不是直接崩溃。
基本组成部分包括:- try:尝试执行的代码块,可能会抛出异常。
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认证试题及答案

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

Question No: 11.public class test (2. public static void main (String args[]) {3. int i = 0xFFFFFFF1;4. int j = ~i;5.6. }7. )What is the decimal value of j at line 5?A. 0B. 1C. 14D. –15E. An error at line 3 causes compilation to fail.F. An error at line 4 causes compilation to fail. 答案:( c )Question No: 2Given:Integer i = new Integer (42);Long 1 = new Long (42);Double d = new Double (42.0);Which two expressions evaluate to True? (Choose Two)A. (i ==1)B. (i == d)C. (d == 1)D. (i.equals (d))E. (d.equals (i))F. (i.equals (42))答案:( f )Question No: 3Exhibit :1. public class test (2. private static int j = 0;3.4. private static boolean methodB(int k) (5. j += k;6. return true;6. )7.8. public static void methodA(int i) {9. boolean b:10. b = i < 10 | methodB (4);11. b = i < 10 || methodB (8);12. }13.14. public static void main (String args[] ) (15. methodA (0);16. system.out.printIn(j);17. )18. )What is the result?A. The program prints “0”B. The program prints “4”C. The program prints “8”D. The program prints “12”E. The code does not complete.答案:( b )Question No: 4Given1. Public class test (2. Public static void main (String args[]) (3. System.out.printIn (6 ^ 3);4. )5. )What is the output?答案:( 5 )Question No: 5Given:1. public class Foo {2. public static void main (String [] args) {3. StringBuffer a = new StringBuffer (“A”);4. StringBuffer b = new StringBuffer (“B”);5. operate (a,b);6. system.out.printIn{a + “,” +b};7. }8. static void operate (StringBuffer x, StringBuffer y) {9. x.append {y};10. y = x;11. }12. }What is the result?A. The code compiles and prints “A,B”.B. The code compiles and prints “A,A”.C. The code compiles and prints “B,B”.D. The code compiles and prints “AB,B”.E. The code compiles and prints “AB,AB”.F. The code does not compile because “+” cannot be overloaded for StringBuffer.答案:( D )Question No: 6Exhibit:1. Public class test (2. Public static void stringReplace (String text) (3. Text = text.replace (‘j’ , ‘i’);4. )5.6. public static void bufferReplace (StringBuffer text) (7. text = text.append (“C”)8. )9.10. public static void main (String args[]) (11. String textString = new String (“java”);12. StringBuffer text BufferString = new StringBuffer (“java”);13.14. stringReplace (textString);15. BufferReplace (textBuffer);16.17. System.out.printIn (textString + textBuffer);18. )19. )What is the output?答案:( javajavaC )Question No: 7Exhibit:1. public class test {2. public static void add3 (Integer i) }3. int val = i.intValue ( );4. val += 3;5. i = new Integer (val);6. )7.8. public static void main (String args [ ] ) {9. Integer i = new Integer (0);10. add3 (i);11. system.out.printIn (i.intValue ( ) );12. }13. )What is the result?A. Compilation will fail.B. The program prints “0”.C. The program prints “3”.D. Compilation will succeed but an exception will be thrown at line 3. 答案:( 0 )Question No: 8Given:1. public class ConstOver {2. public ConstOver (int x, int y, int z) {3. }4. }Which two overload the ConstOver constructor? (Choose Two)A. ConstOver ( ) { }B. Protected int ConstOver ( ) { }C. Private ConstOver (int z, int y, byte x) { }D. Public Object ConstOver (int x, int y, int z) { }E. Public void ConstOver (byte x, byte y, byte z) { }答案:( AC )Question No: 9Given:1. public class MethodOver {2. public void setVar (int a, int b, float c) {3. }4. }Which two overload the setVar method? (Choose Two)A. Private void setVar (int a, float c, int b) { }B. Protected void setVar (int a, int b, float c) { }C. Public int setVar (int a, float c, int b) (return a;)D. Public int setVar (int a, int b, float c) (return a;)E. Protected float setVar (int a, int b, float c) (return c;) 答案:( AC )Question No: 10Given:1. class BaseClass {2. Private float x = 1.0f ;3. protected float getVar ( ) ( return x;)4. }5. class Subclass extends BaseClass (6. private float x = 2.0f;7. //insert code here8. )Which two are valid examples of method overriding? (Choose Two)A. Float getVar ( ) { return x;}B. Public float getVar ( ) { return x;}C. Float double getVar ( ) { return x;}D. Public float getVar ( ) { return x;}E. Public float getVar (float f ) { return f;}答案:( BD )Question No: 11Which two demonstrate an “is a” relationship? (Choose Two)A. public interface Person { }public class Employee extends Person { }B. public interface Shape { }public class Employee extends Shape { }C. public interface Color { }public interface Employee extends Color { }D. public class Species { }public class Animal (private Species species;)E. interface Component { }Class Container implements Component (Private Component[ ] children;)答案:( CE )Question No: 12Which statement is true?A. An anonymous inner class may be declared as final.B. An anonymous inner class can be declared as private.C. An anonymous inner class can implement multiple interfaces.D. An anonymous inner class can access final variables in any enclosing scope.E. Construction of an instance of a static inner class requires an instance of the enclosing outer class.答案:( )Question No 13Given:1. package foo;2.3. public class Outer (4. public static class Inner (5. )6. )Which statement is true?A. An instance of the Inner class can be constructed with “new Outer.Inner ()”B. An instance of the inner class cannot be constructed outside of package foo.C. An instance of the inner class can only be constructed from within the outer class.D. From within the package bar, an instance of the inner class can be constructed with “new inner()”答案:( )Question No 14Exhibit:1. public class enclosingone (2. public class insideone{}3. )4. public class inertest(5. public static void main (string[]args)(6. enclosingone eo= new enclosingone ();7. //insert code here8. )9. )Which statement at line 7 constructs an instance of the inner class?A. InsideOnew ei= eo.new InsideOn();B. Eo.InsideOne ei = eo.new InsideOne();C. InsideOne ei = EnclosingOne.new InsideOne();D. EnclosingOne.InsideOne ei = eo.new InsideOne(); 答案:( )Question No 15Exhibit:1. interface foo {2. int k = 0;3. }4.5. public class test implements Foo (6. public static void main(String args[]) (7. int i;8. Test test = new test ();9. i= test.k;10.i= Test.k;11.i= Foo.k;12.)13.)14.What is the result?A. Compilation succeeds.B. An error at line 2 causes compilation to fail.C. An error at line 9 causes compilation to fail.D. An error at line 10 causes compilation to fail.E. An error at line 11 causes compilation to fail. 答案:( )Question No 16Given:1. //point X2. public class foo (3. public static void main (String[]args) throws Exception {4. printWriter out = new PrintWriter (new5. java.io.outputStreamWriter (System.out), true;6. out.printIn(“Hello”);7. )8. }Which statement at PointX on line 1 allows this code to compile and run?A. Import java.io.PrintWriter;B. Include java.io.PrintWriter;C. Import java.io.OutputStreamWriter;D. Include java.io.OutputStreamWriter;E. No statement is needed.答案:( )Question No 17Which two statements are reserved words in Java? (Choose Two)A. RunB. ImportC. DefaultD. Implement答案:( )Question No 18Which three are valid declarations of a float? (Choose Three)A. Float foo = -1;B. Float foo = 1.0;C. Float foo = 42e1;D. Float foo = 2.02f;E. Float foo = 3.03d;F. Float foo = 0x0123;答案:( )Question No 19Leading the way in IT testing and certification tools, Question No 19Given:8. int index = 1;9. boolean[] test = new Boolean[3];10. boolean foo= test [index];What is the result?A. Foo has the value of 0.B. Foo has the value of null.C. Foo has the value of true.D. Foo has the value of false.E. An exception is thrown.F. The code will not compile.答案:( )Question No 20Given:1. public class test(2. public static void main(string[]args){3. string foo = args [1];4. string foo = args [2];5. string foo = args [3];6. }7. )And command line invocation:Java Test red green blueWhat is the result?A. Baz ha s the value of “”B. Baz has the value of nullC. Baz has the value of “red”D. Baz has the value of “blue”E. Bax has the value of “green”F. The code does not compile.G. The program throws an exception.答案:( )Question No 21Given:8. int index = 1;9. int [] foo = new int [3];10.int bar = foo [index];11.int baz = bar + index;What is the result?A. Baz has the value of 0B. Baz has the value of 1C. Baz has the value of 2D. An exception is thrown.E. The code will not compile.答案:( )Question No 22Given:1. public class foo {2. public static void main (String[]args) {3. String s;4. system.out.printIn (“s=” + s);5. }6. }What is the result?A. The code compiles and “s=” is printed.B. The code compiles and “s=null” is printed.C. The code does not compile because string s is not initialized.D. The code does not compile because string s cannot be referenced.E. The code compiles, but a NullPointerException is thrown when toString is called.答案:( )Question No 23Which will declare a method that forces a subclass to implement it?A. Public double methoda();B. Static void methoda (double d1) {}C. Public native double methoda();D. Abstract public void methoda();E. Protected void methoda (double d1){}答案:( )Question No 24You want subclasses in any package to have access to members of a superclass. Which is the most restrictive access modifier that will accomplish this objective?A. PublicB. PrivateC. ProtectedD. TransientE. No access modifier is qualified答案:( )Question No 25Given:1. abstract class abstrctIt {2. abstract float getFloat ();3. }4. public class AbstractTest extends AbstractIt {5. private float f1= 1.0f;6. private float getFloat () {return f1;}7. }What is the result?A. Compilation is successful.B. An error on line 6 causes a runtime failure.C. An error at line 6 causes compilation to fail.D. An error at line 2 causes compilation to fail.答案:( )Question No 26Exhibit:1. public class test(2. public int aMethod()[3. static int i=0;4. i++;5. return I;6. ]7. public static void main (String args[]){8. test test = new test();9. test.aMethod();10.int j = test.aMethod();11.System.out.printIn(j);12.}13.)What is the result?A. Compilation will fail.B. Compilation will succeed and the program will print “0”C. Compilation will succeed and the program will print “1”D. Compilation will succeed and the program will print “2”答案:( )Question No 27Given:1. class super {2. public float getNum() {return3.0f;}3. }4.5. public class Sub extends Super {6.7. }Which method, placed at line 6, will cause a compiler error?A. Public float getNum() {return 4.0f; }B. Public void getNum () { }C. Public void getNum (double d) { }D. Public double getNum (float d) {retrun 4.0f; }答案:( )Question No 28Which declaration prevents creating a subclass of an outer class?A. Static class FooBar{}B. Private class FooBar{}C. Abstract public class FooBar{}D. Final public class FooBar{}E. Final abstract class FooBar{}答案:( )Question No 29Given:1. byte [] arry1, array2[];2. byte array3 [][];3. byte[][] array4;If each array has been initialized, which statement will cause a compiler error?A. Array2 = array1;B. Array2 = array3;C. Array2 = array4;D. Both A and BE. Both A and CF. Both B and C答案:( )Question No 30Exhibit:1. class super (2. public int I = 0;3.4. public super (string text) (5. I = 16. )7. )8.9. public class sub extends super (10. public sub (string text) (11. i= 212. )13.14. public static void main (straing args[]) (15. sub sub = new sub (“Hello”);16. system.out. PrintIn(sub.i);17. )18. )What is the result?A. Compilation will fail.B. Compilation will succeed and the program will print “0”C. Compilation will succeed and the program will print “1”D. Compilation will succeed and the program will print “2”答案:( )Question No 31Given:1. public class returnIt (2. returnType methodA(byte x, double y) (3. return (short) x/y * 2;4. )5. )What is the valid returnType for methodA in line 2?A. IntB. ByteC. LongD. ShortE. FloatF. Double答案:( )Question No 32Given the ActionEvent, which method allows you to identify the affected component?A. GetClass.B. GetTarget.C. GetSource.D. GetComponent.E. GetTargetComponent.答案:( )Question No 33Which is a method of the MouseMotionListener interface?A. Public void mouseMoved(MouseEvent)B. Public boolean mouseMoved(MouseEvent)C. Public void mouseMoved(MouseMotionEvent)D. Public boolean MouseMoved(MouseMotionEvent)E. Public boolean mouseMoved(MouseMotionEvent)答案:( )Question No 34Exhibit:1. import java.awt*;2.3. public class X extends Frame (4. public static void main(string []args) (5. X x = new X ();6. X.pack();7. x.setVisible(true);8. )9.10. public X () (11. setlayout (new GridLayout (2,2));12.13. Panel p1 = new panel();14. Add(p1);15. Button b1= new Button (“One”);16. P1.add(b1);17.18. Panel p2 = new panel();19. Add(p2);20. Button b2= new Button (“Two”);21. P2.add(b2);22.23. Button b3= new Button (“Three”);24. add(b3);25.26. Button b4= new Button (“Four”);27. add(b4);28. )29. )Which two statements are true? (Choose Two)A. All the buttons change height if the frame height is resized.B. All the buttons change width if the Frame width is resized.C. The size of the button labeled “One” is constant ev en if the Frame is resized.D. Both width and height of the button labeled “Three” might change if the Frame is resized.答案:( )Question No 35You are assigned the task of building a panel containing a TextArea at the top, a label directly below it,and a button directly below the label. If the three components are added directly to the panel. Whichlayout manager can the panel use to ensure that the TextArea absorbs all of the free vertical space whenthe panel is resized?A. GridLayout.B. CardLayout.C. FlowLayout.D. BorderLayout.E. GridBagLayout.答案:( )Question No 36Which gets the name of the parent dire ctory file “file.txt”?A. String name= File.getParentName(“file.txt”);B. String name= (new File(“file.txt”)).getParent();C. String name = (new File(“file.txt”)).getParentName();D. String name= (new File(“file.txt”)).getParentFile();E. Directory dir=(ne w File (“file.txt”)).getParentDir();String name= dir.getName();答案:( )Question No 37Which can be used to encode charS for output?A. Java.io.OutputStream.B. Java.io.OutputStreamWriter.C. Java.io.EncodeOutputStream.D. Java.io.EncodeWriter.E. Java.io.BufferedOutputStream.答案:( )Question No 38The file “file.txt” exists on the file system and contsins ASCII text.Given:38. try {39. File f = new File(“file.txt”);40. OutputStream out = new FileOutputStream(f, true);41. }42. catch (IOException) {}What is the result?A. The code does not compile.B. The code runs and no change is made to the file.C. The code runs and sets the length of the file to 0.D. An exception is thrown because the file is not closed.E. The code runs and deletes the file from the file system. 答案:( )Question No 39Which constructs a DataOutputStream?A. New dataOutputStream(“out.txt”);B. New dataOutputStream(new file(“out.txt”));C. New dataOutputStream(new writer(“out.txt”));D. New dataOutputStream(new F ileWriter(“out.txt”));E. New dataOutputStream(new OutputStream(“out.txt”));F. New dataOutputStream(ne w FileOutputStream(“out.txt”));答案:( )Question No 40What writes the text “” to the end of the file “file.txt”?A. OutputStream out= new FileOutp utStream (“file.txt”); Out.writeBytes (“/n”);B. OutputStream os= new FileOutputStream (“file.txt”, true); DataOutputStream out = new DataOutputStream(os);out.writeBytes (“/n”);C. OutputStream os= new FileOutputStream (“file.txt”); DataOutputStream out = new DataOutputStream(os);out.writeBytes (“/n”);D. OutputStream os= new OutputStream (“file.txt”, true); DataOutputStream out = new DataOutputStream(os);out.writeBytes (“/n”);答案:( )Question No 41Given:1. public class X (2. public object m () {3. object o = new float (3.14F);4. object [] oa = new object [1];5. oa[0]= o;6. o = null;7. return oa[0];8. }9. )When is the float object created in line 3, eligible for garbage collection?A. Just after line 5B. Just after line 6C. Just after line 7 (that is, as the method returns)D. Never in this method.答案:( )Question No 42Given:3. string foo = “ABCDE”;4. foo.substring(3);5. foo.concat(“XYZ”);6.Type the value of foo at line 6.答案:( )Question No 43Which method is an appropriate way to determine the cosine of 42 degrees?A. Double d = Math.cos(42);B. Double d = Math.cosine(42);C. Double d = Math.cos(Math.toRadians(42));D. Double d = Math.cos(Math.toDegrees(42));E. Double d = Math.cosine(Math.toRadians(42));答案:( )Question No 44You need to store elements in a collection that guarantees that no duplicates are stored and all elementscan be accessed in natural order. Which interface provides that capability?A. Java.util.Map.B. Java.util.Set.C. Java.util.List.D. Java.util.StoredSet.E. Java.util.StoredMap.F. Java.util.Collection.答案:( )Question No 45Which statement is true for the class java.util.HashSet?A. The elements in the collection are ordered.B. The collection is guaranteed to be immutable.C. The elements in the collection are guaranteed to be unique.D. The elements in the collection are accessed using a unique key.E. The elements in the collections are guaranteed to be synchronized. 答案:( )Question No 46Given:1. public class IfTest (2. public static void main(string[]args) {3. int x = 3;4. int y = 1;5. if (x = y)6. system.out.printIn(“Not equal”);7. else8. system.out.printIn(“Equal”);9. }10. )What is the result?A. The output is “Equal”B. The output in “Not Equal”C. An error at line 5 causes compilation to fall.D. The program executes but does not print a message.答案:( )Question No 47Exhibit:1. public class test (2. public static void main(string args[]) {3. int 1= 0;4. while (i) {5. if (i==4) {6. break;7. }8. ++i;9. }10.11. }12. )What is the value of i at line 10?A. 0B. 3C. 4D. 5E. The code will not compile.答案:( )Question No 48Given:3. int i= 1, j= 10 ;4. do (5. if (i++> --j) continue;6. ) while (i<5);After execution, what are the values for I and j?A. i = 6 and j= 5B. i = 5 and j= 5C. i = 6 and j= 4D. i = 5 and j= 6E. i = 6 and j= 6答案:( )Question No 49Given:1. switch (i) {2. default:310-025Leading the way in IT testing and certification tools, - 27 -3. System.out.printIn(“Hello”);4. }What are the two acceptable types for the variable i? (Choose Two)A. CharB. ByteC. FloatD. DoubleE. Object答案:( )Question No 50Given:1. public class foo {2. public static void main (string[]args)3. try {return;}4. finally {system.out.printIn(“Finally”);}5. }6. }What is the result?A. The program runs and prints nothing.B. The program runs and prints “Finally”C. The code compiles, but an exception is thrown at runtime.D. The code will not compile because the catch block is missing.答案:( )Question No 5151. Which correctly create an array of five empty Strings?A. String a[] = new String[5];for (int i=0;i<5;a[i++]=””);B. String a []={“”,””,””,””,””};C. String a[5];D. String [5] a;E. String [] a = new String[5];for (int i = 0 ;i<5;a[i++] = null);答案:( )Question No 5252. Which cannot be added to a Container?A. an AppletB. a ComponentC. a ContainerD. a MenuComponentE. a panel答案:( )Question No 5353. Which is the return value of Event listener?s method?A. StringB. AWTEventC. voidD. int答案:( )Question No 5454. If we implements MouseListener, which is corrected argument of its method? (short answer) 答案:( )Question No 5555. Us e the operator “>>” and “>>>”. Which statement is true?A. 1010 0000 0000 0000 0000 0000 0000 0000 >> 4 give0000 1010 0000 0000 0000 0000 0000 0000B. 1010 0000 0000 0000 0000 0000 0000 0000 >> 4 give1111 1010 0000 0000 0000 0000 0000 0000C. 1010 0000 0000 0000 0000 0000 0000 0000 >>> 4 give0000 1010 0000 0000 0000 0000 0000 0000D. 1010 0000 0000 0000 0000 0000 0000 0000 >>> 4 give1111 1010 0000 0000 0000 0000 0000 0000答案:( )Question No 5656. Give following fragment.Outer: for(int i=0; i<3; i++)inner:for(int j=0;j<3;j++){If(j>1)break outer;System.out.println(j+”and”+i);}Which will be output?A. 0 and 0B. 0 and 1C. 0 and 2D. 0 and 3E. 1 and 0F. 1 and 1G. 1 and 2H. 1 and 3I. 2 and 0 J. 2 and 1 K. 2 and 2 L. 2 and 3答案:( )Question No 5757. Examine the following code which includes an inner class:public final class Test4 implements A{class Inner{void test(){if (Test4.this.flag);{sample();}}private boolean flag=false;}public void sample(){System.out.println(“Sample”);}public Test4(){(new Inner()).test();}public static void main(String args[]){new Test4();}}What is the result:A.Print out “Sample”B.Program produces no output but termiantes correctly.C. Program does not terminate.D.The program will not compileQuestion No 5858. What is written to the standard output given the following statement: System.out.println(4|7);Select the right answer:A.4B.5C.6D.7E.0答案:( )Question No 5959. Look the inheritance relation:person|----------------| |man womanIn a source of java have the following line:person p=new man();What statement are corrected?A. The expression is illegal.B. Compile corrected but running wrong.C. The expression is legal.D. Will construct a person?s object.答案:( )Question No 6060. Look the inheritance relation:person|----------------| |man womanIn a source of java have the following line:woman w=new man():What statement are corrected?A. The expression is illegal.B. Compile corrected but running wrong.C. The expression is legal.D. Will construct a woman object.答案:( )Question No 6161. Which can NOT be used in declaring or declaring and initializing an automatic (method local) variable?A. finalB. staticC. expressionsD. Constants of non-primitive typeE. initialized arrays (such as “ {“Hello”,”Good bye”}”).答案:( )问答题:1、请简述bean实例的生命周期?2、请写出EJB的几种类型?3、请简述remote接口和home接口主要作用?4、如何给weblogic指定大小的内存?上机题目:请使用一种语言写出用户登陆程序(时间20分钟)。
SCJP官方题库

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

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

●考试大纲●第一部分:Java语言基础●第二部分:流程控制●第三部分:面向对象封装,继承,多态●第四部分:异常处理●第五部分:多线程●第六部分:Java 垃圾回收机制●第七部分:Java I/O●第八部分:Java集合和泛型●第九部分:Java SE实用APIQUESTION 1Given the code in the exhibit.What is the result?A. Compilation failsB. An exception is thrown at runtime.C. An instance of Forest is serialized.D. An instance of Forest and an instance of Tree are both serialized.Answer: ( B )执行时期会抛出java.io.NotSerializableExcetpion异常。
Tree必须实现Serialized接口;因为Forest实现了序列化,并且引用了Tree,但是Tree没有实现序列化!!当一个实现序列化的类在类体里调用另外一个类的时候,那么另外一个类也要实现序列化!如果没有实现,则会报出运行时异常!! 如果要实现序列化,他的成员变量也必须实现序列化.本题中Tree没有实现序列化,所以会产生java.io.NotSerializableException的运行异常!参考大纲:IO操作—对象的序列化序列化的过程就是对象写入字节流和从字节流中读取对象。
见SCJP.u1. SerializableTestQUESTION 2Which code, inserted at line 14, will allow this class to correctly serialized anddesterilized?A. s.defaultReadObject ();B. this = s.defaultReadObject ();C. y = s.default (); x = s.readInt ();D. x = s.readInt(); y = s.readInt ();Answer: ( D )在反序列化方法中,从s对象中读取两个整数. 序列化是写对象,反序列化是读对象…参考大纲:IO操作—对象的序列化QUESTION 3Given the exhibit.What is the result?A. 0B. 1C. 4D. Compilation failsE. An exception is thrown at runtimeAnswer: ( D ) 产生illegal escape character 非法转意符的编译错误split()字符切割器本题是想用空格来分割字符串,只能用“ ”或者“\\ s”来分割,“\ s”没有这个转意字符!所以会报编译错误……tab可以用“\ t”;“\”可以用”\\”表示.String的split方法用来分割字符串,这个方法接受一个正则表达式,根据表达式来分割,“\\s”表示空格,“\s”没有这个转意字符,所以会产illegal escape character的编译错误。
java考试试题及答案

java考试试题及答案一、选择题(每题2分,共20分)1. 下列哪个是Java的基本数据类型?A. StringB. IntegerC. intD. Object答案:C2. Java中的main方法是程序的入口点,它属于哪个类?A. ng.ObjectB. ng.SystemC. ng.RuntimeD. java.applet.Applet答案:A3. 下列哪个关键字用于定义类?A. classB. publicC. staticD. void答案:A4. Java中的哪个关键字用于实现接口?A. implementsB. extendsC. classD. interface答案:A5. 下列哪个是Java集合框架中的接口?A. ArrayListB. ListC. LinkedListD. HashMap答案:B6. 下列哪个不是Java的控制流语句?A. ifB. forC. switchD. while答案:C7. Java中的哪个类提供了日期和时间的处理功能?A. java.util.DateB. java.util.CalendarC. java.time.LocalDateD. java.time.LocalDateTime答案:B8. 下列哪个是Java的异常处理关键字?A. tryB. catchC. finallyD. all of the above答案:D9. 下列哪个不是Java的访问修饰符?A. publicB. privateC. protectedD. global答案:D10. 下列哪个不是Java的注释方式?A. // 单行注释B. /* 多行注释 */C. / 文档注释 */D. # 预处理指令答案:D二、填空题(每空2分,共20分)1. Java语言是________面向对象的编程语言。
答案:完全2. Java程序的执行流程是:编写源代码,编译成字节码,通过________加载并执行。
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考试Java能够自动处理对象的引用和间接引用,实现自动的无用单元收集,使用户不必为存储管理问题烦恼,能更多的时间和精力花在研发上。
下面是关于java程序员的认证SCJP考试,欢迎大家参考!课程:SL-275 JAVA语言编程本课程使学员掌握如何使用标准JAVA Development Kit,V1.1 (JDK) 开发应用程序和applets。
在本课程中您将学会JAVA 语言的语法。
如何使用JAVA 来创建图形用户接口 (GUI), 事件处理机制, 例外处理, 通过设计与开发各种JAVA 程序来获得实际的编程经验. 您也将学到文件输入/输出(I/O)、多线程和网络的知识.。
本课程适用于熟悉C或C++的编程人员, 也适用于想参加Sun JAVA 认证考试的学员。
预备知识:学习本课程之前必须具备以下能力能够编译C 或C++ 程序或者已经参加过SL-110课程;能够创建和编译简单的程序;使用 WWW(World wide web) 浏览器, 如: Netscape;能够使用vi或者OpenWindows的文件编辑器;使用基本UNIX的命令。
课程学习完成后,将具备以下能力:使用JAVA 编程语言创建JAVA 应用程序和applets定义和描述垃圾搜集, 安全性和JAVA 虚拟机(JVM)描述和使用 JAVA 语言面向对象的特点开发图形用户接口 (GUI),利用JAVA支持的多种布局管理描述和使用JAVA 1.1 的事件处理模式使用JAVA 语言的鼠标输入, 文本, 窗口和菜单窗使用JAVA的例外处理来控制程序执行和定义用户自己的例外事件使用JAVA 语言的先进的面向对象特点, 包括方法重载, 方法覆盖, 抽象类, 接口等等实现文件的输入/输出(I/O) 使用JAVA 语言内在的线程模式来控制多线程使用JAVA的Sockets 机制进行网络通信参加Java程序员认证考试 java程序员认证考试考试号为310-025。
SCJP 6.0认证教战手册考题1

public void bar(int x){}
public int bar(String x){return 1;}
public void bar(int x, int y){} } 參考:6-5 繼承
第13題
Given: 1. 2.
參考:4-1 條件控制
4
SCJP 6.0 認證教戰手冊 黃彬華著 碁峰出版
第9題 Given:
11. String[] elements = {"for", "tea", "too"}; 12. String first = (elements.length>0) ? elements[0] : null; What is the result? A. Compilation fails. B. An exception is thrown at runtime. C. The variable first is set to null. D. The variable first is set to elements[0]. 答案:D 參考:4-1 條件控制、5-2 1 維陣列介紹
6
SCJP 6.0 認證教戰手冊 黃彬華著 碁峰出版
3.
new Barn.go("hi", 1);
4.
new Barn.go("hi", "world", 2);
5.
}
6.
public void go(String... y, int x){
7.
System.out.print(y[y.length-1] + " ");
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中存放的元素是无序不重复的。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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)方法。
例题4:y Text Area, javaB.B etade to super(nroent about the garbage collection mechanism are true?A.Garbage collection require additional programe code in cases ultiple threads are running・B.The programmer can indicate that a reference through a local variable is no longer of interest.C.The programmer has a mechanism that explicity and immediately frees the memory used by Java objects・D.The garbage collection mechanism can free the memory used by Java Object at explection time・E.The garbage collection system never reclaims memory from objects ethod:1)public void method(){2)String a,b;3)a二nee over” );5)System.out・println(a+b+” ok” );6)a=null;7)a=b;8)System.out.println(a);9)}In the absence of piler optimization, ethod called getID ethod?A.It is a reference to the object directly affected by the cause of the event.B.11 is an indication of the nature of the cause of the event.C.It is an indication of the position of the mouse ouse click, it is an indication of the text under the mouse at the time of the event.E.It tells the state of certain keys on the keybord at the time of the event.F.It is an indication of the time at ent about listener is true?A.Most ponent alloultiple listeners to be added.B.If multiple listener be add to a single ponent, the event only affected one listener.C・ ponent don?t alloultiple listeners to be add・D.The listener mechanism alloethod as many times as is needed, specifying as many different listeners as your design require.4o A、D控件可以同时使用多个"addXxxxListener方法加入多个监听器。
并且当多个监听器加入到同一控件中时,事件可以响应多个监听器,响应是没有固定顺序的。
5.Give the follople{public static void main(String args[] ){int 1=0;do{System.out.println( u Doing it for 1 is:" +1);}.out.println( “Finish” );}}yClass{//do other thing***} E. class MyClass{//do something-••}15o A、EX处可以是一个输入,包的定义,类的定义。
由于常量或变量的声明只能在类中或方法中,故不能选择C;由于在一个文件中只能有一个public类,故不能选择D。
16.Give this class outline:class Example {private int x;//rest of class body-}Assuming that x invoked by the code java Example, ent can made x be directly accessible in main() method of Example.java?A.Change private int x to public int xB.change private int x to static int xC.Change private int x to protected int xD.change private int x to final int x16o B静态方法除了自己的参数外只能直接访问静态成员。
访问非静态成员,必须先实例化本类的一个实例,再用实例名点取。
17.the piece of preliminary analsis any unrelated parts of a project“The polygon object is a draation stored in a vector, a color, length and ember variable should be accessible only by same package, odifer odiferD.private18o C此题考点是高级访问控制。
请考生查阅高级访问控制说明表格。
19.ethod in a java class corrected?A.public native void method() {}B.public native void method();C.public native method();D.public void method(){native;}E.public void native method();19o Bnative关键字指明是对木地方法的调用,在JAVA中是只能访问但不能写的方法,它的位置在访问权限修饰语的后面及返回值的前面。
20.odifer should be applied to a declaration of a class member variable for the value of variable to remain constant after the creation of the object? 20 o final定义常量的方法是在变量定义前加final关键字。
21.ain() method return of a application?A.StringB.byteC.charD.void21o Dmain()方法没有返回值,所以必须用void修饰。
main()方法的返回值不能任意修改。
22.ent of main() method of application?A.String argsB.String ar[]C.Char args[][]D.StringBuffer arg[]22 o Bmain()方法的参数是字符串数组,参数名可以任意定义。
23.“The Employee object is a person, An Employee has appointment store in a vector, a hire date and a number of dependent ”short ansent declare a class of Employee・23o public class Employee extends Person这也是真实考试中常见的一种题型。
要注意题目叙述中“is a” 表示“extends”的含义。
24.Give the follople{public Example(){//do something}protected Example(int i){//do something}protected void method(){//do something}}public class Hello extends Example {//member method and member variable}ethods are coiTected added to the class Hello?A.public void Example(){}B.public void method(){}C.protected void method(){}D.private void method(){}24o A、B、C考察的知识点是方法覆盖,其中要注意的是方法覆盖时,子类方法的访问权限不能小于父类方法的访问权限。