File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Null pointer Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Null pointer Exception" Watch "Null pointer Exception" New topic
Author

Null pointer Exception

Stephen Davies
Ranch Hand

Joined: Jul 23, 2008
Posts: 352
As usual, there is probably something most obvious I'm missing, but I cant understand why the following code is throwing a nullPointerException. I ssume it has something to do with the initialization of my Array of feeling objects in the Game Constructor?

Firstly here is my Feeling class:





Following is the Game class which is throwing the null pointer exception:




Ant suggestions?


be a well encapsulated person, don't expose your privates, unless you public void getWife()!
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1763
    
    7

The feelings array you declare and initialize at line 3 of the second code sample does not contain any references to actual Feeling objects yet.
It's basically an array of null references at that point. When at line 9 you start looping over the feelings array and attempt to access the Feeling object refered to at array index 0, there's no actual object there, so as soon as you call the setFeeling() method a NullPointerException will be thrown.
You can solve this by creating a new Feeling object inside the loop, using the default constructor, then calling the setter methods on that object reference and finally shoving the reference into the array at the appropriate index. Alternatively, you could define a constructor for the Feeling class that takes both parameters, so you needn't call the setter methods after object creation.


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Stephen Davies
Ranch Hand

Joined: Jul 23, 2008
Posts: 352
Doh! of course, thanks Jelle. infact in an older version I was working on I had a line similar to that. It now works like a charm. Its always the most obvious things I miss! ops:
 
Don't get me started about those stupid light bulbs.
 
subject: Null pointer Exception