FAQ
Cover
This is the archive Discourse for the Processing (ALPHA) software.
Please visit the new Processing forum for current information.

   Processing 1.0 _ALPHA_
   Discussion
   General Processing Discussion
(Moderators: fry, REAS)
   Null pointer exceptions
« Previous topic | Next topic »

Pages: 1 
   Author  Topic: Null pointer exceptions  (Read 1647 times)
sspboyd


Null pointer exceptions
« on: Apr 24th, 2004, 4:29pm »

Hi
I have a rather basic question. What exactly is a null pointer exception? I am getting one with a function I am working on and since I don't know Java I can't intelligently read much out of the error message that comes up.
 
Where or what are the main causes of null pointer exceptions and how do I debug them?
 
Thanks,
steve
 

gmail.com w/ sspboyd username
TomC

WWW
Re: Null pointer exceptions
« Reply #1 on: Apr 24th, 2004, 5:46pm »

NullPointerExceptions occur when you try to access data or call a method on an object which hasn't been initialised.
 
They most commonly occur in my code where I try and access a member of an array which doesn't exist yet.
 
e.g.
 
Code:

 
// a simple demo class...
class Point {
  float x,y,z;
  Point() {
    x = y = z = 0.0;
  }
  public String toString() {
    return "(" + x + ", " + y + ", " + z + ")";
  }
}
 
void setup() {
  // I want an array of 32 points...
  Point points[] = new Point[32];;
  for (int i = 0; i < points.length; i++) {
    println(points[i]); // exception here, because points[i] doesn't exist yet.
  }
}
 

 
When I run the above, the offending line gets highlighted orange in the processing editor when the exception is thrown.
 
The way to fix that is to initialise each element in the array first...
 
Code:

Point points = new Point[32];
for (int i = 0; i < points.length; i++) {
  points[i] = new Point();
}

 
You can also explicitly check if a variable is null:
 
Code:

if (points[i] == null) {
  println("points " + i + " is null.");
}
else {
  println(points[i]);
}

 
If you get an exception, you can pick apart the error message somewhat...
 
Code:

Error while running applet.
 
java.lang.NullPointerException
  at BApplet.println(BApplet.java:1491)
  at Temporary_4643_2863.setup(Temporary_4643_2863.java:20)
  at BApplet.init(BApplet.java:185)
  etc...

 
BApplet.println(BApplet.java:1491)  means the function where the error occurred was println, in the class BApplet, and it was somewhere near line 1491 in BApplet.java (no use to us at the moment).
 
Temporary_4643_2863.setup is the function which called println (Temporary_4643_2863 is what my class is referred to as internally by Processing).  The error occurred on line 20, which is actually line 19 in the processing editor because the processing environment adds an extra line of Java at the start of the temporary file before compiling it.
 
BApplet.init is the function which called setup.  And so on...
 
Hope that helps.
 
Pages: 1 

« Previous topic | Next topic »