• Post Reply Bookmark Topic Watch Topic
  • New Topic

Null pointer exception  RSS feed

 
mike Vigor
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So I'm having a null pointer exception although I can't tell why..

I have a class sector like this


and a constructor which calls on sector like so..I will post only the part of the constructor of interests...


line 21 , that is sectors.add(h) ..is giving me a null pointer exception? why should that be so? the object has been declared and brought to life by "new", I guess is it existing ... or may be not? possible solution?
 
Carey Brown
Saloon Keeper
Posts: 3310
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reference "sectors" is null.

When you have

and it throws a null pointer exception, it is always someReference that is the problem.
 
Fred Kleinschmidt
Bartender
Posts: 571
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the object has been declared and brought to life by "new"

As Carey stated, "sectors" is the problem. Look closely at your code. What is the name of your new Sector variable? Is it "sectors"?
 
mike Vigor
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you all very much...those explanations solved it..
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Carey Brown wrote:. . . When you have

and it throws a null pointer exception, it is always someReference that is the problem.
Nearly always. There are some methods, e.g. most methods of a String, which are programmed not to accept nulls, and they will throw the same Exception if you pass null as an argument.
 
Dave Tolls
Ranch Foreman
Posts: 3056
37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'll get a different stack trace in that case, won't you?
Something from inside String, rather than inside your own class.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you would. Of course if you haven't noticed this:-
The API documentation for String wrote: Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.
. . . you might not understand the stack trace.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!