Search code examples
javanullpointerexceptionhashmapbluej

Java HashMap class throws a NullPointerException


I am using BlueJ and testing the HashMap class to see how it works. Below is the code I used to test the class. There is an error that is thrown in line 23, during the first attempt to call the fillMyMap() method in the constructor.

I tried deleting the call to fillMyMap() in the constructor. The HashMapTester object is instantiated, but the same NullPointerException is thrown when I call that method explicitly.

I tried rewriting the myMap variable declaration, but using a different syntax results in a failure to compile.

I've tested other HashMap code (e.g., from Objects First with BlueJ), and that code runs fine, so there is not a Library, class, or package problem.

I tried changing the variables, thinking I accidentally hit a reserved word. The same result. What is wrong with this code?

import java.util.HashMap;

public class HashMapTester
{
    //Fields
    public HashMap<String, String> myMap;

    // The constructor is supposed to construct a new
    // HashMap object with variable name myMap.
    // The fillMyMap() method call simply fills the HashMap
    // with data prior to testing it.
    public HashMapTester()
    {
        HashMap<String, String> myMap = new HashMap<String, String>();
        fillMyMap();
    }

    // fillMyMap() methods is supposed to fill up 
    // the keys and values of the HashMap<String, String> 
    // object.
    public void fillMyMap()
    {
        myMap.put("doe", "A deer...a female deer."); //<-- ERROR OCCURS HERE!
        myMap.put("ray", "A drop of golden sun.");
        myMap.put("me", "A name I call myself.");
        myMap.put("fah", "A long, long way to run.");
        myMap.put("sew", "A needle sewing thread.");
        myMap.put("la", "A note to follow sew.");
        myMap.put("tea", "It goes with jam and bread.");
    }

    public String sing(String note)
    {
        String song = myMap.get(note);    
        return song;
    }
}

Solution

  • HashMap<String, String> myMap = new HashMap<String, String>();
    

    Is declaring a local variable in the constructor, not instantiating the field variable.

    Use

    this.myMap = new HashMap<String, String>();