What will be the output of the following piece of code:
class Person{
public void talk() {}
}
public class Test{
public static void main(String args[]){
Person p = null;
try{
p.talk();
}
catch(NullPointerException e){
System.out.print("There is a NullPointerException. ");
}
catch(Exception e){
System.out.print("There is an Exception. ");
}
System.out.print("Everything went fine. ");
}
}
class Person{
public void talk() {}
}
public class Test{
public static void main(String args[]){
Person p = null;
try{
p.talk();
}
catch(NullPointerException e){
System.out.print("There is a NullPointerException. ");
}
catch(Exception e){
System.out.print("There is an Exception. ");
}
System.out.print("Everything went fine. ");
}
}
A. There is a NullPointerException. Everything went fine.
B. There is a NullPointerException.
C. There is a NullPointerException. There is an Exception.
D. This code will not compile, because in Java there are no pointers.
Answer: Option A
Person p is not been initialized. So it will throw NullPointerException when talk() method is tried to access.
when there is no exception than why it is printing null pointer exception