# NullPointerException in java

## Recommended Posts

slackey    100
For Comp Sci class I am creating a prison simulation since we are learning about searches and sorts. I have 3 classes in this project, a Prisoner class, a Prison class, and a driver class with a main method to run the prison. The Prisoner class defines a prisoner, and the Prison class is essentially an ArrayList of prisoners with methods to add, remove, sort, and search through the prisoners. My problem is I keep getting a NullPointerException when I try to add a Prisoner object to the ArrayList in the Prison class. In my Prison class I have the following method:
public boolean addPrisoner(Prisoner p)
{
if(population < capacity)  //checks to make sure there is room in the prison
{
prisoners.add(p);  //prisoners is the ArrayList containing all prisoners
population++;      //population is increased when prisoner is added
return true;
}
else
return false;
}

In the driver program I create a new Prison object, then create a Prisoner object. When I call the addPrisoner method to add the Prisoner to the Prison, I get a NullPointerException and I am not sure why. I'd like to figure out why I am getting this exception so that then I can fix it.

##### Share on other sites
Evil Steve    2017
Try adding some logging statements (System.Out.Println()) to check that prisoners isn't null. Either it or p is null. You have actually allocated prisoners with new, haven't you?

And does ArrayList not have a size() or count() member (It's been ages since I used Java)? That'd mean you can get rid of population.

##### Share on other sites
Toolmaker    967
How hard is this?

public class Prison{	private ArrayList prisoners = new ArrayList();	private int capacity = 0;	public Prison(int c)	{		capacity = c;	}	public boolean addPrisoner(Prisoner p)	{		if(prisoners.size() < capacity)  //checks to make sure there is room in the prison		{			prisoners.add(p);  //prisoners is the ArrayList containing all prisoners			return true;		}		else			return false;	}}

Toolmaker

##### Share on other sites
Zahlman    1682
In Java, variables of object type are effectively pointers, and they get default-initialized to null whenever they actually are default-initialized. Therefore if you declare a class member ArrayList like this:

	private ArrayList prisoners;

Then it is equivalent to

	private ArrayList prisoners = null;

and not to Toolmaker's version.

##### Share on other sites
slackey    100
Ah I see why I was getting the NullPointerException now, and I fixed it. Thanks for all your help!