How to run half element of array length

i have 50 images and i want to run sequential each image in my folder and what i am trying to do is that i am creating an array of 100 images.but i have only 50 image and other 50 images Add in a sequence when program is running and.

i want auto running array which read value if value is available .
just like if array running 50 images if it encounter 51 image then it should be run in next loop.each time i want to do that.
and when i trying to do that i get NullPinterException. so tell me what should i do.

int maxImages = 100;
PImage[] images = new PImage[maxImages];

  for (int  j = images.length-1; j >= 0; j-- ) {
    
    if(images[j] == null)
    {
      maxImages++ ;
    }
   
   
   images[j] = loadImage( "img"+j+".png" );
frameRate(1);
}
}
// Discourse.Processing.org/t/how-to-run-half-element-of-array-length/12439/2
// GoToLoop (2019/Jul/02)

static final String NAME = "img", EXT = ".png";
static final int IMAGES = 100, PRELOAD = 50;

final PImage[] images = new PImage[IMAGES];
int idx, total = PRELOAD;

void setup() {
  size(1200, 600);
  frameRate(1);

  for (int i = 0; i < PRELOAD; )
    images[i] = loadImage(NAME + i++ + EXT);
}

void draw() {
  background((color) random(#000000));
  set(0, 0, images[idx = (idx + 1) % IMAGES]);

  if (total < IMAGES)
    images[total] = loadImage(NAME + total++ + EXT);
}

Another option is to use an ArrayList, and add newly loaded images to the end of the list. Then looping through the list by its length will never encounter nulls – the list is always as long as its number of entries, and it grows as you add: 51, 52, 53… 99, 100.

https://processing.org/reference/ArrayList.html