shrewquest
shrewquest

Reputation: 561

NullPointerException when putting a non-null key and value into a Hashtable

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?

Upvotes: 3

Views: 11151

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213311

You have not initialized your Hashtable: -

static Hashtable<String,action> callfunc; // Reference points to null

when neither of the arguments to put() are null

You should rather use HashMap, which allows 1 null key, to avoid getting NPE when using put with null key, method which in case of Hashtable throws NPE, because it does not allow null keys, or value.

So, change your declaration to: -

static Hashtable<String,action> callfunc = new Hashtable<String, action>();

or even better: -

static Map<String, action> callfunc = new HashMap<String, action>();

As a side note, you should follow Java Naming Convention in your code. All the class name and interface name, should start with UpperCase letter, and follow CamelCasing thereafter.

Upvotes: 6

RNJ
RNJ

Reputation: 15552

callfunc reference is null not the inputs.

Try this:

static Hashtable<String,action> callfunc = new Hashtable<String,action>()

Also this post might be useful as to whether you want Hashtable or HashMap

Upvotes: 1

Related Questions