2010年9月12日 星期日

JAVA-CORE 面試題

Question: How could Java classes direct program messages to the system console, but error messages, say to a file?

Answer: The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:

Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

Question: Why would you use a synchronized block vs. synchronized method?

Answer: Synchronized blocks place locks for shorter periods than synchronized methods.

Question: Explain the usage of the keyword transient?

Answer: This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

Question: How can you force garbage collection?

Answer: You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

Question: What's the difference between the methods sleep() and wait()

Answer: The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

Question: Can you call one constructor from another if a class has multiple constructors

Answer: Yes. Use this() syntax.

Question: How would you make a copy of an entire Java object with its state?

Answer: Have this class implement Cloneable interface and call its method clone().

clone() 預設是 重新配置一塊記憶體,並予以 copy ,
所以內容與原來的是一模一樣, 但是分屬不同的空間
所以 x.clone() 當然不等於 x


沒有留言:

張貼留言