Solving java.lang.ArrayindexOutOfBoundsException: 1 in Java

The error java.lang.ArrayIndexOutOfBoundsException
: 1 means index 1 is invalid and it's out of bound i.e. more than the length of the array. Since array has a zero-based index in Java, this means you are trying to access the second element of an array which only contains one element. The ArrayIndexOutfBoundsException comes when your code, mostly for loop tries to access an invalid index of the array. If you have worked in C, C++ then you will notice this difference between array in C and Java. You simply cannot access invalid array index in Java i.e. indexes which are less than zero and more than the length of the array. ArrayIndexOutOfBounds is also a subclass of IndexOutOfBoundsException which is used to throw error related to invalid index e.g. try to access outside of length in String etc.

How to Loop Through An Array in Java with Example

There are multiple ways to loop over an array in Java e.g. you can use a for loop, an enhanced for loop, a while loop or a do-while loop. Since while and do-while needs a condition to terminate they often depend upon the content of the array e.g. stop when the current element is null or even or odd etc. If you just want to iterate over an array to access each element e.g. loop over an array and print each entry then you should use either for loop or the enhanced for loop. The traditional for loop uses a counter and allows you to iterate until the last element is reached i.e. counter is equal to the length of the array while enhanced for loop maintains that counter internally, allowing you to iterate without worrying about counts. This results in clean code and it also eliminates the possibility of one-off errors. In this article, I'll show you 2 ways to iterate over an array, first by using traditional for loop and second by using enhanced for loop of Java 1.5.

6 example to declare two dimensional array in Java

Declaring a two-dimensional array is interesting in Java as Java programming language provides many ways to declare a 2D array and each way have some special things to learn about. For example, It's possible to create a two-dimensional array in Java without specifying the second dimension, sounds crazy right? but it's possible because two-dimensional array in Java is nothing but an array of array. You can even create a two-dimensional array where each subarray has different length or different type, also known as a heterogeneous array in Java. Some of the ways described here also apply how you to declare one-dimensional array e.g. changing the place of square brackets and it has implication on any other variables declared in the same line.