[SOLVED] Java Class Property (Null Pointer?) Explanation?

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

[SOLVED] Java Class Property (Null Pointer?) Explanation?

Post by Chris Corbyn »

Just playing around with GCJ outside of an IDE at the moment but why does this happen?

Code: Select all

/**
 * Main Entry point for Application
 */
class App
{
	/**
	 * Static method main() excuted when app starts
	 * @param String arguments
	 */
	public static void main(String[] args)
	{
		Zoo myZoo = new Zoo("Chester");
		for (int i = 0; i < args.length; i++)
		{
			myZoo.addAnimal(new Animal(args[i]));
		}
	}
}

/**
 * Zoo class
 * Stores animals
 */
class Zoo
{
	/**
	 * The name of this Zoo
	 */
	private String name;
	/**
	 * A container for animals in this Zoo
	 */
	private Animal[] animals;
	
	/**
	 * Constructor
	 * @param String name
	 */
	public Zoo(String myName)
	{
		name = myName;
	}
	/**
	 * Get the name of this Zoo
	 * @return String
	 */
	public String getName()
	{
		return name;
	}
	/**
	 * Add a new Animal to this Zoo
	 * @param String animal
	 */
	public void addAnimal(Animal animal)
	{
		animals[animals.length] = animal;
	}
}

/**
 * An animal which lives in the Zoo
 */
class Animal
{
	/**
	 * The name of the animal
	 */
	private String name;
	
	/**
	 * Constructor
	 * @param String name
	 */
	public Animal(String itsName)
	{
		name = itsName;
	}
}
When I run it this happens. Am I accessing the "animals" variable correctly or is it not an array or something?

Code: Select all

[d11wtq@pc-cac Zoo]$ ./runme Monkey Elephant
Exception in thread "main" java.lang.NullPointerException
   at Zoo.addAnimal(runme)
   at App.main(runme)
EDIT | Refactored code and ammended above but same error.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Used java.util.ArrayList instead. Works nicely.
Post Reply