JAVA基础面试题2答案版_第1页
JAVA基础面试题2答案版_第2页
JAVA基础面试题2答案版_第3页
JAVA基础面试题2答案版_第4页
JAVA基础面试题2答案版_第5页
已阅读5页,还剩11页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、JAVA语言基础笔试题-2Question1Given:classApublicvoidprocess()System.out.print(“A)“classBextendsApublicvoidprocess()throwsRuntimeExceptioncess();if(true)thrownewRuntimeException();System.out.print(“B)”publicstaticvoidmain(Stringargs)try(A)newB().process();catch(Exceptione)System.out.print(“Exception)“Whatist

2、heresult?ExceptionAExceptionAExceptionBABExceptionCompilationfailsbecauseofanerrorinline14.Compilationfailsbecauseofanerrorinline19.答案:B考点:方法的重写(重写方法异常抛出部分的理解)多态异常处理说明:子类重写父类方法,不能抛出比父类方法更多的异常,但此处子类重写方法声明抛出了RuntimeException,不算多抛,算是平抛,是可以的。RuntimeException是Exception的子类,可以被Exception捕获。Question2Given:st

3、aticclassAvoidprocess()throwsExceptionthrownewException();TOC o 1-5 h zstaticclassBextendsAvoidprocess()System.out.println(“B)”publicstaticvoidmain(Stringargs)18.Aa=newB();cess();Whatistheresult?BThecoderunswithnooutput.Anexceptionisthrownatruntime.Compilationfailsbecauseofanerrorinline15.Compilatio

4、nfailsbecauseofanerrorinline18.Compilationfailsbecauseofanerrorinline19.答案:F考点:方法的重写(重写方法异常抛出部分的理解)多态静态内部类以及其实例的创建说明:19.cess();是多态调用,调用的应该是类B的process方法,这个方法只是允许抛出RuntimeException,所以19行在理论上不需要进行异常相关处理,系统会自动抛出该异常,但是多态只是在运行时,系统方能识别,在编译的时候,系统还是按照类A的process方法来进行验证,所以出现错误,因为类A抛出的是检查异常,必须显式被捕获或者抛出。Question

5、3Given:staticclassAvoidprocess()throwsExceptionthrownewException();TOC o 1-5 h zstaticclassBextendsAvoidprocess()System.out.println(“B”);publicstaticvoidmain(Stringargs)newB().process();Whatistheresult?BThecoderunswithnooutput.Compilationfailsbecauseofanerrorinline12.Compilationfailsbecauseofanerror

6、inline15.Compilationfailsbecauseofanerrorinline18.答案:A考点:方法的重写(重写方法异常抛出部分的理解)静态内部类以及其实例的创建Question4Given:tryResourceConnectioncon=resourceFactory.getConnection();Resultsr=con.query(“GETINFOFROMCUSTOM)ER”info=r.getData();con.close();catch(ResourceExceptionre)errorLog.write(re.getMessage();returninfo;

7、WhichistrueifaResourceExceptionisthrownonline86?Line92willnotexecute.Theconnectionwillnotberetrievedinline85.Theresourceconnectionwillnotbeclosedonline88.Theenclosingmethodwillthrowanexceptiontoitscaller.答案:C考点:try.catch结构的理解异常的捕获和处理说明:由于抛出的ResourceException,能够被catch块捕获(标配),所以异常在方法中就被处理掉了,不会抛出该方法。根据

8、try块操作上规定,一旦抛出异常,抛出异常语句后续部分的try块语句将不再运行。Question5ClicktheExhibitbutton.publicclassApublicvoidmethod1()Bb=newB();b.method2();/morecodeherepublicclassBpublicvoidmethod2()Cc=newC();c.method3();5./morecodehere6.7.publicclassCpublicvoidmethod3()/morecodehereGiven:tryAa=newA();a.method1();catch(Exceptione

9、)System.out.print(“anerroroccurred!)”WhichtwoaretrueifaNullPointerExceptionisthrownonline3ofclassC?(Choosetwo.)Theapplicationwillcrash.Thecodeonline29willbeexecuted.Thecodeonline5ofclassAwillexecute.Thecodeonline5ofclassBwillexecute.Theexceptionwillbepropagatedbacktoline27.答案:BE考点:异常的抛出、捕获和处理说明:一般来说

10、,异常的抛出,最终终将被处理,本方法不处理,则抛给主调方法,关键是要能抛的出去,因为NullpointerException是RuntimeException,所以一路没有阻碍,最终propagatedback到达27行,Exception是所有异常的父类,所以该异常在这里被处理了,Question6ClicktheExhibitbutton.publicclassApublicvoidmethod1()tryBb=newB();b.method2();/morecodeherecatch(TestExceptionte)thrownewRuntimeException(te);publicc

11、lassBpublicvoidmethod2()throwsTestException/morecodeherepublicclassTestExceptionextendsExceptionGiven:publicvoidmethod()Aa=newA();a.method1();WhichistrueifaTestExceptionisthrownonline3ofclassB?Line33mustbecalledwithinatryblock.Theexceptionthrownbymethod1inclassAisnotrequiredtobecaught.Themethoddecla

12、redonline31mustbedeclaredtothrowaRuntimeException.Online5ofclassA,thecalltomethod2ofclassBdoesnotneedtobeplacedinatry/catchblock.答案:B考点:异常抛出、捕获和处理说明:第8行,把检查异常TestException封装在RuntimeException中抛出是可以,因为系统仍然认为你抛出的是一个运行时异常,任何方法都默认支持抛出运行时异常。Question7Given:publicstaticvoidmain(Stringargs)tryargs=null;args0

13、=”test;”System.out.println(args0);catch(Exceptionex)System.out.println(“Exception)”catch(NullPointerExceptionnpe)System.out.println(“NullPointerException”)Whatistheresult?testExceptionCompilationfails.NullPointerException答案:C考点:异常的捕获处理说明:Exception是能够捕获所有异常的万金油,其一般放在捕获块的最后一环,用来捕获所有的漏网之鱼,如果放在捕获块最前头,将导

14、致后头的捕获块永远无法得到运行,最后产生编译失败。Question8Given:staticvoidtest()throwsErrorif(true)thrownewAssertionError();System.out.print(“test“)publicstaticvoidmain(Stringargs)trytest();catch(Exceptionex)System.out.print(“exception)“;System.out.print(“end”)Whatistheresult?endCompilationfails.exceptionendexceptiontesten

15、dAThrowableisthrownbymain.AnExceptionisthrownbymain.答案:E考点:Error和Exception的关系的理解说明:Error和Exception是兄弟类,其有一个共同的父类Throwable,所以Error也可以被抛出。Exception捕获块无法捕获Error,所以这里Error会被抛出,由JVM做了最终处理。Question9Given:staticvoidtest()tryStringx=null;System.out.print(x.toString()+”);TOC o 1-5 h zfinallySystem.out.print(

16、“finally)”;publicstaticvoidmain(Stringargs)trytest();catch(Exceptionex)System.out.print(“exception”);Whatistheresult?nullfinallynullfinallyCompilationfails.finallyexception答案:E考点:try.catch.finally结构理解说明:允许存在try.finally结构,即使没有catch块的存在。这里try块会产生一个经典的异常NullPointerException,其是RuntimeException,可以被默认抛出,但

17、抛出之前,需要执行一次finally.Question10Given:staticvoidtest()throwsRuntimeExceptiontrySystem.out.print(“test)”thrownewRuntimeException();catch(Exceptionex)System.out.print(“exception”);publicstaticvoidmain(Stringargs)trytest();catch(RuntimeExceptionex)System.out.print(“urntime”);System.out.print(“end)”Whatist

18、heresult?testendCompilationfails.testruntimeendtestexceptionendAThrowableisthrownbymainatruntime.答案:D考点:异常的抛出、捕获和处理说明:本题test方法已经在内部把异常处理,该异常没有被抛给main方法。Question11Givenamethodthatmustensuethatitsparameterisnotnull:publicvoidsomeMethod(Objectvalue)/checkfornullvalueSystem.out.println(value.getClass();

19、What,insertedatline12,istheappropriatewaytohandleanullvalue?assertvalue=null;assertvaluenull,valueisnull!if(value=null)thrownewAssertionException(“valueisnull!)”if(value=null)thrownewIllegalArgumentException(“valueisnull)”答案:D考点:常见异常类的使用Question12ClicktheExhibitbutton.publicclassClassApublicvoidmeth

20、odA()ClassBclassB=newClassB();classB.getValue();And:classClassBpublicClassCclassC;22.publicStringgetValue()returnclassC.getValue();And:classClassCpublicStringvalue;32.publicStringgetValue()value=“ClassB”;returnvalue;Given:ClassAa=newClassA();a.methodA();Whatistheresult?Compilationfails.ClassCisdispl

21、ayed.Thecoderunswithnooutput.Anexceptionisthrownatruntime.答案:D考点:常见异常的识别(NullpinterException)说明:第24行,对classC的getValue方法调用,由于classC的实例不存在,所以无法运行。抛出异常,这种情况只有在运行的时候才知道,不会认为是编译错误。Question13Given:publicclassFoostaticinta;statica0=2;publicstaticvoidmain(Stringargs)Whichexceptionorerrorwillbethrownwhenapro

22、grammerattemptstorunthiscode?java.lang.StackOverflowErrorjava.lang.IllegalStateExceptionjava.lang.ExceptionlnlnitializerErrorjava.lang.ArraylndexOutOfBoundsException答案:C考点:静态块以及常见异常的识别说明:在静态块中,对a进行了调用,但a没有指向任何对象,所以抛出NullpinterException,但由于是发生在静态块中,所以系统最终抛出了ExceptionlnlnitializerErrorQuestion14Given:

23、publicclassClassApublicvoidcount(inti)count(+i);And:ClassAa=newClassA();a.count(3);Whichexceptionorerrorshouldbethrownbythevirtualmachine?StackOverflowErrorNullPointerExceptionNumberFormatExceptionIllegalArgumentExceptionExceptionlnlnitializerError答案:A考点:递归调用理解、堆栈的运作模式说明:此处count方法产生无穷递归调用,最终导致堆栈空间溢出

24、。Question15Given:publicclassBoxer1Integeri;intx;publicBoxer1(inty)x=i+y;System.out.println(x);publicstaticvoidmain(Stringargs)newBoxer1(newInteger(4);Whatistheresult?Thevalue4isprintedatthecommandlineCompilationfailsbecauseofanerrorinline5.Compilationfailsbecauseofanerrorinline9.ANullPointerExceptio

25、noccursatruntime.ANumberFormatExceptionoccursatruntime.AnIllegalStateExceptionoccursatruntime.答案:D考点:自动装箱和拆箱、基本类型和类类型说明:x=i+y,i是类类型为null,这里其实系统是采取一个自动拆箱操作,也就是对value();所以此处抛出一个NullpinterExceptionQuestion16Given:publicclassTestString1publicstaticvoidmain(Stringargs)Stringstr=”420”str+=42;System.out.pr

26、int(str);答案:D考点:字符串概念的理解说明:字符串和任何基本类型相加,最终其将全部转成字符串“420”+42-“420”+newInteger(42).toString();Whatistheoutput?4242046242042Compilationfails.Anexceptionisthrownatruntime.Question17Given:classConverterpublicstaticvoidmain(Stringargs)Integeri=args0;intj=12;System.out.println(“Itis”+(j=i)+“thatj=i”);Whati

27、stheresultwhentheprogrammerattemptstocompilethecodeandrunitwiththecommandjavaConverter12?Itistruethatj=i.Itisfalsethatj=i.Anexceptionisthrownatruntime.Compilationfailsbecauseofanerrorinline13.答案:D考点:命令行参数理解说明:任何的命令行参数,都将被理解为字符串,即使是数字参数也是如此,需要做转换,比女叮ntegeri=Integer.parselnt(argsO);Question18Giventhis

28、methodinaclass:publicStringtoString()StringBufferbuffer=newStringBuffer();buffer.append(“”)returnbuffer.toString();Whichistrue?ThiscodeisNOTthread-safe.TheprogrammercanreplaceStringBufferwithStringBuilderwithnootherchanges.ThiscodewillperformwellandconvertingthecodetouseStringBuilderwillnotenhanceth

29、eperformance.Thiscodewillperformpoorly.Forbetterperformance,thecodeshouldberewritten:return“”答案:B考点:StringBuffer和StringBuilder的理解说明:StringBuffer是线程安全的,速度较慢;StringBuilder是线程不安全的,速度较快。两者API一致,主要是为了克服字符串不变性的特性而存在。Question19Given:publicclassMyLoggerprivateStringBuilderlogger=newStringBuilder();publicvoi

30、dlog(Stringmessage,Stringuser)logger.append(message);logger.append(user);TheprogrammermustguaranteethatasingleMyLoggerobjectworksproperlyforamulti-threadedsystem.Howmustthiscodebechangedtobethread-safe?synchronizethelogmethodreplaceStringBuilderwithStringBufferNochangeisnecessary,thecurrentMyLoggerc

31、odeisalreadythread-safe.replaceStringBuilderwithjustaStringobjectandusethestringconcatenation(+=)withinthelogmethod答案:B考点:StringBuffer和StringBuilder的理解Question20Given:publicStringmakinStrings()Strings=“Fred”s=s+“47”s=s.substring(2,5);s=s.toUpperCase();returns.toString();HowmanyStringobjectswillbecre

32、atedwhenthismethodisinvoked?123456答案:E考点:字符串不变性说明:任何字符串的运算结果都将产生一个新的字符串对象。Question21publicclassTestString3publicstaticvoidmain(Stringargs)/insertcodehereSystem.out.println(s);Whichtwocodefragments,insertedindependentlyatline3,generatetheoutput4247?(Choosetwo.)Strings=“123456789”;s=(s-”123”).replace(

33、1,3,”24-”“)89”;StringBuffers=newStringBuffer(”123456789”);s.delete(0,3).replace(1,3,“24”).delete(4,6);StringBuffers=newStringBuffer(”123456789”);s.substring(3,6).delete(1,3).insert(1,“24”);StringBuilders=newStringBuilder(”123456789”);s.substring(3,6).delete(1,2).insert(1,“24”);StringBuilders=newStri

34、ngBuilder(”123456789”);s.delete(0,3).delete(1,3).delete(2,5).insert(1,“24”);答案:BE考点:StringBufferAPI的使用说明:s.delete(0,3)或者s.subString(0,3)以上均为从0位开始操作,不包含3位。Question22Given:publicclassYikes12.publicstaticvoidgo(Longn)System.out.println(“Long“);publicstaticvoidgo(Shortn)System.out.println(“Short“);publi

35、cstaticvoidgo(intn)System.out.println(“int“);publicstaticvoidmain(Stringargs)shorty=6;longz=7;go(y);go(z);Whatistheresult?intLongShortLongCompilationfails.Anexceptionisthrownatruntime.答案:A考点:重载以及不匹配参数的撮合识别说明:如果基本类型没有对应的方法参数,则往更高精度升级,如果有找到匹配的,则执行。如果基本类型即使升级也无法找到合适的,则进行装箱,升级为类类型,然后寻求匹配,如过能匹配,则成功,不能匹配,

36、则编译失败,在类类型,不会再寻求向上升级。Question23Given:publicclassWowpublicstaticvoidgo(shortn)System.out.println(“short”);publicstaticvoidgo(Shortn)System.out.println(“SHORT)”;publicstaticvoidgo(Longn)System.out.println(“LONG)”;publicstaticvoidmain(Stringargs)Shorty=6;intz=7;go(y);go(z);Whatistheresult?shortLONGSHOR

37、TLONGCompilationfails.Anexceptionisthrownatruntime.答案:C考点:重载以及不匹配参数的撮合识别说明:基本类型可以尝试升级,但如果即使升级也无法匹配的话,就会装箱成为类对象去尝试匹配,匹配失败,则失败,不会去在类层面进行类型升级。类型升级只有在基本类型是可以进行的,自动升级的方向都是从低精度向高精度自动升级。Question24Given:classMakeFilepublicstaticvoidmain(Stringargs)tryFiledirectory=newFile(“d)”;Filefile=newFile(directory,”f)”;if(!file.exists()file.createNewFile();catch(IOExceptione)e.printStackTrace();ThecurrentdirectorydoesNOTcontainadirectorynamedd.Whichthreearetr

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论