• Post Reply Bookmark Topic Watch Topic
  • New Topic

Null pointer exception  RSS feed

 
Ranch Hand
Posts: 53
  • 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?
 
Saloon Keeper
Posts: 4066
48
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.
 
Bartender
Posts: 600
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: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you all very much...those explanations solved it..
 
Marshal
Posts: 58454
178
  • 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.
 
Rancher
Posts: 3385
38
  • 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: 58454
178
  • 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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!