File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception in thread "main" java.lang.NullPointerException

 
Gulshan Singh
Ranch Hand
Posts: 41
  • 0
  • 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
Marshal
Pie
Posts: 20833
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • 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
  • 0
  • 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
Pie
Posts: 20372
44
Chrome Eclipse IDE Java Windows
  • 0
  • 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
  • 0
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic