0

My code is as follows:

public class Meh {
    public static void main(String[] args) {
        String entries[] = { "entry1", "entry2" };
        int count = 0;
        while (entries[count++] != null) {
            System.out.println(count);
        }
        System.out.println(count);
    }
}

Why does my code result in an arrayindexoutofboundsexception?

  • `entries[count++] != null` this is always true. – SamHoque Oct 26 '18 at 09:09
  • Take a look at this: https://stackoverflow.com/a/5413593/4187549 – Furkan Kambay Oct 26 '18 at 09:11
  • `ArrayIndexOutOfBoundsException` is thrown when you try to use index which is out of array bounds (<0 OR >=array.length). Since `while (entries[count++] != null)` is always true, after last element you end up with `count` which is 2, and in next iteration test `entries[count++]` is like `entries[2]` which is out of array bounds. – Pshemo Oct 26 '18 at 09:11

1 Answers1

0

I'm guessing you are trying to make a loop, You are trying to read from an index not in bound. so here is the working code

public static void main(String[] args) {
    String entries[] = {"entry1", "entry2"};
    int count = 0;
    while (count < entries.length) {
        System.out.println(entries[count]);
        count++;
    }
    System.out.println(count);
}
SamHoque
  • 2,978
  • 2
  • 13
  • 43