Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Exception in thread "main" java.lang.NullPointerException  RSS feed

 
Gulshan Singh
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I'm very new to Java but not new to programming. I have this code that gives me an exception:

Exception in thread "main" java.lang.NullPointerException
at battleship.Battleship.main(Battleship.java:10)

Here's the code:

What's wrong? This is my first program in Java so it's probably something simple...
 
Henry Wong
author
Sheriff
Posts: 22843
119
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This....



Declares a reference to and instantiates a Ship *array* of size three. It doesn't actually instantiates the Ships -- you still need to do that.

Henry
 
Brian Legg
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct me if I'm wrong but won't the line "ship[i].placeShip(); " also throw an error for accessing a non-static method of a different class from a static context? You'd either have to make placeShip() a static method or fully qualify the call with the class name.
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brian Legg wrote:Correct me if I'm wrong but won't the line "ship[i].placeShip(); " also throw an error for accessing a non-static method of a different class from a static context? You'd either have to make placeShip() a static method or fully qualify the call with the class name.

You're wrong, so here's the correction

ship[i] is a reference to a Ship object, so you can call its instance methods on it. However, as Henry already said, the reference is still null and that's causing the problem.
 
Brian Legg
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob. I always get mixed up with that stuff..... that's why I never code anything in main() at all.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!