Null Pointer Exception on Object Array

  • B/c its iterator variable is local to the loop.
  • On each iteration the iterator is assigned w/ 1 of the array’s indices.
  • Assigning something else to the iterator won’t affect the array’s content.
  • Here’s an example similar to what happens to an enhanced loop iteration:
final PVector[] vecs = new PVector[5]; // 5 indices (0 to 4)
println(vecs); // starts off all null

PVector vec = vecs[0]; // local variable vec equals to null
vec = PVector.random3D(this); // reassigning w/ another value won't affect vecs[0]
println(vecs[0]); // vecs[0] is still null

vecs[0] = PVector.random3D(this); // direct assignement to index 0
println(vecs[0]); // now vecs[0] is initialized w/ a PVector object

exit();
3 Likes