2009年2月20日 星期五

第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 文字類型

第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 數字與日期/時間格式設定

2009年2月19日 星期四

第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 數字類型

----------------------------------

先找相同型態,再找尋可以自動轉型,最後找可以autoboxing的型態.

第182題




第172題

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 數字與日期/時間格式設定

--------------------------------------------------

先建立一個DateFormat物件, 因為ds內沒有時間, 所以用getDateInstance();
1000 * 60 * 60 * 24 (一天的時間).

第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 規則運算式與相關類別

---------------------------------------

split 為分隔符號, \\d 代表數字, 所以跳過數字不看.

第181題






第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 規則運算式與相關類別

-----------------------------------------

15行 nextInt() 碰到文字就會產生 InputMissmatchException.

第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.
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 數字與日期/時間格式設定

---------------------------------------
setMaximumFractionDigits(4); //小數點到四位數,超過則四捨五入.
setMinimumFractionDigits(2); // 小數點最少取兩位.

第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){
8. } }



第179題



第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(){
D. Line 2 of class Target can be changed to private Integer i = 0;

答案:D
參考:11-1 數字類型
-------------------------------------------------------------------
更改Target類別的內容也不會更改結果
D. Line 2 of class Target can be changed to private Integer i = 0; //會autoynboxing

第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 規則運算式與相關類別

第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()
答案:

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類別

第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類別
-------------------------------------------------------
12. if(testIfB("True")){
>> 18. public Boolean testIfB(String str){
>> 19. return Boolean.valueOf(str); //把字串"True"變Boolean的True

第167題

Given:
11. String test = "Test A. Test B. Test C.";
12. //insert code here
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 規則運算式與相關類別
-----------------------------------------------------------
第12行插入code而原字串變成"Test A", "Test B", and "Test C"
E. String regex = "\\.\\s*"; // \\.=小數點,\\s*=空白

第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 數字類型
-----------------------------------------------
3. Boolean test = new Boolean(true); //test =true
5. Integer y = new BuildStuff().go(test, x); //x=343
9. if(b) return (i/7); //b=true...343/7=49

第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 數字與日期/時間格式設定
--------------------------------------------------------------------
第23行要插入code讓程式compile成功

E. df = DateFormat.getInstance(); //會取得DateFormat的物件實體

第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 數字與日期/時間格式設定

第163題

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 文字類型
----------------------------------------------------------

A. 字串不能用減號
C. 字串沒有delete
D. 字串沒有delete

第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 數字類型
-----------------------------------------------------
12. Integer i = new Integer(1) + new Integer(2); //i=3

2009年2月18日 星期三

JDK 版本名稱

VersionDateCodeName中文名稱
JDK 1.0(January 23, 1996)Oak.橡樹
JDK 1.1 (February 19, 1997)
J2SE 1.2(December 8, 1998)Playground遊樂場
J2SE 1.3(May 8, 2000) Kestrel茶隼
J2SE 1.4(February 6, 2002) Merlin
J2SE 5.0(September 30, 2004)Tiger
Java SE 6(December 11, 2006)Mustang 野馬
Java SE 7recent Dolphin海豚

第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 數字類型

------------------------------------

Integer i 沒有給初始值, 所以初始值是 null, null 跟 數字相機阿就產生 NullPointerException

第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 文字類型

----------------------------------------

sb1.append("abc"); //原來的字串後面插入abc , 123abc
s1 = s1.concat("abc"); //concat() 會做串接, 並產生一個新的實體. 所以要在指定回給s1.

第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類別

--------------------------------------------------------------

314.159,26 在義大利文裡,小數點是千分符號, 逗點是小數點, 跟一般常用相反.
nf取得ITALIAN格式後在 格式化.

第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);
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 數字與日期/時間格式設定

----------------------------------------

解析第17行 變成 Date, 並用ParseException 去接可能發生的例外.

第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類別

------------------------------------

11. String pw = c.readPassword("%s", "pw: "); //回傳字元陣列, 而不是字串

第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){
e.printStackTrace();
}
}
}
參考:10-5-1 BufferedReader與BufferedWriter類別

------------------------------------

BufferedReader 是屬於 IO

第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);
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類別

2009年2月17日 星期二

第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);
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類別

-------------------------------------

System.out.printf("%7.3f \n", d);
// 7 = 寬度
// .3 = 小數點後幾碼
// f = 類型 float.

第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 多重串接

-----------------------------------------

writeObject 是專門序列化的方法, 裡面先寫入
s.writeInt(x); s.writeInt(y);
readObject 反序列化就是把他讀取出來.
所以x = s.readInt(); y = s.readInt();

第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.
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類別

------------------------------------------

14. File dir = new File("dir"); //命名一個檔名為dir
15. dir.mkdir(); // 用此名建立一個目錄
16. File f1 = new File(dir, "f1.txt"); // 在dir 下面開一個 f1.txt
18. f1.createNewFile(); // 建立檔案.
20. File newDir = new File("newDir"); //命名一個檔名為 newDir
21. dir.renameTo(newDir); //把原來的 dir 改成 newDir.

第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 多重串接

--------------------------------------

什麼樣的能力只存在於BufferedWriter裡面,
可以換行 (new line) /n

第143題

Given:
System.out.printf("Pi is approximately %f and E is approximately %b, Math.PI, Math.E);
Place the values where they would appear in the output.
答案:
Pi is approximately 3.141593
and E is approximately true
參考:10-2 Console類別、11-1 數字類型
----------------------------------------
%f 格式化 Math.PI , float
%b 格式化 Math.E , 除非是布林值的 false, 不然就是true.

第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 多重串接

-------------------------------------

20. b.serializeBanana(b); // 序列化b
21. b2 = b.deserializeBanana(); //反序列化 b 給 b2, 此時 b2 的實體跟b 一樣.

第141題

Given:
11. class A{
12. public void process(){System.out.print("A, ");}
13. class B extends A{
14. public void process() throws IOException{
15. super.process();
16. System.out.print("B, ");
17. throw new IOException(),
18. }
19. public static void main(String[] args){
20. try{new B().process();}
21. catch(IOException e){System.out.println("Exception");}
22. }

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拋出例外事件。

-----------------------------------

14行 子類別B 裡的process 要改寫 父類別A的 process, 但 父類別的 process 並沒有 throws IOException

第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

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

------------------------------------

ClassA a = new ClassA();
並呼叫 a.mthodA();
>>12. ClassB classB = new ClassB();
>>13. classB.getValue();
>>>23. public String getValue(){
>>>24. return classC.getValue(); //此時產稱 NullPointerException,
原因21. public ClassC classC; 沒有實體化,預設初始值是null;

第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{
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拋出例外事件。

-----------------------------

11行呼叫了 SayHello(), 並SayHello() 說明了可能會拋出TestException, TestException 是 Exception 子類別, 所拋出的exception由第10行處理, 所以第10行必須有try / catch 或是 手動 throw Exception.

第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類別
-------------------------------------------------------------------------------------------------
從主控台的模式下讀取一列資料
String s = c.readLine...

第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" )));
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類別

第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類別
-----------------------------------------------------------------------------------------
B. An object serialized on one JVM can be successfully deserialized on a different JVM.
如果一個物件在一個jvm上做序列化就可以在另一個jvm上做反序列化
ex:執行一個程式產生一個新的jvm,這個程式是把物件寫入檔案中...
再開一個程式把產生另一個jvm,反序列化就是檔案取出
D. The values in fields with the transient modifier will NOT survive serialization and deserialization.
屬性加上transient的修飾詞 在序列化過程中就不會保留它的值,因此在做反序列化時

會取出系統預設的初始值,換句話說不會保留原有的值
E. It is legal to serialize an object of a type that has a supertype that does NOT implement java.io.Serializable.
如果現在要序列化一個物件,該物件所屬類別的父類別不需要實做java.io.Serializable,

但該物件是需要實做

第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例外事件與處理機制

---------------------------------------------------

16行呼叫test() 之後,
12. 會產生一個 AssertionError();
由第11行 throw Error 拋回給main();

但是17的 Exception 無法處理, 原因 Exception跟Error沒有繼承關係.
所產的Error是一個throwable物件 由main()拋出.

第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. }
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例外事件與處理機制

-------------------------------------------

19. try{test();}
>>11. static void test(){
>>13. String x = null;
>>14. System.out.print(x.toString() + " "); //產生null pointer exception ,因為 x = null;
>>16. finally{System.out.print("finally ");} // output finally
>>>>20. catch(Exception ex){System.out.print("exception ");} //接到 exception, output exception.

第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

--------------------------------------------------

第18行 final 要搭配 try / catch

第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類別
---------------------------------------------------------------------
4. File dir = new File("dir"); //建立dir物件
5. File f = new File(dir, "f"); //建立f物件
但都沒有呼叫...create new file 或 mkdirs
所以沒有東西新增到檔案系統中

第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 got aiko
D. An exception is thrown at runtime.
E. Compilation fails due to an error on line 8.

答案:E
參考:10-2 Console類別
----------------------------------------------------------------------
8. Console c = new Console(); //外部物件不能直接呼叫...,要用syatem.Console()

第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);
} ? . Place here ();
}catch(Exception ex){
ex.printStackTrace();
}
}
}


Code Fragments
BufferedReader
StreamReader
FileReader
readLine
readLn
read
closeFile
close
x1

x2
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類別

第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 多重串接

第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. }
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。

----------------------------------------------------------

method2()的exception 拋出給原呼叫式 第5行的b.method2(); 並由 Method1()的try / catch 接住.
然後丟出 RuntimeException(te).
原本拋出的TestException 已經被處理掉, 另RuntimeException不需要被處理.

第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錯誤事件

------------------------------------------------

第3行一值都是true,
第4行 assert 要為 false才會執行後面的程式碼.

2009年2月16日 星期一

第140題

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拋出例外事件。
-----------------------------------------------------------------------
類別c的第3行會產生NullPointerException
25. try{
26. A a = new A();
27. a.method1();
>>2. public void method2(){
>>3. C c = new C();
>>4. c.method3();
>>>>2. public void method2(){
>>>>3. C c = new C();
>>>>4. c.method3();
>>>>>>2. public void method3(){ //產生NullPointerException
NullPointerException會丟回原呼叫的27. a.method1(); 後再被28行catch到後執行第29行

第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錯誤事件
-------------------------------------------------------------------------
第12行中加code處理空值的情況
D. if (value == null){ //先檢查是否為空值
throw new IllegalArgumentException("value is null"); //為空值時再產生Exception
}

第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錯誤事件
---------------------------------------------------------
那二個會產生 StackOverflowError?
StackOverflowError=方法不斷的呼叫自己,導至遞回過深而產生所以呼叫的上限
D. void doOne(int x){doTwo(x);}
void doTwo(int y){doThree(y);}
void doThree(int z){doTwo(z);} //出不去
F. void counter(int i){counter(++i);} //出不去

第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
參考:9-3 使用throw自行產生例外事件、9-5 使用throws拋出例外事件。
--------------------------------------------------------------------
20. new SubB().foo();
>>14. public void foo() throws RuntimeException{
>>15. super.foo(); //x
>>>>16. if(true) throw new RuntimeException(); //Exception
>>>>20. new SubB().foo();

第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例外事件與處理機制。
-------------------------------------------------------
16. }catch(Exception ex) { 為
18. }catch(NullPointerException npe){ 的父類別
所以要照子類別放前,父類別放後的規則

第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

參考:9-2 Java例外事件與處理機制。
-------------------------------------------------------------------
題目說第86行會產生ResourceException
所以第88 行不會被run到

第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。
----------------------------------------------------------------------------------------
13. A a = new SubB2(); //實體SubB2(),宣告類型A
14. a.foo();//如果在執行階段會call第9 行,
但要先看編譯階段因為編譯階段早於執行階段
從編譯階段看 a為A的類型,所以編譯器會認為第14行會call第6 行
6. void foo() throws Exception{throw new Exception();} //會丟出Exception
所以14. a.foo(); 要用try-catch包起來 或者main要加throws Exception
但都沒有所以D. Compilation fails due to an error on line 14.

第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例外事件與處理機制

------------------------------------------------------------------
第37行在何情況下會被執行?
在33或35行執行過不管成功與否都會執行第37行
但第31行如果發生問題的話就不會執行第37行

第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例外事件與處理機制

第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
D. test exception end
E. A Throwable is thrown by main at runtime.

答案:D
參考:9-2 Java例外事件與處理機制
------------------------------------------------------------------------------
19. try{test();}
>>13. System.out.print("test ");
>>14. throw new RuntimeException();
>>16. catch(Exception ex){ System.out.print("exception ");}
>>21. System.out.print("end ");

第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例外事件與處理機制
-------------------------------------------------------------------------

13. float f = Float.parseFloat(str); //在try 中f
15. f = 0; //不同於13行的區域變數f

第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
D. Line 19
E. The object is NOT a candidate for garbage collection.

答案: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列舉類型
-------------------------------------------

沒18. case default: 這種語法

第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
答案:D
參考:8-7 資源回收機制
-------------------------------------------------------------------------
第4 行的doSomething 被呼叫後,第5行的o 何時會被資源回收