Array IndexOutofbounds Exception in Java: When we must store values, we should go with variables. But when we require to store some same data type element, then that time we should go with Array.
Issues In Array:
There are so many benefits of using Array in our program, but some drawbacks or issues appear when dealing with that array and the array elements.
We are facing the following issues when we are dealing with an array:
- Arrays are fixed in size, so if we don’t know the required size, then it is a problem.
- If we Assign more size than the requirement, then we waste the memory.
- if we assign a minimum size to an array, it will create a problem.
Exceptions Come in Array:
When you perform some operations in an array, there may be times when you face some exceptions. Here is some exception related to the array
- Array IndexOutofbounds Exception
When Can You Get Array IndexOutofbounds Exception?
- Suppose an Array has size 10, but you want to access the 11th element of an array; in that case, you will get an ArrayIndex Exception.
- Similarly, if you try to access an array element by giving a negative value that time, you can get an ArrayIndex Exception.
How to Handel Array IndexOutofbounds Exception
We Can Handel ArrayIndex Exception in two ways:
- Using the for-each loop
- Using Try-catch
Using the for-each loop:
Without mentioning the size of an array, we can access the elements of a display by using each loop, for example
for(int element : array) { }
Using Try-catch:
As we know, to handle or overcome the exception, there is a concept called TRY CATCH. We can put those statements under the try block, which may generate an exception. In the catch block, we write those statements to handle an exception.
package co.java.exception; public class ArrayIndexException { public static void main(String[] args) { int[] arr=new int[3]; arr[0]=10; arr[1]=20; arr[2]=30; arr[3]=40; // Here You Get The exception for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } } }