In thefollowing code, which lines will be printed on the standard output?
publicclass Test
{
Public void method1(int x) throws Exception
{
try
{
method2(x);
System.out.println("Checkpoint1");
}
finally
{
System.out.println("Checkpoint 2");
}
System.out.println("Checkpoint3");
}
publicvoid method2(int x) throws Exception
{
if (x < 0)
{
throw new NegativeArraySizeException();
}
}
staticpublic void main(String[] args) throws Exception
{
Test t =new Test();
t.method1(-55);
System.out.println("Checkpoint4");
}
}
A.Checkpoint 1
B. Checkpoint 2
C.Checkpoint 3
D.Checkpoint 4
Given:
11.classA{
12.public void process() { System.out.print(”A“); } }
13. classB extends A {
14.public void process() throws NullPointerException {
15.super.process();
16. if(true) throw new NullPointerException ();
17. System.out.print(“B”); }}
18.public static void main(String[] args) {
19. try { ((A)new B()).process(); }
20. catch(Exception e) { System.out.print(”Exception“); }
21. }}
What isthe result?
(Choose One)
A.Exception
B. A Exception
C. AException B
D. A BException
E.Compilation fails because of an error in line 14.
F.Compilation fails because of an error in line 19.
答案:B
NullPointerException也是RuntimeException, 所以此处不认为子类重写方法抛出了比父类对应方法更多的异常。
Question15
Click theExhibit button.
ClassTestException
1. publicclass TestException extends Exception {
2. }
Class A:
1. publicclass A {
2.
3. publicString sayHello(String name) throws TestException {
4.
5.if(name == null) {
6. throw new TestException();
7. }
8.
9. return “Hello “+ name;
10. }
11.
12. }
Aprogrammer wants to use this code in an application:
45. Aa=new A();
46. System.out.println(a.sayHello(”John”));
Which twoare true?
(ChooseTWO)
A. ClassA will not compile.
B. Line46 can throw the unchecked exception TestException.
C. Line45 can throw the unchecked exception TestException.
D. Line 46 will compile if theenclosing method throws a TestException.
E. Line 46 will compile ifenclosed in a try block, where TestException
is caught.
答案: DE
检查异常TestException要么显式抛出或者捕获处理。
Analyze the following two classes
1. class First
2. {
3. static int a = 3;
4. }
5.
6. final class Second extendsFirst
7. {
8. void method()
9. {
10. System.out.println(a);
11. }
12. }
(Choose One)
- Class First compiles, but class Second does not.
- Neither class compiles.
- Both classes compile, and if method() is invoked, it writes 3 to the output.
- Both classes compile, and if method() is invoked, it throws an exception.
答案;C
静态属性也将被子类继承。
访问静态属性,最好直接直接使用类名,但使用this也是可以的,只是不推荐,容易在阅读代码过程中产生混淆。
Question 11
What will be the result of attempting to compile and run thefollowing code?
Object o1 = new Object();
Object o2 = new Object();
o1 = o2;
if(o1.equals(o2)) { System.out.println("Equals"); }
(Choose One)
- Compile time error
- "Equals"
- No output
- Run time error
答案: B
因为o1和o2指向了同一个对象,object的equals方法,只有在自己和自己比较时才相等。