Java - Interview Questions and Answers on Null

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

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

Q2.  Does SQL allow null values ? Can we use it within Where clause ?

Ans. Yes , we can have null values for columns in SQL. Null value represent that the columns value is unknown or haven't been filled. Yes, We can use it within where clause to get the rows with null values.

Q3.  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);"

Q4.  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) {
e.printStackTrace();
    }
}

Ans. NullPointerException at line:

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

Q5.  Can we have null keys in TreeMap ?

Ans. No, results in exception.

Q7.  Can value be null in TreeMap ?

Ans. Yes.

Q8.  How can we protect an application from throwing a NullPointerException ?

Ans. By having Null Checks.

Q9.  When does an application throw NullPointerException ?

Ans. When it tries to access an object element or method using reference which is actually null.