aspose file tools*
The moose likes Beginning Java and the fly likes Exception in thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception in thread "main" java.lang.NullPointerException" Watch "Exception in thread "main" java.lang.NullPointerException" New topic
Author

Exception in thread "main" java.lang.NullPointerException

Gulshan Singh
Ranch Hand

Joined: Apr 22, 2009
Posts: 41
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

Joined: Sep 28, 2004
Posts: 18896
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Brian Legg
Ranch Hand

Joined: Nov 07, 2008
Posts: 488
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.


SCJA
~Currently preparing for SCJP6
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Brian Legg
Ranch Hand

Joined: Nov 07, 2008
Posts: 488
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.
 
subject: Exception in thread "main" java.lang.NullPointerException