有关SCJP1000题的部分笔记

37.How can you prevent the kind of memory leaks described in the previous question? (The previous question:True or false? As a consequence of automatic garbage collection, the problem of "memory leaks" prevalent in C and C++ is completely eliminated in Java.)

答案:Purposely assign null to all reference variables that refer to an object when you no longer need that object.

解析:在Java中,尽管有GC,但依然会出现内存泄漏。尽量采用上面的办法。

66.The valid integral expressions in Java are NN, 0NN, 0xNN and 0XNN.

问题:C与C++中如何表达?

77.Give the following method:

  1. public void method() {
  2. String a, b;
  3. a = new String("Hello, world!");
  4. b = new String("game over");
  5. System.out.println(a + b + "ok");
  6. a = null;
  7. a = b;
  8. System.out.println(a);
  9. }

In the absence of compiler optimization, which is the earliest point the object a referred is definity eligible to be garbage collection?

答案:Before line 6.

解析:第6行代码把null赋值给引用变量a后,a以前保存的引用所指向的内存空间就失去作用,应被释放。所以GC可能最早回收a.回收了怎么还去打印?回收了可以再调出来么?

175.Which statements about Java code security are true?

  1. The bytecode verifier loads all classes needed for the execution of a program.
  2. Executing code is performed by the runtime interpreter.
  3. At runtime the bytecodes are loaded, checked and run in an interpreter.
  4. The class loader adds security by sepating the namespace for the classes of the local file system from those imported from network sources.

答案:B C D

解 析:Java程序运行过程:类加载器(class loader)加载程序运行时需要的所有类,它通过区分本机文家系统的类和网络文件系统导入的类增加安全性。因为本机类总是先被加载,一旦所有类被加载 完,执行文件的内存划分就固定了,这时候特定的内存地址被分配给对应的符号引用,查找表也被建立。由于内存划分发生在运行时,解释器在受限制代码区增加保 护以防止未授权访问;然后字节码校验器进行校验。主要执行的检查是:类符合JVM规范的类文件格式,没有违反访问限制,代码没有造成堆栈的上溢或下溢,所 有操作代码的参数类型都是正确的,没有非法数据类型转换发生;校验通过的字节码被解释器执行。

576. "The Employee object is a person, an Employee has appointment store in a vector, a hire date and a number of dependent"

short answer: use shortest statement declare a class of Employee

答案:public class Employee extends Person

解析:is a表示同类型,用extend完成类型的继承

has a表示合成概念

624.这段程序的输出结果是什么?

import java.io.IOException;

class A {

A() {

System.out.println("Executing class A constructor");

}

A(int a) throws Exception {

System.out.println("Executing class A constructor");

throw new IOException();

}

}

public class B extends A {

B() {

System.out.println("Executing class B constructor");

}

public static void main(String args[]) {

try {

A a = new B();// 注意a对象的构造

} catch (Exception e) {

System.out.println(e.getMessage());

}

}

}

答案:"Executing class A constructor" followed by "Executing class B constructor" .

解析:在调用子类构造器创建一个对象时,会在子类构造器中先调用父类构造器。

  1. (640) 在同一个类的不同构造方法中调用该类的其他构造方法需要使用this(...)形式,而且必须是在构造器的第一行调用。构造方法是一个类对象实例化的起点 (严格地说首先执行的并不是构造方法的第一个语句,而是内存的分配),在构造方法中不能将类成员作为参数引用。
  2. (695) If there is more than one thread waiting on a condition, there is no way to predict which thread will be notified.