We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › NullPointerException
Page Index Toggle Pages: 1
NullPointerException (Read 460 times)
NullPointerException
May 18th, 2008, 5:07pm
 

Why does this error occurs?
Re: NullPointerException
Reply #1 - May 18th, 2008, 6:19pm
 
You get it when you try to access an object that doesn't yet exist. e.g.
Code:
String s;
int i=s.length(); // null pointer exception


In the above example, s has only been defined, not created. You've said s is going to be a String, but not made an actual String for s to point to.
Re: NullPointerException
Reply #2 - May 21st, 2008, 12:22pm
 
One common mistake is when you have an array of objects, you need to initialize the array AND loop through all the objects and initialize each element.

e.g.

AnyClass[] myArray;  // I want an array called myArray, and it will contain elements of type AnyClass

println(myArray[1].anyProperty); // this will give null pointer exception because myArray has not been created yet.

myArray = new AnyClass[100]; // now the myArray array has been created: enough memory to store 100x AnyClass instances has been allocated
// BUT still myArray[1].anyProperty will give null pointer exception because that instance of AnyClass as not been created

// so we need to loop through the array, and create an instance of AnyClass 100 times
for(int i=0; i<100; i++) myArray[i] = new AnyClass();

// now we can use myArray[...]

Page Index Toggle Pages: 1