java.util.Hashtable’s null pointer exception is occuring in the following code when neither of the arguments to put() are null :
import java.util.Hashtable;
interface action
{
void method();
}
class forclass implements action
{
public void method()
{
System.out.println("for(...){");
}
}
class ifclass implements action
{
public void method()
{
System.out.println("if(..){");
}
}
public class trial
{
static Hashtable<String,action> callfunc;
//a hashtable variable
public static void init()
{
//System.out.println("for"==null); //false
//System.out.println(new forclass() == null); //false
callfunc.put("for",new forclass()); //exception occuring here
callfunc.put("if",new ifclass());
//putting values into the hashtable
}
public static void main(String[] args)
{
init(); //to put stuff into hashtable
action a = callfunc.get("for");
//getting values for specified key in hashtable
a.method();
callfunc.get("if").method();
}
}
Exception in thread “main” java.lang.NullPointerException –
at trial.init(trial.java:33)
at trial.main(trial.java:38)
why is this exception occuring? how do i fix it?
You have not initialized your
Hashtable: –You should rather use
HashMap, which allows1 null key, to avoid gettingNPEwhen usingputwithnull key, method which in case ofHashtablethrowsNPE, because it does not allownull keys, or value.So, change your declaration to: –
or even better: –
As a side note, you should follow
Java Naming Conventionin your code. All the class name and interface name, should start withUpperCaseletter, and followCamelCasingthereafter.