Java - Exceptions - Interview Questions and Answers on NullPointerException

Q1.  How would you go about debugging a NullPointerException?

Ans. Identify the line that's throwing the exception. Evaluate the nested object references individually to find which is currently null and hence throwing NullPointerException.

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

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

Q4.  Can we have null keys in TreeMap ?

Ans. No, results in NullPointerException.

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

Ans. By having Null Checks.

Q6.  When does an application throw NullPointerException ?

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