Jamie Strine Jamie Strine - 1 month ago 10
Java Question

Why am I getting a NullPointer Exception with my array?

Can't for the life of me figure out why I'm getting an error here. It lets me put in the input, but then quits out and says theres a NullPointerException at the line that starts with "emp[i].setName".

String dpt, salary, name;
Manager[] emp = new Manager[3];

for (int i=0; i<3; i++)
{
name = JOptionPane.showInputDialog("Enter Name");
emp[i].setName(name);

Answer

When you create an array in Java, all of the elements are nulls (for non-primitive types anyway; ints, for example will just be 0). If you want to create an array with actual objects, you need to create them. One option (and the simplest) is to create them in a loop like this:

String dpt, salary, name;
Manager[] emp = new Manager[3];

for (int i=0; i<emp.length; i++)
{
  emp[i] = new Manager(); // Create the object
  name = JOptionPane.showInputDialog("Enter Name");
  emp[i].setName(name);
}

Also notice that I use emp.length in the for loop instead of just the number 3. This is so that if the size of your manager array changes, you won't end up with ArrayIndexOutOfRangeException (trying to access an element in the array that doesn't exist).

This question has a much more detailed answer that is definitely worth reading.

Comments