0
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(Interview.java:41)
at com.assignment.Interview.main(Interview.java:57)

5 Answers 5

3

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

private HashMap<String,String> stateNames = new HashMap<String,String>();
Sign up to request clarification or add additional context in comments.

Comments

3

You forgot to initialize your HashMap, change:

private HashMap<String,String> stateNames;

to:

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

Comments

2

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<>();
}

Comments

2

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>()

Comments

2

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<>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.