Common Errors in Array

In this blog, we will discuss some most popular errors that have high occurrence chances while working with arrays, therefore whenever you see them while you are adding your own code, you will figure out the solution for it.

String[] students = new String[3]
students[5] = "xyz";

In the above code snippet, we have created an array with a length of 3, however at some point, we’re trying to access the index of 5. This will generate anΒ ArrayIndexOutOfBoundsException.

So, if you ever see this, it means you’re trying to access an index beyond the length of the array.

Moreover, a similar kind of error manifest can be seen in loops when you’re off by 1.

  String[] students = {"Pablo","John", "Sutton"};
    for (int i =0; i<4;i++){
        System.out.println("Hi " +students[i]);

When our loop iterates 1 too many or 1 too few times, this happens because sometimes we get a little confused with the index starting at 0 and then the condition statement. If you’re over by 1, this will also throw anΒ ArrayIndexOutOfBoundsException.

Rutu Shah