Null pointer exception when trying assign values to hashmap

package com.assignment;

import java.util.ArrayList;
import java.util.HashMap;

public class Interview {

private HashMap<String,Integer> stateCounts = null;
private HashMap<String,String> stateNames;
private ArrayList<InputData> inputList = null;

public void loadStateNames(String stateKey,String stateName)
    stateNames.put(stateKey, stateName);

public static void main(String Args[])
    Interview interview = new Interview();
    interview.loadStateNames("NY", "New York");

When I try to pass to strings to loadStateNames. I get a null pointer exception. Can't figure out whats causing this error.

Exception in thread "main" java.lang.NullPointerException
at com.assignment.Interview.loadStateNames(
at com.assignment.Interview.main(


You are not initializing them. You should do this in the constructor:

public Inteview() {
    stateNames = new HashMap<>();

Also, I doubt you want to give a null reference to stateCounts and inputList. They should also be initialized in the constructor:

public Inteview() {
    stateNames = new HashMap<>();
    stateCounts = new HasMap<>();
    inputList = new ArrayList<>();

You have not initialised the Map ,change it to ::

private HashMap<String,String> stateNames = new HashMap<String,String>();

You forgot to initialize your HashMap, change:

private HashMap<String,String> stateNames;


private HashMap<String,String> stateNames = new HashMap<String,String>();

When you declare a class variable like this:

private HashMap<String,String> stateNames;

or like this:

private HashMap<String,String> stateNames = null;

it is initialized with null.

You cannot add keys/values to it when it is null.

Either initialize it in a constructor or at declaration time.

private HashMap<String,String> stateNames = new HashMap<String,String>()

You should create an instance:

private HashMap<String,String> stateNames = new HashMap<String, String>();

And for others too. BTW use interface in left side for polymorphism and in Java 7+ you don't need provide types in right side:

 private Map<String,String> stateNames = new HashMap<>();

Need Your Help

Launching External Activity In Portrait

android-intent android-activity android-manifest android

I have implemented an application, in which runs in a 50 inch touch display. In my manifest I have declared that the application should run on Reverse Portrait mode. Now My application is using an