Java - Interview Questions and Answers on Null

Q1.  Difference between HashMap and Hashtable?

Ans. Hashtable is synchronized whereas HashMap is not.

HashMap allows null values whereas Hashtable doesn’t allow null values.

Q2.  Can we create a null as a key for a map collection ?

Ans. Yes , for Hashtable. Hashtable implements Map interface.

Q3.  How would you go about debugging a NullPointerException?

Ans. Open ended Question.

Q4.  What will be the output of following code ?

public static void main(String[] args){
String name = null;
File file = new File("/folder", name);
System.out.print(file.exists());
}

Ans. NullPointerException at line: 

"File file = new File("/folder", name);"

Q5.  What will be the output of following code ?

public static void main(String[] args){
String child = null;
File file = new File("/folder", child);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Ans. NullPointerException at line:

File file = new File("/folder", child);

Q6.  Can we have null keys in TreeMap ?

Ans. No, results in exception.

Q7.  Can value be null in TreeMap ?

Ans. Yes.