• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Null Pointer Exception

 
mike hew
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
mike hew
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15219
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic