torsdag, maj 25, 2006

NullPointerException in Java



This the same post as below that is in Swedish, but in English instead. I thought I might aswell translate that post in case someone googles on this problem.

I thought I'd share some insights I've made during the time I was making a small app for a class I'm taking at the moment, consering error messages in Java.
Java doesn't always have the best messages (not that any language really does) but this one can be a bit tricky to understand if you are a newbie.

The one I'm talking about is the NullPointerException error. Most newbies have heard people say that Java doesn't have pointers, which makes this one even harder to understand.
Java DOES have pointers, it's just that you don't have to deal with them yourself.

What NullPointerException really means, is that you are trying to use an object, that doesn't exist. You have a reference to null.
That can happen in all sorts of situations (f.ex getText() that returns this if the textbox is empty), but the one that I belive to be the most common is the one I'll talk about in this point.

What it all boils down to, really, is scope. Combine that with an easily made typo and you can find yourself in a real hassle that can be quite painful to debug if you don't understand what this NullPointerException even means.

Look at the following code example:

public class MyClass {
private SecondClass classtwo;

public MyClass() {
// Notice the error on the row below
SecondClass classtwo = new SecondClass();
}

private void Thingy() {
classtwo.changeto(42);
}
}

As you can see, I first declare a reference to an object, that I call classtwo. But I haven't yet made such an object.
The problem comes when I in the constructor, I do it again. But this time I create the object also.
But, because it's made inside a method, the scope of that object is only inside that method.

The Thingy() method later on, only sees the first classtwo reference, which leads to nothing == NullPointerException.
The right way would have been to do 'classtwo = new SecondClass()' in the constructor. Then the both methods would have been talking about the same object.
Another problem could be that I forgot the "new SecondClass()" part, ie. create the object. A class is not an object, and you should never confuse the two.

This is something you should keep in mind. Creating a reference to an object is not the same as creating the object. And you CAN have several objects with the same name. In that case, it's all about scope.
Now mix this with static and non-static methods/variables, and it can be quite cumbersome to grasp when you are new to the object oriented way of thought.

Disclaimer:
English is not my mother-tongue, I have only been programming Java for a month so I am not in any way an expert.
The terminology might be off, I might not even know what the h*ll im talking about. But this might help someone, so why not.

Inga kommentarer: