2

My program is throwing a NullPointerException. I suspect Calling the instance method of a null object is the reason for it throwing a null pointer exception.

Can anyone explain what does this actually mean?

Nishant
  • 49,257
  • 12
  • 102
  • 116
tin_tin
  • 418
  • 2
  • 10
  • 20

3 Answers3

12

It means you have code that looks like this:

foo.method();

...and foo is null. foo has to refer to an object instance in order for you to call methods or access fields on it. E.g., you must assign something to foo (something other than null) like foo = new Foo(); or such.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
1

There are two types of methods in Java: static and instance. A static method can be invoked WITHOUT an instance of the class, an instance method MUST be invoked on an instance of the class. Static methods cannot invoke instance methods or use instance data, but the reverse is not true — instance methods can invoke static methods and use static data.

The null pointer exception (NPE) you're seeing is because you're invoking an instance method on a null reference. You need to set the reference to an actual object of that class (or a subclass of it).

Interestingly enough, though, it's quite legal to invoke a static method on a null reference. It's very odd syntax and somewhat misleading, but it will work.

Eric Giguere
  • 3,435
  • 13
  • 11
0

You called a method on an object which you did not initialize. For exemple your code has a line such as :

myObject.callMethod();

But this "myObject" has not been initialized with a line like :

myObject = new myObjectClass();

Please post some code if you want a more in-context answer !

Dunaril
  • 2,607
  • 5
  • 27
  • 53