File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Null Pointer Exception" Watch "Null Pointer Exception" New topic

Null Pointer Exception

mike hew

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(
at ShapeTest.main(

line 20 and 115 are in the bold

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24195

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

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: 15033

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 8 API documentation
I agree. Here's the link:
subject: Null Pointer Exception
It's not a secret anymore!