Java - Interview Questions and Answers on NullPointerException

Q1. What is NullPointerException ?

Ans. The exception which JVM throws if we try to access elements using null object reference.

Q2.  How would you go about debugging a NullPointerException?

Ans. Open ended Question.

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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Ans. NullPointerException at line:

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