• 沒有找到結果。

書名:SCJP 6.0 認證教戰手冊 作者:黃彬華 完全擬真試題 101-200(共 244 題)

N/A
N/A
Protected

Academic year: 2022

Share "書名:SCJP 6.0 認證教戰手冊 作者:黃彬華 完全擬真試題 101-200(共 244 題)"

Copied!
53
0
0

加載中.... (立即查看全文)

全文

(1)

書名:SCJP 6.0 認證教戰手冊 作者:黃彬華

完全擬真試題 101-200(共 244 題)

第101題 Given:

10. package com.sun.scjp;

11. public class Geodetics {

12. public static final double DIAMETER = 12756.32; //kilometers 13. }

Which two correctly access the DIAMETER member of the Geodetics class? (Choose two.) A. import com.sun.scjp.Geodetics;

public class TerraCarta{

public double halfway()

{return Geodetics.DIAMETER/2.0;}

B. import static com.sun.scjp.Geodetics;

public class TerraCarta{

public double halfway(){return DIAMETER/2.0;}}

C import static com.sun.scjp.Geodetics.*;

public class TerraCarta{

public double halfway(){return DIAMETER/2.0;}}

D. package com.sun.scjp;

public class TerraCarta{

public double halfway(){return DIAMETER/2.0;}}

答案:AC

參考:8-2 方法種類與呼叫方式

第102題 Given:

10. interface Foo{int bar();}

11. public class Sprite{

12. public int fubar(Foo foo){return foo.bar();}

13. public void testFoo(){

14. fubar(

15. //insert code here 16. );

17. } 18. }

Which code, inserted at line 15, allows the class Sprite to compile?

A. Foo{public int bar(){return 1;}}

B. new Foo{public int bar(){return 1;}}

C. new Foo(){public int bar(){return 1;}}

(2)

D. new class Foo{public int bar(){return 1;}}

答案:C

參考:8-5 內部類別

第103題 Given:

11. public enum Title{

12. MR("Mr."), MRS("Mrs."), MS("Ms.");

13. private final String title;

14. private Title(String t){title = t;}

15. public String format(String last, String first){

16. return title + " " + first + " " + last;

17. } 18. }

19. public static void main(String[] args){

20. System.out.println(Title.MR.format("Doe", "John"));

21. } What is the result?

A. Mr. John Doe

B. An exception is thrown at runtime.

C. Compilation fails because of an error in line 12.

D. Compilation fails because of an error in line 15.

E. Compilation fails because of an error in line 20.

答案:A

參考:8-6 Java 列舉類型

第104題 Given:

10. class Line{

11. public static class Point{}

12. } 13.

14. class Triangle{

15. //insert code here 16. }

Which code, inserted at line 15, creates an instance of the Point class defined in Line?

A. Point p = new Point();

B. Line.Point p = new Line.Point();

C. The Point class cannot be instatiated at line 15.

D. Line l = new Line(); l.Point p = new l.Point();

答案:B

參考:8-5 內部類別

(3)

第105題 Given:

1. public class A { 2.

3. private int counter = 0;

4

5. public static int getInstanceCount(){

6. return counter;

7. } 8.

9. public A(){

10. counter++;

11. } 12.

13. }

And given this code from Class B:

25. A a1 = new A();

26. A a2 = new A();

27. A a3 = new A();

28. System.out.println(A.getInstanceCount());

What is the result?

A. Compilation of class A fails.

B. Line 28 prints the value 3 to System.out.

C. Line 28 prints the value 1 to System.out.

D. A runtime error occurs when line 25 executes.

E. Compilation fails because of an error on line 28.

答案:A

參考:8-2 方法種類與呼叫方式

第106題

Given classes defined in two different files:

1. package util;

2. public class BitUtils{

3. public static void process(byte[] b){/* more code here */}

4. }

1. package app;

2. public class SomeApp{

3. public static void main(String[] args){

4. byte[] bytes = new byte[256];

5. //insert code here 6. }

7. }

What is required at line 5 in class SomeApp to use the process method of BitUtils?

A. process(bytes);

B. BitUtils.process(bytes);

C. util.BitUtils.process(bytes);

(4)

D. SomeApp cannot use methods in BitUtils.

E. import util.BitUtils.*; process(bytes);

答案:C

參考:7-1 Java 套件、8-3 類別成員的匯入

第107題 Given:

10. class Inner{

11. private int x;

12. public void setX(int x){this.x = x;}

13. public int getX(){return x;}

14. } 15.

16. class Outer{

17. private Inner y;

18. public void setY(Inner y){this.y = y;}

19 public Inner getY(){return y;}

20. } 21.

22. public class Gamma{

23. public static void main(String[] args){

24. Outer o = new Outer();

25. Inner i = new Inner();

26. int n = 10;

27. i.setX(n);

28. o.setY(i);

29. //insert code here

30. System.out.println(o.getY().getX());

31. } 32. }

Which three code fragments, added individually at line 29, produce the output 100? (Choose three.) A. n = 100;

B. i.setX(100);

C. o.getY().setX(100);

D. i = new Inner(); i.setX(100);

E. o.setY(i); i = new Inner(); i.setX(100);

F. i = new Inner(); i.setX(100); o.setY(i);

答案:BCF

參考:7-4 封裝、8-1 變數種類與其生命期

第108題 Given:

11. class Snoochy { 12. Boochy booch;

13. public Snoochy(){booch = new Boochy(this);}

14 }

(5)

15.

16. class Boochy{

17. Snoochy snooch;

18. public Boochy(Snoochy s){snooch = s;}

19. }

And the statements.

21. public static void main(String[] args){

22. Snoochy snoog = new Snoochy();

23. snoog = null;

24. //more code here 25. }

Which statement is true about the objects referenced by snoog, snooch, and booch immediately after line 23 executes?

A. None of these objects are eligible for garbage collection.

B. Only the object referenced by booth is eligible for garbage collection.

C. Only the object referenced by snoog is eligible for garbage collection.

D. Only the object referenced by snooch is eligible for garbage collection.

E. The objects referenced by snooch and booth are eligible for garbage collection.

答案:E

參考:8-7 資源回收機制

第109題 Given:

5. class Payload{

6. private int weight;

7. public Payload (int w){weight = w;}

8. public void setWeight(int w){weight = w;}

9. public String toString(){return Integer.toString(weight);}

10. }

11. public class TestPayload{

12. static void changePayload(Payload p){/* insert code */}

13. public static void main(String[] args){

14. Payload p = new Payload(200);

15. p.setWeight(1024);

16. changePayload(p);

17. System.out.println("p is " + p);

18. }}

Which code fragment, inserted at the end of line 12, produces the output p is 420?

A. p.setWeight(420);

B. p.changePayload(420);

C. p = new Payload(420);

D. Payload.setWeight(420);

E. p = Payload.setWeight(420);

答案:A

參考:8-2 方法種類與呼叫方式

(6)

第110題 Given:

11. public static void test(Sting str){

12. int check = 4;

13. if(check = str.length()){

14. System.out.print(str.charAt(check -= 1) + ", ");

15. }else{

16. System.out.print(str.charAt(O) + ", ");

17. } 18. }

and the invocation:

21. test("four");

22. test("tee");

23. test("to");

What is the result?

A. r, t, t, B. r, e, o,

C. Compilation fails.

D. An exception is thrown at runtime.

答案:C

參考:4-1 條件控制、8-2 方法種類與呼叫方式

第111題 Given:

15. public class Pass2{

16. public static void main(String[] args){

17. int x = 6;

18. Pass2 p = new Pass2();

19. p.doStuff(x);

20. System.out.print(" main x = " + x);

21. } 22.

23. void doStuff(int x){

24. System.out.print(" doStuff x = " + x++);

25. } 26. }

And the command-line invocations:

javac Pass2.java java Pass2 5 What is the result?

A. Compilation fails.

B. An exception is thrown at runtime.

C. doStuff x = 6 main x = 6 D. doStuff x = 6 main x = 7

(7)

E. doStuff x = 7 main x = 6 F. doStuff x = 7 main x = 7 答案:C

參考:4-1 條件控制、8-2 方法種類與呼叫方式

第112題 Given:

12. public class Test{

13. public enum Dogs{collie, harrier);

14. public static void main(String[] args){

15. Dogs myDog = Dogs.collie;

16. switch(myDog){

17. case collie:

18. System.out.print("collie ");

19. case harrier:

20. System.out.print("harrier ");

21. } 22. } 23. } What is the result?

A. collie B. harrier

C. Compilation fails.

D. collie harrier

E. An exception is thrown at runtime.

答案:D

參考:4-1 條件控制、8-6 Java 列舉類型

第113題 Given:

10. public class Foo{

11. static int[] a;

12. static{ a[0] = 2;}

13. public static void main( String[] args){}

14. }

Which exception or error will be thrown when a programmer attempts to run this code?

A. java.lang.StackOverflowError B. java.lang.IllegalStateException C. java.lang.ExceptionInInitializerError D. java.lang.ArrayIndexOutOfBoundsException 答案:C

參考:8-1 變數種類與其生命期、9-1 執行上的錯誤

(8)

第114題 Given:

10. class Line{

11. public class Point{public int x, y;}

12. public Point getPoint(){return new Point();}

13. }

14. class Triangle{

15. public Triangle(){

16. //insert code here 17. }

18. }

Which code, inserted at line 16, correctly retrieves a local instance of a Point object?

A. Point p = Line.getPoint();

B. Line.Point p = Line.getPoint();

C. Point p = (new Line()).getPoint();

D. Line.Point p = (new Line()).getPoint();

答案:D

參考:8-5 內部類別

第115題 Given:

11. public static void main(String[] args){

12. for(int i = 0; i <= 10; i++){

13. if(i > 6) break;

14. }

15. System.out.println(i);

16. } What is the result?

A. 6 B. 7 C. 10 D. 11

E. Compilation fails.

F. An exception is thrown at runtime.

答案:E

參考:8-1 變數種類與其生命期

第116題 Given:

11. public class Commander{

12. public static void main(String[] args){

13. String myProp = /* insert code here */

14. System.out.println(myProp);

15. }

(9)

16. }

and the command line:

java -Dprop.custom=gobstopper Commander

Which two, placed on line 13, will produce the output gobstopper? (Choose two.) A. System.load("prop.custom");

B. System.getenv("prop.custom");

C. System.property("prop.custom);

D. System.getProperty("prop.custom");

E. System.getProperties().getProperty("prop.custom");

答案:DE

參考:8-4 main()方法的參數傳遞與系統屬性設定

第117題 Given:

11. class Converter{

12. public static void main(String[] args){

13. Integer i = args[0];

14. int j = 12;

15. System.out.println("It is " + (j==i) + " that j==i.");

16. } 17. }

What is the result when the programmer attempts to compile the code and run it with the command java Converter 12?

A. It is true that j==i.

B. It is false that j==i.

C. An exception is thrown at runtime.

D. Compilation fails because of an error in line 13.

答案:D

參考:8-4 main()方法的參數傳遞與系統屬性設定

第118題 Given

10. class Foo{

11. static void alpha(){/* more code here */}

12. void beta() {/* more code here */) 13. }

Which two statements are true? (Choose two.) A. Foo.beta() is a valid invocation of beta().

B. Foo.alpha() is a valid invocation of alpha().

C. Method beta() can directly call method alpha().

D. Method alpha() can directly call method beta().

答案:BC

(10)

參考:8-2 方法種類與呼叫方式

第119題 Given:

11. public static void main(String[] args){

12. String str = "null";

13. if (str == null) {

14. System.out.println("null");

15. }else (str.length() == 0) { 16. System.outprintln("zero");

17. }else{

18. System.out.println("some");

19. } 20. } What is the result?

A. null B. zero C. some

D. Compilation fails.

E. An exception is thrown at runtime.

答案:D

參考:4-1 條件控制、11-2 文字類型

第120題 Given:

1. public class GC{

2. private Object o;

3. private void doSomethingElse(Object obj){o = obj;}

4. public void doSomething(){

5. Object o = new Object();

6. doSomethingElse(o);

7. o = new Object();

8. doSomethingElse(null);

9. o = null;

10. } 11. }

When the doSomething method is called, after which line does the Object created in line 5 become available for garbage collection?

A. Line 5 B. Line 6 C. Line 7 D. Line 8 E. Line 9 F. Line 10

(11)

答案:D

參考:8-7 資源回收機制

第121題 Given:

11. public class Test{

12. public enum Dogs {collie, harrier, shepherd}

13. public static void main(String[] args){

14. Dogs myDog = Dogs.shepherd;

15. switch(myDog){

16. case collie:

17. System.out.print("collie ");

18. case default:

19. System.out.print("retriever ");

20. case harrier:

21. System.out.print("harrier ");

22. } 23. } 24. } What is the result?

A. harrier B. shepherd C. retriever

D. Compilation fails E. retriever harrier

F. An exception is thrown at runtime, 答案:D

參考:4-1 條件控制、8-6 Java 列舉類型

第122題 Given:

11. public void genNumbers(){

12. ArrayList numbers = new ArrayList();

13. for(int i=0; i<10; i++){

14. int value = i * ((int)Math.random());

15. Integer intObj = new Integer(value);

16. numbers.add(intObj);

17. }

18. System.out.println(numbers);

19. }

Which line of code marks the earliest point that an object referenced by intObj becomes a candidate for garbage collection?

A. Line 16 B. Line 17 C. Line 18

(12)

D. Line 19

E. The object is NOT a candidate for garbage collection.

答案:D

參考:8-7 資源回收機制

第123題 Given:

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.0

B. Compilation fails.

C. A ParseException is thrown by the parse method at runtime.

D. A NumberFormatException is thrown by the parse method at runtime.

答案:B

參考:8-1 變數種類與其生命期、9-2 Java 例外事件與處理機制

第124題 Given:

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 end

B. Compilation fails.

C. test runtime end

(13)

D. test exception end

E. A Throwable is thrown by main at runtime.

答案:D

參考:9-2 Java 例外事件與處理機制

第125題 Given:

33. try{

34. //some code here

35. }catch(NullPointerException el){

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. a B. b C. c D. ac E. abc 答案:D

參考:9-2 Java 例外事件與處理機制

第126題 Given:

31. //some code here 32. try{

33. //some code here

34. }catch(Some Exception se) { 35. //some code here

36. }finally{

37. //some code here 38. }

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 答案:BCE

參考:9-2 Java 例外事件與處理機制

(14)

第127題 Given:

1. public class Donkey2{

2. public static void main(Stnng[] 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 Donkey2 is invoked twice, the first time without assertions enabled, and the second time with assertions enabled, what are the results?

A. no output

B. no output assert is on C. assert is on

D. no output

An Assertion Error is thrown.

E. assert is on

An AssertionError is thrown.

答案:C

參考:9-7 測試程式與 AssertionError 錯誤事件

第128題 Given:

1. public class A{

2. public void method1(){

3. try{

4. B b = new B();

5. b.method2();

6. //more code here 7. }catch(TestException te){

8. throw new RuntimeException(te);

9. } 10. } 11. }

1. public class B{

2. public void method2() throws TestException{

3. //more code here 4. }

5. }

1. public class TestException extends Exception{

2. }

(15)

And 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 a try/catch block.

答案:B

參考:9-2 Java 例外事件與處理機制、9-3 使用 throw 自行產生例外事件、9-4 自訂例外類別、9-5 使用 throws 拋出例外事件、9-6 RuntimeException 與 CheckedException。

第129題 Given:

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.

答案:A

參考:9-2 Java 例外事件與處理機制

第130題 Given:

11. static void test(){

12. try{

13. String x = null;

14. System.out.print(x.toString() + " ");

15. }

16. finally{System.out.print("finally ");}

17. }

(16)

18. public static void main(String[] args){

19. try{test();}

20. catch(Exception ex){System.out.print("exception ");}

21. } What is the result?

A. null B. finally C. null finally D. Compilation fails.

E. finally exception 答案:E

參考:9-2 Java 例外事件與處理機制

第131題 Given:

11. static void test() throws Error{

12. if(true) throw new AssertionError();

13. System.out.print("test ");

14. }

15. public static void main(String[] args){

16. try{test();}

17. catch(Exception ex){System.out.print("exception ");}

18. System.out.print("end ");

19. } What is the result?

A. end

B. Compilation fails.

C. exception end D. exception test end

E. A Throwable is thrown by main.

F. An Exception is thrown by main.

答案:E

參考:9-2 Java 例外事件與處理機制

第132題 Given:

1. class TestException extends Exception{}

2. class A{

3. public String sayHello(String name) throws TestException{

4. if(name == null) throw new TestException();

5. return "Hello " + name;

6. } 7. }

8. public class TestA{

(17)

9. public static void main(String[] args){

10. new A().sayHello("Aiko");

11. } 12. }

Which statement is true?

A. Compilation succeeds.

B. class A does not compile.

C. The method declared on line 9 cannot be modified to throw TestException.

D. TestA compiles if line 10 is enclosed in try/catch block that catches TestException.

答案:D

參考:9-2 Java 例外事件與處理機制、9-3 使用 throw 自行產生例外事件、9-4 自訂例外類別、9-5 使用 throws 拋出例外事件。

第133題 Given:

10. public class ClassA{

11. public void methodA(){

12. ClassB classB = new ClassB();

13. classB.getValue();

14. } 15. } And:

20. class ClassB{

21. public ClassC classC;

22.

23. public String getValue(){

24. return classC.getValue();

25. } 26. } And:

30. class ClassC{

31. public String value;

32.

33. public String getValue(){

34. value = "ClassB";

35. return value;

36. } 37. } And given:

ClassA a = new ClassA();

a.methodA();

What is the result?

A. Compilation fails.

B. ClassC is displayed.

C. The code runs with no output.

D. An exception is thrown at runtime.

(18)

答案:D

參考:9-2 Java 例外事件與處理機制

第134題 Given:

5. classA{

6. void foo() throws Exception{throw new Exception();}

7. }

8. class SubB2 extends A{

9. void foo(){System.out.println("B ");}

10. }

11. class Tester{

12. public static void main(String[] args){

13. A a = new SubB2();

14. a.foo();

15. } 16. } What is the result?

A. B

B. B, followed by an Exception.

C. Compilation fails due to an error on line 9.

D. Compilation fails due to an error on line 14.

E. An Exception is thrown with no other output.

答案:D

參考:9-3 使用 throw 自行產生例外事件、9-5 使用 throws 拋出例外事件、9-6 RuntimeException 與 Checked Exception。

第135題 Given:

84. try{

85. ResourceConnection con = resourceFactory.getConnection();

86. Results r = con.query("GET INFO FROM CUSTOMER");

87. info = r.getData();

88. con.close();

89. }catch(ResourceException re){

90. errorLog.write(re.getMessage());

91. }

92. return info;

Which statement is true if a ResourceException is thrown on line 86?

A. Line 92 will not execute.

B. The connection will not be retrieved in line 85.

C. The resource connection will not be closed on line 88.

D. The enclosing method will throw an exception to its caller.

答案:C

(19)

參考:9-2 Java 例外事件與處理機制。

第136題 Given:

11. public static void main(String[] args){

12. try{

13. args = null;

14. args[0] = "test";

15. System.out.println(args[0]);

16. }catch(Exception ex) {

17. System.out.println("Exception");

18. }catch(NullPointerException npe){

19. System.out.println("NullPointerException");

20. } 21. } What is the result?

A. test B. Exception C. Compilation fails.

D. NullPointerException 答案:C

參考:9-2 Java 例外事件與處理機制。

第137題 Given:

11. class X{public void foo(){System.out.print("X ");}}

12.

13. public class SubB extends X{

14. public void foo() throws RuntimeException{

15. super.foo();

16. if(true) throw new RuntimeException();

17. System.out.print("B ");

18. }

19. public static void main(String[] args){

20. new SubB().foo();

21. } 22. } What is the result?

A. X, followed by an Exception.

B. No output, and an Exception is thrown.

C. Compilation fails due to an error on line 14.

D. Compilation fails due to an error on line 16.

E. Compilation fails due to an error on line 17.

F. X, followed by an Exception, followed by B.

答案:A

(20)

參考:9-3 使用 throw 自行產生例外事件、9-5 使用 throws 拋出例外事件。

第138題

Which two code fragments are most likely to cause a StackOverflowError? (Choose two.) A. int[] x = {1, 2, 3, 4, 5};

for(int y=0; y<6; y++) System.out.println(x[y]);

B. static int[] x = {7, 6, 54};

static{x[1] = 8; x[4] = 3;}

C. for(int y=10; y<10; y++) doStuff(y);

D. void doOne(int x){doTwo(x);}

void doTwo(int y){doThree(y);}

void doThree(int z){doTwo(z);}

E. for(int x=0; x<1000000000; x++) doStuff(x);

F. void counter(int i){counter(++i);}

答案:DF

參考:9-8 StackOverflowError 錯誤事件

第139題

Given a method that must ensure that its parameter is not null:

11. public void someMethod(Object value){

12. //check for null value ...

20. System.out.println(value.getClass());

21. }

What, inserted at line 12, is the appropriate way to handle a null value?

A. assert value == null;

B. assert value != null : "value is null";

C. if (value == null){

throw new AssertionException("value is null");

}

D. if (value == null){

throw new IllegalArgumentException("value is null");

} 答案:D

參考:9-3 使用 throw 自行產生例外事件、9-7 測試程式與 AssertionError 錯誤事件

第140題

(21)

Given:

1. public class A{

2. public void method1(){

3. B b = new B();

4. b.method2();

5. //more code here 6. }

7. }

1. public class B{

2. public void method2(){

3. C c = new C();

4. c.method3();

5. //more code here 6. }

7. }

1. public class C{

2. public void method3(){

3. //more code here 4. }

5. } And given:

25. try{

26. A a = new A();

27. a.method1();

28. }catch(Exception e){

29. System.out.print("an error occurred");

30. }

Which two statements are true if a NullPointerException is thrown on line 3 of class C? (Choose two.) A. The application will crash.

B. The code on line 29 will be executed.

C. The code on line 5 of class A will execute.

D. The code on line 5 of class B will execute.

E. The exception will be propagated back to line 27.

答案:BE

參考:9-2 Java 例外事件與處理機制、9-5 使用 throws 拋出例外事件。

第141題 Given:

11. class A{

12. public void process(){System.out.print("A, ");}

13. }

14. class B extends A{

15. public void process() throws IOException{

16. super.process();

17. System.out.print("B, ");

18. throw new IOException();

(22)

19. } 20. }

21. public static void main(String[] args){

22. try{new B().process();}

23. catch(IOException e){System.out.println("Exception");}

24. } What is the result?

A. Exception B. A, B, Exception

C. Compilation fails because of an error in line 20.

D. Compilation fails because of an error in line 14.

E. A NullPointerException is thrown at runtime.

答案:D

參考:9-2 Java 例外事件與處理機制、9-3 使用 throw 自行產生例外事件、9-5 使用 throws 拋出例 外事件。

第142題

Assuming 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 serialization 21. b2 = b.deserializeBanana(); //assume correct

22. System.out.println("restore " + b2.yellow + b2.juice + b2.good);

24. }

25. //more Banana methods go here 50. }

What is the result?

A. restore 400 B. restore 403 C. restore 453 D. Compilation fails.

E. An exception is thrown at runtime.

答案:C

參考:10-5 多重串接

第143題 Given:

System.out.printf("Pi is approximately %f and E is approximately %b", Math.PI, Math.E);

(23)

Place the values where they would appear in the output.

Pi is approximately Place here and E is approximately Place here

Values

3 3.141593 true Math.PI 2 2.718282 false Math.E

答案:

Pi is approximately 3.141593 and E is approximately true

參考:10-2 Console 類別、11-1 數字類型

第144題

Which capability exists only in java.io.BufferedWriter?

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.

答案:D

參考:10-5 多重串接

第145題

Given that the current directory is empty, and that the user has read and write permissions, and the 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.

(24)

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.

答案:E

參考:10-3 File 類別

第146題 Given:

1. import java.io.*;

2. public class Foo implements Serializable{

3. public int x, y;

4. public Foo(int x, int y){this.x = x; this.y = y;}

5.

6. private void writeObject(ObjctOutputStream s) 7. throws IOException{

8. s.writeInt(x); s.writeInt(y);

9. } 10.

11. private void readObject(ObjectInputStream s) 12. throws IOException, ClassNotFoundException{

13.

14. //insert code here 15.

16. } 17. }

Which code, inserted at line 14, will allow this class to correctly serialize and deserialize?

A. s.defaultReadObject();

B. this = s.defaultReadObject(), C. y = s.readInt(); x = s.readInt();

D. x = s.readInt(); y = s.readInt();

答案:D

參考:10-5 多重串接

第147題 Given:

1. public class LineUp{

2. public static void main(String[] args){

3. double d = 12.345;

4. //insert code here 5. }

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);

(25)

D. System.out.printf("|%3.7f| \n", d);

E. System.out.printf("|%7.3d| \n", d);

F. System.out.printf("|%7.3f| \n", d);

答案:F

參考:10-2 Console 類別

第148題 Given:

12. import java.io.*;

13. public class Forest implements Serializable{

14. private Tree tree = new Tree();

15. public static void main(String[] args){

16. Forest f = new Forest();

17. try{

18. FileOutputStream fs = new FileOutputStream("Forest.ser");

19. ObjectOutputStream os = new ObjectOutputStream(fs);

20. os.writeObject(f); os.close();

21. }catch(Exception ex){ex.printStackTrace();}

22. }}

23.

24. class Tree{}

What is the result?

A. Compilation fails.

B. 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.

答案:B

參考:10-5 多重串接

第149題

Place the Fragments into the program, so that the program will get lines from a text file. display them, and then close all the resources.

Program import java.io.*;

class ReadFile{

public static void main(String[] args){

try{

File ? = new File("MyText.txt");

Place here ? = new Place here (x1);

Place here x4 = new Place here (x2);

String x3 = null;

while((x3 = ? . Place here ()) != null){

System.out.println(x3);

Code Fragments BufferedReader

StreamReader FileReader

readLine readLn

read closeFile

close x1 x2

(26)

} ? . Place here ();

}catch(Exception ex){

ex.printStackTrace();

} } }

x3 x4

答案:

import java.io.*;

class ReadFile{

public static void main(String[] args){

try{

File x1 = new File("MyText.txt");

FileReader x2 = new FileReader (x1);

BufferedReader x4 = new BufferedReader (x2);

String x3 = null;

while((x3 = x4.readLine ()) != null){

System.out.println(x3);

} x4 . close ();

}catch(Exception ex){

ex.printStackTrace();

} } }

參考:10-5-1 BufferedReader 與 BufferedWriter 類別

第150題 Given:

5. import java.io.*;

6. public class Talk{

7. public static void main(String[] args){

8. Console c = new Console();

9. String pw;

10. System.out.print("password: ");

11. pw = c.readLine();

12. System.out.println("got" + pw);

13. } 14. }

If the user types the password aiko when prompted, what is the result?

A. password:

got B. password:

got aiko C. password: aiko

(27)

got aiko

D. An exception is thrown at runtime.

E. Compilation fails due to an error on line 8.

答案:E

參考:10-2 Console 類別

第151題

Given that the current directory is empty, and that the user has read and write privileges to the current directory, and the following:

1. import java.io.*;

2. public class Maker{

3. public static void main(String args){

4. File dir = new File("dir");

5. File f = new File(dir, "f");

6. } 7. }

Which statement is true?

A. Compilation fails.

B. Nothing is added to the file system.

C. Only a new file is created on the file system.

D. Only a new directory is created on the file system.

E. Both a new file and a new directory are created on the file system.

答案:B

參考:10-3 File 類別

第152題

Which three statements concerning the use of the java.io.Serializable interface are true? (Choose three.) A. Objects from classes that use aggregation cannot be serialized.

B. An object serialized on one JVM can be successfully deserialized on a different JVM.

C. The values in fields with the volatile modifier will NOT survive serialization and deserialization.

D. The values in fields with the transient modifier will NOT survive serialization and deserialization.

E. It is legal to serialize an object of a type that has a supertype that does NOT implement java.io.Serializable.

答案:BDE

參考:10-5-2 ObjectInputStream 與 ObjectOutputStream 類別

第153題

Chain these constructors to create objects to read from a file named "in" and to write to a file named "out".

reader = Place here Place here "in" ));

writer = Place here Place here Place here "out" )));

(28)

Constructors

new FileReader( new PrintReader( new BufferedReader(

new BufferedWriter( new FileWriter( new PrintWriter(

答案:

reader = new BufferedReader( new FileReader( "in" ));

writer = new PrintWriter( new BufferedWriter( new FileWriter( "out" )));

參考:10-5-1 BufferedReader 與 BufferedWriter 類別

第154題

Given that c is a reference to a valid java.io.Console object, which two code fragments read a line of text from the console? (Choose two.)

A. String s = c.readLine();

B. char[] c = c.readLine();

C. String s = c.readConsole();

D. char[] c = c.readConsole();

E. String s = c.readLine("%s", "name ");

F. char[] c = c.readLine("%s", "name ");

答案:AE

參考:10-2 Console 類別

第155題

The doesFileExist method takes an array of directory names representing a path from the root filesystem and a file name. The method returns true if the file exists, false if it does not.

Place the code fragments in position to complete this method.

public static boolean doesFileExist(String[] directories, String filename){

Place here

for(String dir : directories){

Place here }

Place here Place here }

Code Fragments

path = path.getSubdirectory(dir); return !file.isNew(); return(file != null);

String path = ""; path = path.getFile(filename); File path = new File("");

return file.exists(); return path.isFile(); File file = new File(path, filename);

(29)

path = new File(path, dir); File path = new File(File.separator); path = path + File.separator + dir;

答案:

public static boolean doesFileExist(String[] directories, String filename){

String path = "";

for(String dir : directories){

path = path + File.separator + dir;

}

File file = new File(path, filename);

return file.exists();

}

參考:10-3 File 類別

第156題

Place the code fragments into position to use a BufferedReader to read in an entire text file.

class PrintFile{

public static void main(String[] args){

BufferedReader buffReader = null;

//More code here to initialize buffReader try{

String temp;

while( Place here Place here ){

System.out.println(temp);

}

}catch Place here e.printStackTrace();

} } }

Code Fragments

(temp = buffReader.readLine()) && buffReader.hasNext() (temp = buffReader.nextLine()) (IOException e){

!= null (FileNotFoundException e){

答案:

class PrintFile{

public static void main(String[] args){

BufferedReader buffReader = null; / //More code here to initialize buffReader try{

String temp;

while( (temp = buffReader.readLine()) != null ){

System.out.println(temp);

}

}catch (IOException e){

(30)

e.printStackTrace();

} } }

參考:10-5-1 BufferedReader 與 BufferedWriter 類別

第157題

Given that c is a reference to a valid java.io.Console object, and:

11. String pw = c.readPassword("%s", "pw: ");

12. System.out.println("got " + pw);

13. String name = c.readLine("%s", "name: ");

14. System.out.println(" got", name);

If the user types fido when prompted for a password, and then responds bob when prompted for a name, what is the result?

A. pw:

got fido name: bob got bob B. pw: fido got fido name: bob got bob C. pw:

got fido

name: bob got bob D. pw: fido

got lido

name: bob got bob E. Compilation fails.

F. An exception is thrown at runtime.

答案:E

參考:10-2 Console 類別

第158題

Given a vaid DateFormat object named df, and 16. Date d = new Date(0L);

17. String ds = "December 15, 2004";

18. //insert code here

What updates d's value with the date represented by ds?

A. 18. d = df.parse(ds);

B. 18. d = df.getDate(ds);

(31)

C. 18. try{

19. d = df.parse(ds);

20. }catch(ParseException e){}

D. 18. try{

19. d = df.getDate(ds);

20. }catch(ParseException e){}

答案:C

參考:11-4 數字與日期/時間格式設定

第159題 Given:

11. double input = 314159.26;

12. NumberFormat nf = NumberFormat.getInstance(Locale.ITALIAN);

13. String b;

14. //insert code here

Which 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);

答案:B

參考:11-4-1 NumberFormat 類別

第160題 Given:

22. StringBuilder sb1 = new StringBuilder("123");

23. String s1 = "123";

24. //insert code here

25. 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");

答案:E

參考:11-2 文字類型

(32)

第161題 Given:

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.

答案:D

參考:11-1 數字類型

第162題 Given:

11. public static void main(String[] args){

12. Integer i = new Integer(1) + new Integer(2);

13. switch(i){

14. case 3: System.out.println("three"); break;

15. default: System.out.println("other"); break;

16. } 17. } What is the result?

A. three B. other

C. An exception is thrown at runtime.

D. Compilation fails because of an error on line 12.

E. Compilation fails because of an error on line 13.

F. Compilation fails because of an error on line 15.

答案:A

參考:11-1 數字類型

第163題

(33)

Given:

1. public class TestString3{

2. public static void main(String[] args){

3. //insert code here 5. System.out.println(s);

6. } 7. }

Which two code fragments, inserted independently at line 3, generate the output 4247? (choose two.) A. String s = "123456789";

s = (s - "123").replace(1, 3, "24") - "89";

B. StringBuffer s = new StringBuffer("123456789");

s.delete(0, 3).replace(1, 3, "24").delete(4, 6);

C. StringBuffer s = new StringBuffer("123456789");

s.substring(3, 6).delete(1, 3).insert(1, "24");

D. StringBuilder s = new StringBuilder("123456789");

s.substring(3, 6).delete(1, 2).insert(1, "24");

E. StringBuilder s = new StringBuilder("123456789");

s.delete(0, 3).delete(1, 3).delete(2, 5).insert(1, "24");

答案:BE

參考:11-2 文字類型

第164題 Given:

1. d is a valid, non-null Date object

2. df is a valid, non-null DateFormat object set to the current locale

What outputs the current locale's country name and the appropriate version of d's date?

A. Locale loc = Locale.getLocale();

System.out.println(loc.getDisplayCountry() + " " + df.format(d));

B. Locale loc = Locale.getDefault();

System.out.println(loc.getDisplayCountry() + " " + df.format(d));

C. Locale loc = Locale.getLocale();

System.out.println(loc.getDisplayCountry() + " " + df.setDateFormat(d));

D. Locale loc = Locale.getDefault();

System.out.println(loc.getDisplayCountry() + " " + df.setDateFormat(d));

答案:B

參考:11-4 數字與日期/時間格式設定

(34)

第165題 Given:

5. import java.util.Date;

6. import java.text.DateFormat;

21. DateFormat df;

22. Date date = new Date();

23. //insert code here

24. String s = df.format(date);

Which code fragment, inserted at line 23, allows the code to compile?

A. df = new DateFormat();

B. df = Date.getFormat();

C. df = date.getFormat();

D. df = DateFormat.getFormat();

E. df = DateFormat.getInstance();

答案:E

參考:11-4 數字與日期/時間格式設定

第166題 Given:

1. public class BuildStuff{

2. public static void main(String[] args){

3. Boolean test = new Boolean(true);

4. Integer x = 343;

5. Integer y = new BuildStuff().go(test, x);

6. System.out.println(y);

7. }

8. int go(Boolean b, int i){

9. if(b) return (i/7);

10. return (i/49);

11. } 12. }

What is the result?

A. 7 B. 49 C. 343

D. Compilation fails.

E. An exception is thrown at runtime.

答案:B

參考:11-1 數字類型

第167題 Given:

11. String test = "Test A. Test B. Test C.";

12. //insert code here

(35)

13. String[] result = test.split(regex);

Which regular expression, inserted at line 12, correctly splits test into "Test A",

"Test B", and "Test C"?

A. String regex = "";

B. String regex = " ";

C. String regex = ".*";

D. String regex = "\\s";

E. String regex = "\\.\\s*";

F. String regex = "\\w[\.] +";

答案:E

參考:11-5 規則運算式與相關類別

第168題 Given:

11. public void testIfA(){

12. if(testIfB("True")){

13. System.out.println("True");

14. }else{

15. System.out.println("Not true");

16. } 17. }

18. public Boolean testIfB(String str){

19. return Boolean.valueOf(str);

20. }

What is the result when method testIfA is invoked?

A. True B. Not true

C. An exception is thrown at runtime.

D. Compilation fails because of an error at line 12.

E. Compilation fails because of an error at line 19.

答案:A

參考:11-1-2 Wrapper 類別

第169題 Given:

12. NumberFormat nf = NumberFormat.getInstance();

13. nf.setMaximumFractionDigits(4);

14. nf.setMinimumFractionDigits(2);

15. String a = nf.format(3.1415926);

16. String b = nf.format(2);

Which two statements are true about The result if the default locale is Locale.US? (Choose two.) A. The value of b is 2.

(36)

B. The value of a is 3.14.

C. The value of b is 2.00.

D. The value of a is 3.141.

E. The value of a is 3.1415.

F. The value of a is 3.1416.

G. The value of b is 2.0000.

答案:CF

參考:11-4 數字與日期/時間格式設定

第170題 Given:

12. String csv = "Sue,5,true,3";

13. Scanner scanner = new Scanner(csv);

14. scanner.useDelimiter(",");

15. int age = scanner.nextInt();

What is the result?

A. Compilation fails.

B. After line 15, the value of age is 5.

C. After line 15, the value of age is 3.

D. An exception is thrown at runtime.

答案:D

參考:11-5 規則運算式與相關類別

第171題 Given:

11. String test = "a1b2c3";

12. String[] tokens = test.split("\\d");

13. for(String s : tokens) System.out.print(s + " ");

What is the result?

A. a b c B. 1 2 3 C. a1b2c3 D. a1 b2 c3

E. Compilation fails.

F. The code runs with no output.

G. An exception is thrown at runtime.

答案:A

參考:11-5 規則運算式與相關類別

第172題

(37)

Given:

33. Date d = new Date(0);

34. String ds = "December 15, 2004";

35. //insert code here 36. try{

37. d = df.parse(ds);

38. }

39. catch(ParseException e){

40. System.out.println("Unable to parse " + ds);

41. }

42. //insert code here too

What creates the appropriate DateFormat object and adds a day to the Date object?

A. 35. DateFormat df = DateFormat.getDateFormat();

42. d.setTime((60 * 60 * 24) + d.getTime();

B. 35. DateFormat df = DateFormat.getDateInstance();

42. d.setTime((1000 * 60 * 60 * 24) + d.getTime());

C. 35. DateFormat df = DateFormat.getDateFormat();

42. d.setLocalTime((1000 * 60 * 60 * 24) + d.getLocalTime());

D. 35. DateFormat df = DateFormat.getDateInstance();

42. d.setLocalTime((60 * 60 * 24) + d.getLocalTime());

答案:B

參考:11-4 數字與日期/時間格式設定

第173題 Given:

11. public class Yikes{

12.

13. public static void go(Long n){System.out.print("Long ");}

14. public static void go(Short n){System. outprint("Short ");}

15. public static void go(int n){System.out.print("int ");}

16. public static void main(String[] args){

17. short y = 6;

18. long z = 7;

19. go(y);

20. go(z);

21. } 22. } What is the result?

A. int Long B. Short Long C. Compilation fails.

D. An exception is thrown at runtime.

答案:A

參考:11-1 數字類型

(38)

第174題 Given:

12. Date date = new Date();

13. df.setLocale(Locale.ITALY);

14. String s = df.format(date);

The variable df is an object of type DateFormat that has been initialized in line 11.

What is the result if this code is run on December 14, 2000?

A. The value of s is 14-dic-2000.

B. The value of s is Dec 14, 2000.

C. An exception is thrown at runtime.

D. Compilation fails because of an error in line 13.

答案:D

參考:11-4 數字與日期/時間格式設定

第175題

Which two scenarios are NOT safe to replace a StringBuffer object with a StringBuilder object? (Choose two.)

A. When using versions of Java technology earlier than 5.0.

B. When sharing a StringBuffer among multiple threads.

C. When using the java.io class StringBufferInputStream.

D. When you plan to reuse the StringBuffer to build more than one string.

E. Enitiation of separate design processes to the separation of users 答案:AB

參考:11-2 文字類型

第176題

Place the code fragments into position to produce the output: true true false Code

Scanner scanner = new Scanner("One,5,true,3,true,6,7,false);

scanner.useDelimiter(",");

while( Place hete ){

if( Place hete ){

System.out.print( Place hete + " ");

}else Place hete ; }

Code Fragments

scanner.hasNextBoolean() scanner.nextBoolean() scanner.next() scanner.hasNext() 答案:

(39)

Code

Scanner scanner = new Scanner("One,5,true,3,true,6,7,false);

scanner.useDelimiter(",");

while( scanner.hasNext() ){

if( scanner.hasNextBoolean() ){

System.out.print( scanner.nextBoolean() + " ");

}else scanner.next() ; }

參考:11-5-2 Scanner 類別

第177題 Given:

11. String test = "This is a test";

12. String[] tokens = test.split("\s");

13. System.out.println(tokens.length);

What is the result?

A. 0 B. 1 C. 4

D. Compilation fails.

E. An exception is thrown at runtime.

答案:D

參考:11-5 規則運算式與相關類別

第178題 Given:

1. public class Target{

2. private int i = 0;

3. public int addOne(){

4. return ++i;

5. } 6. } And:

1. public class Client{

2. public static void main(String[] args){

3. System.out.println(new Target().addOne());

4. } 5. }

Which change can you make to Target without affecting Client?

A. Line 4 of class Target can be changed to return i++;

B. Line 2 of class Target can be changed to private int i = 1;

C. Line 3 of class Target can be changed to private int addOne(){

(40)

D. Line 2 of class Target can be changed to private Integer i = 0;

答案:D

參考:11-1 數字類型

(41)

第179題

Place the Relations on their corresponding Implementation Structures. Note Not all Implementation Structures will be used.

Implementation Structures

Relations class A{

List<B> b;

}

class A extends B, C{}

class A{

答案:有 2 個找不到對應的關聯

參考:6-5 繼承、12-3 泛型

第180題

Place the correct description of the compiler output on the code fragments to be inserted at lines 4 and 5. The same compiler output may be used more than once.

1. import java.util.*;

2. public class X{

3. public static void main(String[] args){

4. //insert cede here 5. // insert code here 6. }

7. public static void foo(List<Object> list){

class A{}

class A{

B b;

}

class A implements B, C{}

B c; C c;

}

class A extends B{}

Car is a Vehicle Car is a Collectableand

Car has a SteeringWheel

Car has Wheels

Mini is a Car

Car is an Object

class A{

List<B> b;

}

class A{}

class A{

B b;

}

class A implements B, C{}

class A extends B, C{}

class A{

B c; C c;

}

class A extends B{}

Car is a Vehicle and Car is a Collectable

Car has a SteeringWheel Car has Wheels

Mini is a Car Car is an Object

(42)

8. } } Code

ArrayList<String> x1 = new ArrayList<String>();

foo(x1);

ArrayList<Object> x2 = new ArrayList<String>();

foo(x2);

ArrayList<Object> x3 = new ArrayList<Object>();

foo(x3);

ArrayList x4 = new ArrayList();

foo(x4);

Compiler Output Compilation succeeds.

Compilation fails due to an error in the first statement.

Compilation of the first statement succeeds, but compilation fails due to an error in the second statement.

答案:

Code

ArrayList<String> x1 = new ArrayList<String>();

foo(x1);

ArrayList<Object> x2 = new ArrayList<String>();

foo(x2);

ArrayList<Object> x3 = new ArrayList<Object>();

foo(x3);

ArrayList x4 = new ArrayList();

foo(x4);

參考:12-3 泛型

第181題

Place code into the class so that it compiles and generates the output answer = 42. Note: Code options may be used more than once.

Class

public class Place here { private Place here object;

public Place here ( Place here object){

this.object = object;

}

public Place here getObject(){

return object;

}

public static void main(String[] args){

Code Options Gen<T>

Gen<?>

Gen

? T

Compilation of the first statement succeeds, but compilation fails due to

an error in the second statement.

Compilation fails due to an error in the first statement.

Compilation succeeds.

Compilation succeeds.

(43)

Gen<String> str = new Gen<String>("answer");

Gen<Integer> intg = new Gen<Integer>(42);

System.out.println(str.getObject() + "=" + intg.getObject());

} } 答案:

public class Gen<T>{

private T object;

public Gen ( T object){

this.object = object;

}

public T getObject(){

return object;

}

public static void main(String[] args){

Gen<String> str = new Gen<String>("answer");

Gen<Integer> intg = new Gen<Integer>(42);

System.out.println(str.getObject() + "=" + intg.getObject());

} }

參考:12-3-1 泛型功能介紹

第182題

Given the class definitions:

class Animal{}

class Dog extends Animal{}

and the code:

public void go(){

ArrayList<Dog> aList = new ArrayList<Dog>();

takeList(aList);

}

//insert definition of the takeList() method here

Place the correct Compilation Result on each takeList() method definition to indicate whether or not the go() method would compile given that definition.

takeList() Method Definition

public void takeList(ArrayList list){}

public void takeList(ArrayList<Animal> list){}

public void takeList(ArrayList<? extends Animal> list){}

public void takeList(ArrayList<?> list){}

public void takeList(ArrayList<Object> list){}

Compilation Result

(44)

Compilation succeeds.

Compilation fails.

答案:

takeList() Method Definition

public void takeList(ArrayList list){}

public void takeList(ArrayList<Animal> list){}

public void takeList(ArrayList<? extends Animal> list){}

public void takeList(ArrayList<?> list){}

public void takeList(ArrayList<Object> list){}

參考:12-3 泛型

第183題

Place the code in the appropriate places such that this program will always output [1, 2].

import java.util.*;

public class MyInt Place here Place here { public static void main(String[] args){

ArrayList<MyInt> list = new ArrayList<MyInt>();

list.add(new MyInt(2));

list.add(new MyInt(1));

Collections.sort(list);

System.out.println(list);

}

private int i;

public MyInt(int i){this.i = i;}

public String toString(){return Integer.toString(i);}

Place here int Place here { MyInt i2 = (MyInt)o;

return Place here ; }

}

Code

implements extends sortable Object Comparable protected public i – i2.i i i2.i – i compare(MyInt o, MyInt i2) compare(Object o, Object i2)

sort(Object o) sort(MyInt o) compareTo(MyInt o) compareTo(Object o) 答案:

import java.util.*;

public class MyInt implements Comparable { public static void main(String[] args){

ArrayList<MyInt> list = new ArrayList<MyInt>();

Compilation succeeds.

Compilation fails.

Compilation succeeds.

Compilation succeeds.

Compilation fails.

(45)

list.add(new MyInt(2));

list.add(new MyInt(1));

Collections.sort(list);

System.out.println(list);

}

private int i;

public MyInt(int i){this.i = i;}

public String toString(){return Integer.toString(i);}

public int compareTo(Object o) { MyInt i2 = (MyInt)o;

return i - i2.i ; }

}

參考:12-4-3 SortedSet 集合

第184題

Place each Collection Type on the statement to which it applies.

Statements

allows access to elements by their integer index defines the method V get(Object key) is designed for holding elements prior to processing contains no pair of elements e1 and e2, such that e1.equals(e2)

Collection Types java.util.Map

java.util.Set java.util.List java.util.Queue 答案:

Statements

allows access to elements by their integer index defines the method V get(Object key) is designed for holding elements prior to processing contains no pair of elements e1 and e2, such that e1.equals(e2)

java.util.List java.util.Map java.util.Queue

java.util.Set

參考:12-4 各種集合的特色、12-5 Map 的功能與架構

第185題 Given:

1. public class Person{

2. private String name;

(46)

3. public Person(String name){this.name = name;}

4. public boolean equals(Person p){

5. return p.name.equals(this.name);

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 p.name cannot be accessed in line 5.

C. To work correctly with hash-based data structures, this class must also implement the hashCode method.

D. When adding Person objects to a java.util.Set collection, the equals method in line 4 will prevent duplicates.

答案:A

參考:12-4 各種集合的特色

第186題

Which 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 object inequality for that class.

B. The hashCode method is used by the java.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, but NOT object equality, for that class.

D. The only important characteristic of the values returned by a hashCode method is that the distribution of values must follow a Gaussian distribution.

E. The hashCode method is used by the java.util.HashSet collection class to group the elements within that set into hash buckets for swift retrieval.

答案:CE

參考:12-4 各種集合的特色

第187題 Given:

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 here 10. }

Which method will complete this class?

A. public int compareTo(Object o){/* more code here */}

參考文獻

相關文件

The ProxyFactory class provides the addAdvice() method that you saw in Listing 5-3 for cases where you want advice to apply to the invocation of all methods in a class, not just

• The  ArrayList class is an example of a  collection class. • Starting with version 5.0, Java has added a  new kind of for loop called a for each

The calculation of derivatives of complicated functions involving products, quotients, or powers can often be simplified by taking logarithms. The method used in the next example

The main advantages of working with continuous designs are (i) the same method- ology can be essentially used to find continuous optimal designs for all design criteria and

For an important class of matrices the more qualitative assertions of Theorems 13 and 14 can be considerably sharpened. This is the class of consistly

It is the author’s hope that the Zuting shiyuan may be effectively used as a supplement for understanding Chan texts, and its contributions be fully valued.. Furthermore, the

/** Class invariant: A Person always has a date of birth, and if the Person has a date of death, then the date of death is equal to or later than the date of birth. To be

Note that this method uses two separate object variables: the local variable message and the instance field name.. A local variable belongs to an individual method, and you can use