Null Pointer when subtracting a Vector

Hi, Could anyone tell me why this following code gives me a NullPointerException?

Vector2 e1 = vertices[i];
         
         Vector2 e2 = vertices[i + 1 == vertices.length ? 0 : i + 1];
         
         Vector2 edge = e1.subtract(e2);

Vector2 Constructors and variables

public float x, y;
   public Vector2(float x, float y){
      this.x = x;
      this.y = y;
   }
   
   public Vector2(Vector2 vec){
      this.x = vec.x;
      this.y = vec.y;

   }

Code to subtract vector

public Vector2 subtract(Vector2 vec){
//NullPointerException at this point
      return new Vector2(x - vec.x, y - vec.y);

   }

Have you heard of “debugging?”
If you use an IDE, you can set a breakpoint at the offending source line, start in debugging mode and inspect the values of all live arguments, variables and object fields when execution hits the breakpoint.
And then you’ll find that the argument to the call of Vector2.subtract is null.

Hi, yeah I wasn’t familiar with debugging until I had this problem and learned how to do it in Eclipse, it just took me to the Constructor of the Vector2 class, and then I couldn’t really figure out the issue from there.

You get a Nullpointer, if one of your variables contain a null value and you try to access a method or property on it. So in your case, at least one entry in your vertices array happen to be null.

Go on practicing using the debugger, because this kind of errors can be found easily with it. Hint: you can inspect the contents of variables in the current scope (frame) in a breakpoint, so searching for the origin of the null value should be a piece of cake, when familiar with debugging.

Thanks for the advice! at the break-point instance nothing in my vertices array is equal to null, nor my subtract argument

Edit, never-mind, figured out how to use debugger with loops and yes there is definitely a null value, cheers.