Set - 1

Question 16 :

Jack developed a program by using a Map container to hold key/value pairs. He wanted to make a change to the map. He decided to make a clone of the map in order to save the original data on side. What do you think of it?

Answer :

If Jack made a clone of the map, any changes to the clone or the original map would be seen on both maps, because the clone of Map is a shallow copy. So Jack made a wrong decision.


Question 17 :

What is more advisable to create a thread, by implementing a Runnable interface or by extending Thread class?

Answer :

Strategically speaking, threads created by implementing Runnable interface are more advisable. If you create a thread by extending a thread class, you cannot extend any other class. If you create a thread by implementing Runnable interface, you save a space for your class to extend another class now or in future.


Question 18 :

What is NullPointerException and how to handle it?

Answer :


When an object is not initialized, the default value is null. When the following things happen, the NullPointerException is thrown:
Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of a null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.
The NullPointerException is a runtime exception. The best practice is to catch such exception even if it is not required by language design.


Question 19 :

An application needs to load a library before it starts to run, how to code?

Answer :

One option is to use a static block to load a library before anything is called. For example,

class Test { 
	static {
		System.loadLibrary("path-to-library-file");
	}
	....
}

When you call new Test(), the static block will be called first before any initialization happens. Note that the static block position may matter.


Question 20 :

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);