user2788945
user2788945

Reputation: 273

ArrayIndexOutOfBound Exception

This is the code where I am getting index out of bound exception and I don't understand why,

 int index = array.length - 1;
 E item = array[index];

  while (item == null && index >= 0) {
  index--;
  item = array[index];
  }

I am getting java.lang.ArrayIndexOutOfBoundsException: -1 at item = array[index]; I don't know where I went wrong. Could anyone please help.

Upvotes: 0

Views: 782

Answers (5)

mosaad
mosaad

Reputation: 2381

This should work

int index = array.length - 1;
 E item = array[index];

  while (item == null && index > 0) {
  index--;
  item = array[index];
  }

Upvotes: 0

josh
josh

Reputation: 23

Your while loop is decrement before using the index as a pointer to the object in the array. This will result in pointing at -1 and will give you the null pointer exception.

Try placing the decrement after item = array[index];

Upvotes: 0

Prateek
Prateek

Reputation: 1926

int index = array.length - 1;
 E item = array[index];

  while (item == null && index >= 0) {
  index--;
  item = array[index];
  }

Here you are first decrementing the index before you access the element at that index. When index = 0 as you first decrement the index it reaches -1 and array[-1] gives you java.lang.ArrayIndexOutOfBoundsException

 int index = array.length - 1;
     E item = array[index];

      while (item == null && index >= 0) {      
      item = array[index];
      index--;
      }

This should work for you.

Upvotes: 0

Thomas
Thomas

Reputation: 12029

In the last loop run index is 0 which is true for the condition. Then you decrement to -1 and try to access the array element at that position.

Upvotes: 0

sandymatt
sandymatt

Reputation: 5612

while (item == null && index >= 0) {
  index--;
  item = array[index];
}

should be

while (item == null && index >= 0) {
  item = array[index--];
}

Upvotes: 1

Related Questions