0

I haven't used Java in a while so I'm rusty. I have a method that returns an array of objects. In my main, I created a new object array and set that new array of objects to the return array of the method. Something like this:

Obj[] main_arr = new Obj[100];
main_arr = method(x);

for (int i = 0; i < main_arr.length; i ++){
  if(main_arr[i].number == 1) {  // the error seems to be here
      // do some stuff
  }
  else {
      // do some stuff
  }

}

I am trying to loop through main_arr and access the things in this object array, however I get a Null Pointer Exception. I've been in the debugger tool and main_arr seems to have the correct content. Any ideas why? Thank you in advance!

Hai Le
  • 25
  • 6

3 Answers3

1

Some elements of main_arr are null.

This could happen, for example, if main_arr has 100 elements but only the first 10 were actually assigned a value.

cybersam
  • 63,203
  • 6
  • 53
  • 76
0

It's main_arr.length() not main_arr.length

0

Java Array Object does not have a method to get its length. Youneed to use the ‘array length attribute’, like this:

int arrayLength = myArray.length;
for (int i = 0; i <= arrayLength - 1; i++) {

   if (myArray[i] == whatever) {
      //do some job
   }
}

Credits: https://www.edureka.co/blog/array-length-in-java/

Misho73bg
  • 38
  • 2
  • 4