Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
單元 7 內部類別、文字類型、異常處理 1. 內部類別(Inner Classes) 定義在類別(class)中的類別(class)即稱為內部類別(inner class)。 內部類別分成下面四種: 靜態成員內部類別(Static Member Class), 成員內部類別(Member Class), 區域內部類別(Local Class)和匿名內部類別(Anonymous Class),分別介紹如下: A. 靜態成員內部類別(Static Member Class) 類似外圍類別(containing class)的靜態成員,與外圍類別的實例(instance)沒有關聯。 靜態成員內部類別的使用方法: Outer.Inner in = new Outer.Inner() ; 範例: public class Test { static int i; protected static class Inner { public void h() { i = 3; System.out.println(i); } } public static void main(String[] args) { Inner inn = new Inner(); inn.h(); // 2 } } class A { public static void main(String[] args) { Test.Inner ic = new Test.Inner(); ic.h(); // 3 } } B. 成員內部類別(Member Class) 類似外圍類別(containing class)的實例變數(instance field)或實例方法(instance method)。每 個成員類別的實例(instance)是與外圍類別的實例結合在一起的。 成員內部類別的使用方法: Outer.Inner in = new Outer().new Inner() ; 範例: public class Test { int i; public class Inner { public void h() { i = 3; System.out.println(i); } } public static void main(String[] args) { Test t = new Test(); Inner inn = t.new Inner(); inn.h(); } } class A { public static void main(String[] args) { Test.Inner ic = new Test().new Inner(); ic.h(); } } C. 區域內部類別(Local Class) 有效範圍只限於這個區塊內。 區域變數的生命,始於 JVM 進入它所在的區塊執行,結束於 JVM 離開它所在的區塊。 若一個類別只會在某個方法內被使用,可使用區域內部類別。 範例: class Test { private int x = 3; public void g() { final int i = 4; int j = 5; class Inner { int k = 6; public void f() { int m = 7; System.out.print(x); System.out.print(i); //System.out.print(j); // compile error System.out.print(k); System.out.print(m); } } Inner in = new Inner(); //create Inner class 的 object in.f(); //呼叫 Inner class 的 method } public static void main(String[] args) { Test t = new Test(); //Inner in = new Inner(); in.f(); //Inner is out of scope t.g(); } } D. 匿名內部類別(Anonymous Class) 匿名內部類別是區域內部類別(Local Class)的一種,但沒有類別名稱(class name)。 匿名內部類別不能有建構子 若某類別只會被使用一次,可使用匿名內部類別。 成員內部類別的使用方法: new ClassName ([paralist]) {class body} new InterfaceName () {class body} 範例: class A { int i; A(int i) { this.i = i; } void f() {System.out.println("A");} } class Test { public void g(A a) { a.f(); } public static void main(String[] args) { Test t = new Test(); 2 t.g( new A(2) { void f() {System.out.println(i);} } ); // 2 } } 模擬試題 Question 1 Given the following Java code: 22. class Line 23. { public static class Point {} 24. } 25. 26. class Triangle 27. { //insert code here 28. } Which code, inserted s 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 instantiated a t line 15. D. Lind 1 = new Line(); 1.Point p = new 1.Point(); 答案 B Question 2 Given the following Java code: 9. public class Test{ 10. static class A { 11. 12. void process ( ) throws Exception { throw new Exception ( ) ; } } 13. 14. static class B extends A { void process ( ) { System.out.println( “ B ” ); } 15. 16. } 17. public static void main (String[ ] args ) { 18. A a = new B ( ); 19. a.process ( ); 20. } 21. } 3 What is the result? A. B B. The code exception is thrown at runtime C. The code run with no output D. Compilation fails because of an error in line15. E. Compilation fails because of an error in line18. F. Compilation fails because of an error in line19. 答案 F Question 3 Given the following Java code: 10. interface Foo { 11. int bar( ); 12. } 13. 14. public class Beta { 15. 16. class A implements Foo { 17. 18. Public int bar( ) { return 1; } } 19. 20. public int fubar(Foo foo ) { return foo.bar( ); } 21. 22. public void testFoo( ) { 23. 24. class A implements Foo { 25. 26. public int bar( ) { return 2; } } 27. 28. 29. System.outprintln( fubar( new A( ) ) ); } 30. 31. public static void main( String[ ] argv ) { 32. 33. New Beta( ).testFoo( ); } 34. } Which three statements are true? (choose three) A. Compilation fails B. The code compiles and the output is 2 4 C. If lines 16, 17, and 18 were removed, compilation would fail. D. If lines 24, 25, and 26 were removed, compilation would fail. E. If lines 16, 17, and 18 were removed, the code would compile and the out would be 2. F. If lines 24, 25, and 26 were removed, the code would compile and the out would be 1. 答案 B,E,F Question 4 Given the following Java code: 1. package geometry; 2. public class Hypotenuse { 3. public InnerTriangle it = new InnerTriangle( ); 4. class InnerTriangle { 5. public int base; 6. public int height; 7. 8. } } Which statement is true about the class of an object that can reference the variable base ? A. It can be any class。 B. No class has access to base。 C. The class must belong to the geometry package。 D. The class must be a subclass of the class Hypotenuse。 答案 C Question 5 1. interface TestA { String toString(); } 2. public class Test { 3. public static void main(String[] args) { 4. System.out.println(new TestA() { 5. public String toString() { return “test”; } 6. }); 7. } 8. } 9. Given: What is the result? A. test B. null C. An exception is thrown at runtime. 5 D. Compilation fails because of an error in line 1. E. Compilation fails because of an error in line 4. F. Compilation fails because of an error in line 5. 答案 A Question 6: 擬真試題講義: 第 114 題 2. String 類別 String 物件為不可變更的(immutable)物件,其內的字元或字串長度都不可變更,而且字串的方 法都是回傳一個新的 string 物件。 String 物件的長度可以透過 length()方法取得。 利用 String 物件的 charAt()方法可以使用索引值取得字串裡的某個字元 範例: class Test { public static void main(String [] args) { String str = "我愛人人"; int len = str.length(); for(int i=len-1; i>=0; i--) System.out.print( str.charAt(i) ); System.out.println(); //人人愛我 } } String 類別的尋找字元和子字串的方法 int int int int indexOf (String str) indexOf (String str, int from) lastIndexOf (String str) lastIndexOf (String str, int from) 尋找字串 str 的位置。 從 from 開始尋找字串 str。 尋找最後一個字串 str 的位置。 從 from 開始尋找最後一個 str。 String 類別的擷取子字串方法 public String substring(int beginIndex) public String substring(int beginIndex, int endIndex) 範例: public class Test { public static void main(String[] args) { String str = "How are you"; int firstspace = str.indexOf(' '); int secondspace = str.indexOf(' ',firstspace+1); 6 System.out.println( str.substring(0,firstspace) ); System.out.println( str.substring(firstspace+1,secondspace) ); System.out.println( str.substring(secondspace+1) ); } } 字串的比較 以比較運算子「==」判斷兩個 String 物件時,是判斷兩者是否指向相同的參考。 String 類別的 equals()方法,其功能是比較兩個 String 物件的內容而不是參照。 如果要忽略英文字母的大小寫,可以使用 equalsIgnoreCase()方法。 String 類別其餘的方法 串接字串 取代字元 Trim String concat(String str)//附加在原 string 的後面 String replace(char oldChar, char newChar) // “abbbcdeb”.replace(‘b’,’k’)”akkkcdek” String trim() //移除 string 前後兩端的”white space”(如空白或’\t’...) 3. StringBuffer 類別 StringBuffer 是可變的。 StringBuffer append(String str) StringBuffer append(char[] str) StringBuffer append(char[] str, int offset, int len) StringBuffer insert(int index, char[] str, int offset, int len) StringBuffer insert(int offset, String str) StringBuffer insert(int offset, char[] str) StringBuffer delete(int start, int end) StringBuffer deleteCharAt(int index) 取代字串 StringBuffer replace(int start, int end, String str) 顛倒字串 StringBuffer reverse() 續接字串 插入字串 刪除字串 4. StringBuilder 類別 StringBuilder 的 API 和舊的 StringBuffer 的 API 一樣,除了 StringBuilder 的函式是未受同步控 制(non-synchronized)。 StringBuilder 函式的執行速度比 StringBuffer 來的快。 StringBuilder 有與 StringBuffer 有下列的相同點: 它們是可變的-改變它們的值時,不需要新增物件。 它們的方法會對正執行的物件值起作用,物件的值可以改變。 Question 7 Given the following Java code: 1. 2. public class Test { public static void main ( String[] args ) { 7 3. // insert code here 4. 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).replace(1,3,””).delete(2,5).insert(1, “24”); 答案 B, E Question 8 Given the following Java code: 11. public static void test (String str) { 12. int check = 4; 13. if (check = str.length ( ) ) { System.out.print( str.charAt ( check -= 1 ) + “ 14. 15. } else { System.out.print( str.charAt( 0 ) + “ 16. 17. 18. “ ); } } and the invocation: test( “four” ) ; test( “tee” ) ; test( “to” ) ; What is the result? A. r t t B. r e o C. Compilation fails 8 “ ); D. An exception is thrown at runtime 答案:C Question 9 Given this method in a class: 21. public String toString( ) { 22. StringBuffer buffer = new StringBuffer( ); 23. buffer.append ( ‘<’ ); 24. buffer.append ( this.name ); 25. buffer.append ( ‘>’ ); 26. return buffer.toString( ); 27. } Which statement is true? A. This code in NOT thread-safe. B. The programmer can replace StringBuffer with StringBuilder with no other changes. C. This code will perform poorly. For better performance, the code should be rewritten: return”<” + this.name +”>”; D. This code will perform well and converting the code to use StringBuilder will not enhance the performance. 答案 B Question 10 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.out.println(”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. 9 答案 D Question 11-13: 擬真試題講義: 第 41,160,175 題 5. 異常處理機制 錯誤或例外都是 java.lang.Throwable 的延伸類別 Error 及其延伸類別:其為嚴重的錯誤,通常捕捉到也無法處理,因此也很少去捕捉。 Exception 及其延伸類別(不包含 RuntimeException 及其延伸類別) :這類例外在一般情況很可能發生, 大多屬於環境問題,又稱可控式異常(Checked Exception) RuntimeException 及其延伸類別:此類例外為程式的執行期錯誤,例如,某數除以 0、陣列索引值超出 範圍等,又稱非可控式異常(Unchecked Exception)。 java.lang.Object java.lang.Throwable java.lang.Error java.lang.VirtualMachineError java.lang.Exception java.io.IOException java.lang.ClassNotFoundException java.lang.RuntimeException java.lang.ArithmeticException java.lang.ArrayStoreException java.lang.IllegalArgumentException java.lang.NumberFormatException java.lang.IllegalStateException java.lang.IndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.StringIndexOutOfBoundsException java.lang.NullPointerException 常見的 RuntimeException(Unchecked Exception) 執行期例外 說明 ArithmeticException 數學運算時的例外。例如:某數除以 0。 ArrayIndexOutOfBoundsException 陣列索引值超出範圍。 NegativeArraySizeException 陣列的大小為負數。 NullPointerException 物件參照為 null,並使用物件成員時所產生的例外。 10 NumberFormatException 數值格式不符所產生的例外。 try-catch 敘述用以捕捉並處理例外 範例: int divider = 0; try { int M = 100; int N = M / divider; } catch (ArithmeticException e) { e.printStackTrace(); } 只要是 Throwable 或其延伸類別之物件,都可以使用 try-catch 敘述捕捉。 try-catch 敘述可以使用多個 catch 區塊 頂多只會有一個 catch 區塊內的敘述被執行。 特化的例外型別須放在較前的 catch 敘述內。 範例: int divider = 0; try { int M = 100; int N = M / divider; } catch (ArithmeticException e) { System.out.println("除以零的錯誤!"); } catch (Exception e) { e.printStackTrace(); } finally 區塊 不論有沒有例外發生,finally 區塊內的敘述皆會執行。 範例: int divider = 0; try { int M = 100; int N = M / divider; System.out.println(N); } catch (ArithmeticException e) { System.out.println("除以零的錯誤!"); } finally { System.out.println("The end!"); } 11 exception 發生時處理方式: 找到適當 catch 執行 catch block,再執行 finally block,然後程式執行恢復正常。(即執行 finally block block 之後的 statement) 未找到適當 執行 finally block,再將控制權交給外層的 try/catch/finally statement。若所 catch block 有外層都未 catch 住這個 exception,程式異常終止。 使用 throw 敘述在程式中丟出例外物件 throw new RuntimeException(“除數為零”); throw new Exception(“找不到檔案”); throws 關鍵字 throws 關鍵字使用於方法或建構子定義的標頭,用來指出例外發生時,由方法(或建構子)丟出的例外型 別。 throws 之後可以接多個例外型別名,表示方法執行過程中可能丟出屬於這些例外型別的物件。 方法不可以使用 throw 丟出不包含在 throws 宣告的例外型別之物件 範例: class Test { public static int divide(int M, int divider) throws RuntimeException { if (divider==0) throw new RuntimeException(“除數為零”); int N = M / divider; return N; } public static void main(String [] args) { int divider = 0; try { int M = 100; int N = divide(M,divider); System.out.println(N); } catch (RuntimeException e) { System.out.println(e.getMessage()); } } } 相對於要被覆寫的函式,一個覆寫函式: 不能丟出新的或範圍更廣的可控式異常(checked exception)。 可以丟出更少或範圍更狹隘的可控式異常(checked exception),或任何非可控異常(unchecked exception)。 Question 14 Given the following Java code: 12 33. try { 34. // some code here 35. } catch( NullPointerException e1 ) { 36. System.out.print(“a”); 37. } catch( RuntimeException e2 ) { 38. System.out.print(“b”); 39. } finally { 40. System.out.print(“c”); 41. } What is the result if NullPointerException occurs on line 34? A. c B. a C. ab D. ac E. bc F. abc 答案 D Question 15 Given the following Java code: 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. } 13 1. public class C { 2. public void method3( ) { 3. // more code here 4. } 5. } And: 25. try { 26. A a = new A ( ); 27. a.method1( ); 28. } catch ( Exception e ) { System.out.print( “ an error occurred” ); 29. 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 line29 will be executed. C. The code on line5 of class A will execute D. The code on line5 of class B will execute E. The exception will be propagated back to line 27 答案 B,E Question 16 Given the following Java code: 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. 19. { } } What is the result? A. test B. Exception C. Compilation fails D. NullPointerException 答案 B 14 Question 17 Given the following Java code: 11. class A { 12. public void process( ) { System.out.print(“A, ”); }} 13. class B { 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”); 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 Question 18 Given the following Java code: 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 15 }}} E. A Throwable is thrown by main F. An Exception is thrown by main 答案 E Question 19 Given the following Java code: 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.pritnln(“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 Questin 20 Given the following Java code: 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. 16 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 Question 21 11. public static void parse(String str) { 12. try{ 13. float f = Float.parseFloat( str); 14. } 15. catch(NumberFormatException e){ 16. f = 0; 17. } 18. finally { 19. System.out.println(f); 20. } 21. } 22. public static void main(String[] args){ 23. parse(“invalid”); 24. } 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 Question 22 Given the following Java code: class SomeException: 1. public class SomeException { 2. } class A: 1. public class A { 2. 3. public void doSomething( ) {} } class B: 1. public class B extends A { 17 2. 3. public void soSomething( ) throws SomeException {} } Which statement is true about the two classes? A. Compilation of both classes will fail. B. Compilation of both classes will succeed. C. Compilation of class A will fail, Compilation of class B will succeed. D. Compilation of class B will fail, Compilation of class A will succeed. 答案:D Question 23 Given the following Java code: 10. public class ClassA { 11. public void count( int i) { 12. count( ++i ); 13. } 14. } And: 20. ClassA a = new ClassA( ); 21. a.count(3); Which exception or error should be thrown by the virtual machine? A. StackOverflowError B. NullPointerException C. NumberFormatException D. IllegalArgumentException E. ExceptionInInitializerError 答案:A Question 24-31: 擬真試題講義: 第 124,126,128,,130,132-134,138 題 18