• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Null Pointer Exception

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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

 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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;
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic