File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes nullpointerexception error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "nullpointerexception error" Watch "nullpointerexception error" New topic

nullpointerexception error

Theresa Marlin
Ranch Hand

Joined: Sep 23, 2009
Posts: 49
I had to write a program that created a pantry which was an array of three jams. When I tried to print out my array, I got a nullpointerexception. What is a nullpointer exception? How can they be fixed?

Class 1:

Class 2

Thank you for your help!!!
Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183

first, please always post the exact exception so it's easier to find the piece of code that causes trouble.

I went through it real quick and think that I found the spot.

What you do is create a Jam array as a local variable but don't put any values in it. Hence the value of each index is null which means it has not gotten a reference yet.

Upon invoking a method on a variable that is null, you'll get a big fat nullpointer exception.

What you want to do is make your Jam array an instance variable and pass the values in the constructor.

JDBCSupport - An easy to use, light-weight JDBC framework -
Geoff Prewett

Joined: Dec 22, 2009
Posts: 2
Sebastian's answer looks like the problem, to me, too. Also, I noticed you're assigning things to the 'patry1' local variable in the Pantry constructor. Since you don't do anything with them, I assume that you probably meant them to persist, in which case you would want to assign them to a member variable. Something like:

(the foreach loop iterates over every item in the array. You probably do not want "for (int i = 0; i < 3; i++)" since if you ever change the length of the array your code will break. "for (int i = 0; i < items.length; ++i)" is better, but the foreach loop is more concise.)

The NullPointerException name is a bit confusing, because what most CS people call "pointers", Java usually calls "references". Basically if you try to do anything will a null reference besides checking to see if it's null, you'll get a NullPointerException. Look at the output window and you'll see a stack trace that points you to the exact line that causes the problem.

Learn Java:
I agree. Here's the link:
subject: nullpointerexception error
It's not a secret anymore!