首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java 考题备忘

2012-12-26 
Java 试题备忘1.Given the following class definitions, what is the output of the statement new Child

Java 试题备忘
1.
Given the following class definitions, what is the output of the statement new Child();
1. class Parent {
2.     {
3.         System.out.print(“1”);
4.     }
5.
6.     public Parent(String greeting) {
7.         System.out.print(“2”);
8.     }
9.  }
10.
11. class Child extends Parent {
12.     static {
13.         System.out.print(“3”);
14.     }
15.
16.     {
17.         System.out.print(“4”);
18.     }
19. }
A. 1234
B. 3123
C. 3142
D. 3124
E. The code does not compile.


E. The Child class gets the default constructor because it does not defi ne a constructor explicitly. The default constructor contains the line super(); which does not compile because Parent does not have a no-argument constructor. Therefore, the correct answer is E.



2.
Given the following class definition:
1. public class Forever {
2. public void run() {
3. while(true) {
4. System.out.println(“Hello”);
5. }
6. System.out.println(“Goodbye”);
7. }
8. }
what is output of the following statement?
new Forever().run();
A. Prints Hello indefinitely
B. Prints Hello until an error occurs
C. Prints Hello until an error occurs, then prints Goodbye
D. Compiler error on line 3
E. Compiler error on line 6

answer:
The code does not compile, so A, B, and C are incorrect. Line 3 is fi ne — you can declare an infi nite while loop. The compiler is aware that line 3 is an infi nite loop and that line 6 is an unreachable statement, so the compiler generates an error at line 6. Therefore, the answer is E.

3.
What is the output of the following program?
1. public class MathProblem {
2.     public static int divide(int a, int b) {
3.         try {
4.             return a / b;
5.         }catch(RuntimeException e) {
6.             return -1;
7.         }catch(ArithmeticException e) {
8.             return 0;
9.         }finally {
10.            System.out.print(“done”);
11.        }
12.     }
13.
14.     public static void main(String [] args) {
15.         System.out.print(divide(12, 0));
16.     }
17. }
A. - 1
B. 0
C. done0
D. done - 1
E. The code does not compile.
answer:
E. The order of catch blocks is important because they are checked in the order they appear after the try block. Because ArithmeticException is a child class of RuntimeException , the catch block on line 7 is unreachable. (If an ArithmeticException is thrown in the try block, it will be caught on line 5.) Line 7 generates a compiler error because it is unreachable code, so the answer is E.

热点排行