Getting null pointer exception error in class using PVector

I don’t understand why I’m getting NPE error. Processing points me to:

  Walker(PVector _location) {
    location.set(_location);
  }

Here is all my code:

PVector location;
PVector velocity;

Walker walker1;

void setup() {
  location = new PVector(random(width), random(height));
  velocity = new PVector(5, 5);
  walker1 = new Walker(location);
  walker1.display();
  size(800, 800);
}

void draw() {
  background(0);
  
  walker1.move(velocity);
}

class Walker {
  PVector location, velocity;

  Walker(PVector _location) {
    location.set(_location);
  }

  void display() {
    stroke(0);
    point(location.x, location.y);
  }
  
  void move(PVector v) {
    location.x = location.x + v.x;
    location.x = location.x + v.x;
  }
}

final PVector location = new PVector(), velocity = new PVector();

That worked, thanks. So what’s the deal here? why use final?

Java’s non-primitive datatypes, like String and PVector, defaults to null when we declare a variable:

So before using a non-primitive variable, for example invoking any of its methods as you did at location.set(_location);, we have to make sure we’ve already initialized it.

That’s why I’ve assigned a PVector to location: final PVector location = new PVector();

Just to make sure those variables can’t be unintentionally re-assigned later on:

Its usage is completely optional, of course.

1 Like