wood burning stoves*
The moose likes Java in General and the fly likes Null Pointer Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Null Pointer Exception" Watch "Null Pointer Exception" New topic
Author

Null Pointer Exception

mike hew
Greenhorn

Joined: Oct 26, 2006
Posts: 27
This is what I'm getting and don't understand why.

Can anyone explain why I would? Thank you in advance.

Exception in thread "main" java.lang.NullPointerException
at ShapeTest.loadShapesArray(ShapeTest.java:115)
at ShapeTest.main(ShapeTest.java:20)

line 20 and 115 are in the bold

Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

The array variables "shape" (and "shapes") are both null; I don't see any attempt to create a Shape[] object for them to refer to. When you try to access shape[index], you'll get a NullPointerException.


[Jess in Action][AskingGoodQuestions]
mike hew
Greenhorn

Joined: Oct 26, 2006
Posts: 27
so, probally this is the cause then?

//CREATE the instance variable shapes, an array of Shape objects,
//with myFile.getCountOfRecords() elements

Shape[] shape = shapes;
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

You have a private static variable named 'shapes' at the top of your class that you don't set to a specific value - so it's initialized to null.

In your method loadShapesArray() you do this:

Shape[] shape = shapes;

But since 'shapes' is null, you are just making 'shape' null also. Therefore this line:

shape[index] = (Shape) new Circle(Integer.parseInt(myFields[c_xCoordinateField])

produces a NullPointerException. You have to initialize the array itself somewhere, by doing something like this:

Shape[] shape = new Shape[10];

That makes an array that can hold 10 Shape objects. For more information on how arrays work, see The Java Tutorial: Arrays.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Null Pointer Exception
 
Similar Threads
enhanced for loop hangup?
Where am I getting this from?
constructor
the instance variable shapes
lost n confussed