Which is the Best Java Web Framework ?

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.



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus




×

Try our new Java Interview Questions Search Tool.

There are more than 1000 questions with practice tests.

It's updated daily and It's Awesome.


×

Try our new Java Practice Test tool.

There are more than 200 questions and expanding quickly. It's updated daily and It's Awesome.