OCJP--SCJP--JAVA考試題_第1頁
OCJP--SCJP--JAVA考試題_第2頁
OCJP--SCJP--JAVA考試題_第3頁
OCJP--SCJP--JAVA考試題_第4頁
OCJP--SCJP--JAVA考試題_第5頁
已閱讀5頁,還剩44頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

1、QUESTION 63GIVEN THE EXHIBIT:23.int z = 5 F2425public voidd Certkillerl (int x)(26assert ( x > 0 ),27switch (ii)(2:8case 2 :x = 3,29default :ert fak)30.)31private void Certkiller2 (int y ) assert (y < o) 3233.private void Certklller3 () assert ( Certkiller4(),3435private Boolean Certkillerl ()

2、(i = 6P return falseWhich stateme nt is true?A. All of the assert stateme nts are used appropriately.B. Only the assert stateme nt on line 31 is used appropriatelyC. The assert stateme nts on lines 29 and 31 are used appropriatelyD. The assert stateme nts on lines 26 and 29 are used appropriatelyE.

3、The assert stateme nts on lines 29 and 33 are used appropriatelyF. The assert stateme nts on lines 29 ,31a nd 33 are used appropriatelyG. The assert stateme nts on lines 26,29 and 31 are used appropriately斷言應(yīng)該用在你認(rèn)為”你的程序不可能產(chǎn)生錯誤的地方,而且有沒有啟用斷言,都不會影響程序的正常運行。斷言使用限制:1. 不要在public方法中,用斷言來檢查參數(shù)的正確性;2. 不要讓斷言語句去

4、處理一些程序必須的流程。原因:1.public方法會被別人調(diào)用,你不能保證他一定啟用斷言;如果沒有啟用,那么用斷言來做參數(shù)的檢查也就沒有 意義了。所以不要用斷言來檢查參數(shù),公共方法的參數(shù)一定要用代碼執(zhí)行檢查;2.如果用斷言來控制程序執(zhí)行流程,如果沒有啟用斷言,那么程序就不能正確執(zhí)行下去。另外,斷言語句不可以有任何邊界效應(yīng),不要使用斷言語句去修改變量和改變方法的返回值,如果這樣當(dāng)啟動斷言和不啟動斷言執(zhí)行的結(jié)果會截然不同。斷言的使用時機:1. 檢查流程的不變性:在if-else switch-case的預(yù)期結(jié)果之外可以加上斷言做額外的檢查。2. 內(nèi)部執(zhí)行的不變性:if(true)return ;

5、assert false;3. 檢查 私有方法的參數(shù),結(jié)果等4. 程序運行中的一致性斷言語句不是永遠(yuǎn)會執(zhí)行,可以屏蔽也可以啟用javac -source 1.4 *.java需要java走a啟用assert;當(dāng)判斷條件為FALSE時就拋出錯誤。Answer: ( C )26行不合適:不要對 public方法的參數(shù)斷言29合適:程序員在程序中最不大可能到達(dá)的地方斷言31合適:斷言private方法的參數(shù)33行不合適:啟用和不啟用斷言會產(chǎn)生不同的程序執(zhí)行序參考大綱:異常處理一斷言和AssertionError11public static void rnin (String args)(12Str

6、ing str = *"nuir*13if (str - = null) f14,system ourpnntin C'nuir)F15)else (str hngth () = = 0) 也system.outpnntln ( "zero")else (1&system cut println ("some")19)20What is the result?A. nullB. zeroC. someD. Compilati on failsE. An exceptio n is throw n at run timeAnswe

7、r: ( D )13行會報錯,應(yīng)在15行使用else if參考大綱:流程控制QUESTION 63Give n the exhibit:11 pubhc static void main(Stringargs) (12.try (13 zrg 玄null;14 aegs 0= *tesf 15 Systemout print In(args0r16 ) catch (Enception ex(17 Systemout printin(Exception"),18 catch (NullPointerException npe)(19 System oui prmtln (NullPc

8、innerExcepton"),20. )21. )What is the result?A. testB. Excepti onC. Compilation failsD. NullPoi nterExceptionAnswer: ( C )18行出錯,應(yīng)該先 catch子異常,再 catch Exception ;13 行把 args 賦 null , 14 行會報 NullPointerException如果沒有第13行運行時14行會報 ArrayIndexOutOfBoundsException_異常。參考大綱:異常處理QUESTION 64Give n the exhibi

9、t:1. importjavautil2. .3 pub IkclassLet terASort (4 public static vid mam (Sting args) 5 ArrayList <Stnng> strings = new ArrayList <Strmg> (),6. strings, add CaAaA1'),7. stringsadd (“AjiA"):8. stringsadd沁匕”)9 stringsadd ("AA詔工10. Collect! ons. sort( strings);11 for (String

10、s : strings) System our print (s 4- " ")* )12. 13. )What is the result?A. Compilation failsB. aAaA aAa AAaa AaAC. AAaa AaA aAa aAaAD. AaA AAaa aAaA aAaE. aAa AaA aAaA AAaaF. An excepti on is throw n at run timeAnswer: ( C )第10行將對strings這個集合做自然排序(ASCII小到大,一個一個比較)Collections.sort(List list)

11、對 list 進(jìn)行排序,對 set 不能排序!List里可以放對象,所以當(dāng)list里面存放的是對象的時候就不能用Collections.sort(List list)去排序了。因為 JVM不知道用什么規(guī)則去排序!只有把對象類實現(xiàn)Comparable接口,然后改寫 compareTo()參考大綱:集合QUESTION 65Give n the exhibit:1. import java util *;2 publicWrappedString (3. private String s;4 public WrappedString (String s) (thiss = sT 5. public

12、 static void mam (String args) (6. HashSet<Object> hs = new HashSet <Object> ().7V/rappedString wsl = new WrappcdStnng (*,aardvark,*)t3.WrpecString ws2 = new WrdppcdStrixig ("daidvark")9 String si new String ("aardvark");10 Stung 32 new Stun呂("aeu Jvaik"),11

13、 hs add (wsl), hs add (ws2 ),; hs addtsi), hs add(s2)T12 System, out print(hs.Size (),)What is the result?A. 0B. 1C. 2D. 3E. 4F. Compilation fails.Answer: ( D )Set中存放的元素是無序不重復(fù)的。 元素,如果有則不更改Ws1 ws2是自定義的類,equals方法,判斷set中是否有該 true。s1和s2相等;G. An excepti on is throw n at run time如果你想Set里Add 一個元素,首先他會去調(diào)用se

14、t的值并返回false,如果沒有,則把元素添加進(jìn)去,并返回ws1和 ws2 equals不相等;String的equals方法已經(jīng)改寫,比較兩個對象是否相同,先比較hashcode,如果相同,在用equals方法比較.如果都相同則兩個對象就認(rèn)為是相同的Hashcode是把對象的內(nèi)存地址經(jīng)過運算得來的基本數(shù)據(jù)類型和基本數(shù)據(jù)類型的包裝類還有String類都已經(jīng)覆蓋了 hashcode(), equals(),所以這些對象的值只要一樣就認(rèn)為對象一樣參考大綱:集合QUESTION 66Give n a pre-ge nerics impleme ntati on of a method:11 publ

15、ic static int sum (Ljst list)(12 int sum = 0;13 for (Iteritor iter = list iterator ( X itrf ), )】4mt i = (Integer) iter next () mt Value ().15 sum += i T16. )17. return sum:18. )Which three cha nges must be made to the method sum to use gen erics? (choose three)A. remove line 14B. replace line 14 wi

16、th "int i = iter. next ();"C. replace line 13 with "for ( int i : in tList ) "D. replace line 13 with " for (Iterator iter : in tList )"E. replace the method declaration with "sum (List<int> intList)"F. replace the method declaration with "sum ( Lis

17、t<Integer> intList)"Answer: ( A, C, F )public static int sum(List <lnteger> intList)int sum=0;for(int i : intList )sum += i;return sum;參考大綱:集合和泛型QUESTION 67Given the exhibit;23. Object myObjects= 24newInteger (12),25.newStrung Cfbo")“26newInteger (5),27. new Boolean (true)28. 2

18、9. JTays sort (myObjects);30. for (hit i0f i<myO切"ts lun呂th, i+ t )(31. Sys te m o ut. pr m t(my 0 b j e ct s t . to String ();32. Sysem. 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 ClassCastE

19、xceptation occurs in line 29.D. A ClassCastExceptation occurs in line 31.E. The value of all four object prints in n atural order.Answer: ( C )Arrays.sort(Object a)方法中,a的每一個元素都必須是相互可以比較的(調(diào)用 pareTo(Object o2)。否則會報 ClassCastException 的異常。參考大綱:泛型QUESTION 68Place the code into positi on to create a clas

20、s that maps from Strings to In teger values.The result of executi on must be on e. Some opti ons may be used more tha n once.G(vennn 匸 new)nn put ( * one"', 1);out血tin(仇n getH良外牯右f)一public class NumberHaaes private HashM*p<jnev Hd 5 h Map < Place here public void put(String nap.put(Pl

21、ace herePlace herePlace herePlace KJIBPlace here> Kap 11Place herePlace herepublic |valuereturn keySet().Set<int >Sstclntegei >1HashSat1 Set<Integer.String> |1. St ring >1 Set < String. Integer > iSet<String, mt> SAt<StriD9>X )Answer:()public class NumberNames

22、private HashMapv String , Integer> map = new HashMapv String , Integer>();public void put(Stri ng n ame, In teger value) map.put (n ame, value);public Set<Stri ng> getNames()Retur n map.keySet();QUESTION 69Place a result onto each method call to in dicate what would happe n if the method

23、 call were inserted at line 9. Note: Results can be used more than once.Given1 import java util ,2 class A < >3 匚la&s B extends A 4 public class Test 5 public static void) ergs)(6 List<A> 1istA nev LinkedList<A>();7 B> lists nev LxnkedList<B>().8 LisKObject > listO

24、new Li nkedLi st Object >().91/ Insert code here1011 public static void m*(List< extends A> list) 12 public static void *2(List<list) 13. Method CallsResulthl(lislA);|m2(li5tA1:hl(listB).1*2(listfl |1;al(iistC)jb2(1: 1MethodResultml(listA)Compiles and runs without error 泛型規(guī)范沒問題m2(listA)C

25、ompiles and runs without error 泛型規(guī)范沒問題ml(listB)Compiles and runs without errorB是A的子類,泛型規(guī)范沒問題m2(listB)Does not compileml(listO)Does not compilem2(listO)Does not compileAnswer:()QUESTION 70Give n the exhibit:1 import javanUtil.* .2. public class PQ 3 public static void main (String args)(APriontyQu cu

26、e'"String pq = nc w I'nontyQuc ue " S trm呂=(.5. pqaddfJ,carrot'*);6. pqaddf*applt7-pqadd(Hbanana,*).8 Systtem cut print In (pq poll () +"*' +pqpeek() ±9.)10 1What is the result?A. apple:appleB. carrot:appleC. apple:ba nanaD. banan a:appleE. carrot:carrotF. carrot:

27、ba nanaAnswer: ( C )PriorityQueue優(yōu)先級隊列:預(yù)設(shè)是自然排序,因此pq內(nèi)的元素順序?qū)⑹莂pple->banana->carrotpoll()取第一個元素,取完之后刪除,peek取第一個元素,并不刪除元素QUESTION 71Give n:11.public class key (12.private long idl;13.private long id2;1415ff clasf key methods16.A programmer is develop ing a class Key, that will be used as a key in

28、a sta ndard java.util.HashMap.Which two methods should be overridde n to assure that key works correctly as a key? (choose two)A. public int hashCode ()B. public Boolea n equals (Key k)C. public int compareTo (Object o)D. public Boolea n equals (Object o)Answer: ( A, D )HashMap中的key不能重復(fù),因此必須實現(xiàn)hashCo

29、de和equals方法QUESTION 73Give n the exhibit:2 U insert code here3 private N minimax.4 public N getMin ()( return min.J5 public N getMax () return max.6 public void add (N added) fif (min = null 11 add?d double Value () <min doubleValue ()日min = added,9 if (max = null 11 added Value ( ) <max doubl

30、eValue ()1°max=往 died.11 12 Which two, in serted at line 2 will allow the code to compile? (Choose Two)A. public class Mi nMax< ? > B. public class MinMax < ? extends NumberC. public class MinMax <N extends Object> D. public class MinMax <N exte nds Number > E. public class

31、 MinMax < ? extends Object > F. public class MinMax < N exte nds In teger > Answer: ( D, F )N是泛型類別變量,它相當(dāng)于一個類型。A類聲明是不能用?這個萬用字符。B 同上C Object 沒有 doubleValue()方法。D OK.E 同A。F OK.QUESTION 73Give n the exhibit: enum Example ONE, TWO, THREE Which stateme nt is true?A. The expressions (ONE = = ON

32、E) and ONE.equals (ONE) are both guaranteed to be true.B. The expressio n (ONE < TWO ) is guara nteed to be true and ONE.compareTo (TWO) is guara nteed to be less tha n one.C. The Example values cannot be used in a raw java.util.HashMap.; in stead, the programmer must use a java.util.E num Map.D.

33、 The Example values can be used in a java.util.SortedSet, but the set will NOT be sorted because enu merated Type do NOT IMPLEMENT java .Ian g.Comparable.Answer: ( A )A正確B不能保證C錯誤枚舉類型的元素是可以用在HASHMAP里的HashMap< In teger, Example>h = new HashMap< In teger, Example>h.put(1, Example.ONE);字符串D錯

34、誤,枚舉類型的元素值是可以放入SortedSet里的例如TreeSet.把枚舉類型的元素轉(zhuǎn)成字符串在放入其中,就已經(jīng)實現(xiàn)comparable接口??梢宰匀慌判颉ortedSet<Example> s = new TreeSet<Example>(); s.add(Example.TWO);s.add(Example.ONE);System.out.pri ntl n( s);打印出結(jié)果ONE, TWOQUESTION 74Give n the exhibit:11. public void genNuabers() 12 ArrayList numbers = new

35、 ArrayList(),13 for (int i-O: i<10; i+) 14"ibt voluc i " ( ( int ) Mdth .xand口*15. Integer intObj = new Integer(vale);16 add(intOb);17+18 . System .out print I 口 (numbex 3).19 Which line of code marks the earliest point that an object refereneed by intObj becomes a can didate for garbag

36、e collect ion?A. Li ne 16B. Li ne 17C. Li ne 18D. Li ne 19E. The object is NOT a can didate for garbage collecti on.Answer: ( D )intObj 一直會被numbers引用,直到19行之后QUESTION 75Give n:12 public class Yippee2 13.14 .static public void nam(String yahoo)15 fQr(int x * 1; x < yahoo.length; x+) 16 . System,out

37、 print (yahooK 1 + ' * >:17.18 19 And the comma nd line in vocati on: javaYippee2 a b cWhat is the result?A. a bB. b cC. a b cD. Compilatio n fails.E. An excepti on is throw n at run time.Answer: ( B )QUESTION 76A class games.cards.Poker is correctly defined in the jar file Poker.jar. A user

38、wantsto execute the main method of Poker on a UNIX system using the comma nd:Java games.cards.PokerWhat allows the user to do this?A. put Poker.jar in directory /stuff/java, and set the CLASSPATH to in clude /stuff/javaB. put Poker.jar in directory /stuff/java, and set the CLASSPA TH to include /stu

39、ff/java/*.jarC. put Poker.jar in directory /stuff/java, and set the CLASSPA TH to include /stuff/java/Poker.jarD. put Poker.jar in directory /stuff/java/games/cards, and set the CLASSPATH to in clude /stuff/javaE. put Poker.jar in directory /stuff/java/games/cards, and set the CLASSPATH to in clude

40、/stuff/java/*.jarF. put Poker.jar in directory /stuff/java/games/cards, and set the CLASSPATH to in clude /stuff/java/Poker.jarAnswer: ( C )classpath中須明確寫明poker.jar,不能用*.jarQUESTION 770 12 3 4 5 6 7 8 9 0 12 3 4 5 6 7 89 0 121 I 1 1 1 1 li 1 2 2 CM2 2 2 2 2 3 ? 3class Inner private int st;public voi

41、d setX( mt x ) this x - x; publxc mt getX( ) return x; class Outer private Inner y;public void setYCInner y )this y V; public 丄nner getY() return y; publ ic class Gamna public stat ic void Main(Strmg args) Ou tex o new Outcx(),Inner 1 new nner();mt n - 10;1 setX( n ):o,setY( 1 j;“ insert code hereSy

42、ste* out print ln( o getY( > ge-tX();Which three code fragme nts, added in dividually at line 29, produce the output 100? (Choose three.)A. n = 100;B. i.setX(100);C. o.getY().setX( 100 );D. i = new Inn er();i.setX( 100 );E. 0.setY ( i ); i = new Inn er(); i.setX ( 100 );F. i = new Inner (); i.set

43、X( 100 ); o.setY( i );Answer: ( B, C, F )根據(jù)內(nèi)存關(guān)系可知QUESTION 78Give n a class Repetiti on:1 package utils;3 public class Repet it ion 4 public stati匚 String tvic«(Striiig s) return s + s, s. yAnd give n ano ther class Demo:1 / instar t code here3 public class Dexo 4 public static voxd *ain(Strinf

44、args) 5 System out prxntlnCtwice('pizza*);6tWhich code should be in serted at li ne 1 of Demo.java to compile and run Demo to prin t "pizzapizza"A. import utils.*;B. static import utils.*;C. import utils.Repetiti on.*;D. static import utils.Repetiti on.*;E. import utils.Repetiti on. tw

45、ice();F. import static utils.Repetiti on. twice;G. static import utils.Repetiti on. twice;Answer: ( F )靜態(tài) import 弓I入靜態(tài)方法 .import static utils.Repetition*; 或者 import static utils.Repetition.twice;A 正常的導(dǎo)入類,Demo的第5行要new實例才能帶用twice方法.B static import順序顛倒,而且要加上 class名C正常的導(dǎo)入,類名后面不能跟*D順序顛倒E正常的導(dǎo)入,只能導(dǎo)入包下的類,不能

46、導(dǎo)入類里的方法.G順序顛倒QUESTION 79Give n:11 publlc static void test(String str J 12 if (str * null | str.length) * 0)13 System out"String is empty4) H14 P else 15 Systes out printing"String is not e>ptyB)16,)JAnd the in vocatio n:31. test(null);What is the result?A. An excepti on is throw n at ru

47、n time.B. "Stri ng is empty" is prin ted to output.C. Compilation fails because of an error in line 12.D. "String is not empty" is printed to output.Answer: ( A )A空指針異常是非短路邏輯運算符QUESTION 80Exhibit:J>r AJtr 8JarCO boLDogaa$LO comL(U boLUta-闔 Dog «a« -H C# cta$UMEriHFco

48、mHO tooLbaDog琢 bCaeL圃陽AMJQbar:-闔 3 tiawuatrJ«rEJarD衍5*圄EMM昭園 CardtMQ META-IMFiwIKi=nclassSdassGive n the fully-qualified class n ames:com.foo.bar.Dogcom.foo.bar.blatz.Bookcom.bar.Carcom.bar.blatz.S unWhich graph represe nts the correct directory structure for a JAR file from which those classes

49、 can be used by the compiler and JVM?A. Jar AB. Jar BC. Jar CD. Jar DE. JarEAnswer: ( A )QUESTION 81Give n:5 6 7 8901111 1122public class Yippee <publicic void Bain( args) f or C int x 1” x < args length, m) Systew out. print (angs f x t ' 41);and two separate comma nd line in vocati ons:j

50、ava Yippeejava Yippee 1 2 3 4 What is the result?A.No output is produced.1 2 3B.No output is produced.2 3 4C.No output is produced.1 2 3 4D.An exceptio n is throw n at run time.1 2 3E.An exceptio n is throw n at run time.2 3 4F.An exceptio n is throw n at run time.1 2 3 4Answer: ( B )QUESTION 82Give

51、 n:13,public class Pass 14public static void Rdin(Strmg args)15mt x - 5;6Pass p = iiev Pass ();17p doStuf f (x).18.System.out.print("x "+ x);19.20 +21 void doStuf f (int x) 22 System cut,print(' ddStutt x - * + x+),23, 24. What is the result?A. Compilation failsB. An excepti on is thro

52、w n at run timeC. doStuff x = 6 main x = 6D. doStuff x = 5 main x = 5E. doStuff x = 5 main x = 6F. doStuff x = 6 main x = 5Answer: ( D )第10行參數(shù)x是值傳遞,不會改變 main中x的值。QUESTION 84Give n:1 public closs GC 2 . private Object o;3 private void doSQMething£lse(Object obj) o » ob” 4 public void doSaMe

53、thingC) <5 Object a new Object();6 dcSoMet hingElse(o).7 . o - new Object();8 doSonethingElse(nuli;9 .q * nul1 +When the doSometh ing method is called, after which line does the Object created in line 5 become available for garbage collect ion?A. Li ne 5B. Li ne 6C. Li ne 7D. Li ne 8E. Li ne 9F.

54、Li ne 10Answer: ( D )棧內(nèi)存用來存放基本類型的變量和對象的引用變量(對象的地址)堆內(nèi)存用來存放由 new創(chuàng)建的對象和數(shù)組QUESTION 84Give n:11. class A 12. public void process() System.out.print(*A,"),13. class B extends A 14 public void process() throws lOException 15. super process();16. System.out print('B,");17. throw new lOExceptio

55、n()1 氛>.19 public static void aain(String args) 20. try nev B() process(J; >21 catch (IOExceptian e) Sys tea cut print ln( "Exception"), What is the result?A. Excepti onB. A, B, Excepti onC. Compilati on fails because of an error in line 20.D. Compilation fails because of an error in line 14.E. A NullPoi nterExceptio n is throw n at run time.Answer: ( D )改寫的規(guī)定,子類拋出的異常要比父類的異常要小.本題中父類沒有異常,子類也不能有異常QUESTION 86Give n:11 public class Test 12. public enua Dogs collie, harr

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論