Java ArrayIndexOutOfBoundsException is produced when the array elements past a predefined length are accessed. Arrays are estimated at the hour of their confirmation, and they are static in nature. When we define an array, the number of elements is fixed, and it starts at 0. For example, if there are 10 elements, the array recognizes the 10th element as the 11th element because the first element is the 0th element. At first, every programmer thinks that once the program is executed, the output is guaranteed. But there are issues raised by the system which prevents program execution at runtime, and these issues are termed as exceptions. Hence, when this IndexOutOfBoundsException occurs during runtime, it is produced from the RuntimeException class, which in turn is a subclass of the Main Exception class, and all these are derived from the java.lang package.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Constructors are formed when an interface is implemented from ArrayOutOfBoundsException. There are 3 types of ArrayIndexOutOfBoundsException constructors,
Below are examples mentioned:
Creating an ArrayOutOfBoundsException
Code:
public class Main { public static void main (String[] args) { String[] veggies = {"Onion", "Carrot", "Potato", "Tomato", "Cucumber", "Radish"}; for (int i=0; i<=veggies.length; i++) { System.out.print (veggies[i] + " "); } } }
Output:
In the above program, we see that the array called veggies consists of 6 elements. Once the for loop is iterated, it considers the condition I <=veggies.length, which means that the array considers the elements from 0th position until the 6th position and finally, during the last iteration, the value i=6 exceeds the array size, and therefore, the ArrayoutOfBoundsException is implemented.
Accessing ArrayOutOfBoundsException for negative index
Code #1
public class Main { public static void main (String[] args) { Integer[] intArray = {5, 7, 9, 11, 13, 15}; System.out.println ( "First element: " + intArray[0]); System.out.println ( "Last element: " + intArray[-8]); } }
Output:
Here, we first declare an array of integers, and then we look into accessing the individual elements in the array. Once that is done, we try to print out the first element by giving the command intArray[0]. This recognizes the 0th element, which is 5 and hence prints it. On the other hand, we also provide a command to print a negative index as -8. Hence, the system fails to recognize this index, and thus the ArrayOutOfBoundsException is printed in the output.
Code #2
public class MyClass { int x; public MyClass () { x = 5; } public static void main (String[] args) { MyClass myObj = new MyClass (); System.out.println (myObj.x); } }
Output:
Every programmer commits a mistake in implementing the array indices and elements. Because of these reasons, an ArrayIndexOutOfBoundsException has occurred. We can avoid these mistakes by following the steps below.
An enhanced loop iterates on adjoining memory territories like arrays and just gets to the legal indices. From this time forward, when enhanced for loop is implemented, we need not worry over misguided or illegal indices being gotten to.
Code:
class Main { public static void main (String[] args) { String[] fruits = {"Apple", "Mango", "Banana", "Watermelon", "Papaya"}; System.out.println ( ""); for (String strval:fruits) { System.out.print (strval + " "); } } }
Output:
We have used an enhanced for loop in the above program to iterate the array of fruits. First, we describe the 5 elements in the array and then implement the enhanced for loop. This loop iterates till the end of the array is reached, and we need not define each array separately. Thus, it goes over only valid indices or elements and finally provides the exact output of what we are looking for. Hence, we can avoid the ArrayIndexOutOfBoundsException by utilizing this enhanced for loop.
Arrays reliably start with list 0 and not 1. Moreover, the last part in the array can be gotten to using the record ‘arraylength-1’ and not ‘arraylength’. Programming engineers should be mindful while using beyond what many would consider possible and, as such, keep up a key good way from ArrayIndexOutOfBoundsException.
Type-safe iterators do not toss an exception when they emphasise an assortment and make changes to it as they depict the assortment and roll out the improvements to it.
Code:
import java.util.HashMap; public class MyClass { public static void main (String[] args) { HashMap<String, String> countries = new HashMap<String, String> (); countries.put ( "India", "Delhi"); countries.put ( "Switzerland", "Bern"); countries.put ( "France", "Paris"); countries.put ( "Belgium", "Brussels"); System.out.println (countries); } }
Output:
Explanation: In the above program, we declare the string of cities and countries and declare that to the HashMap. The system then recognizes this assortment, iterates the code, and finally produces the output without throwing an ArrayIndexOutOfBoundsException.
The ArrayIndexOutOfBoundsException in Java usually occurs when we try to access the elements which are greater than the array length. These exceptions can be avoided by using enhanced for loops or proper indices. There are also exceptions called NullPointerExceptions that are not checked and go beyond RuntimeException; it does not urge the software engineer to utilize the catch square to deal with it. Therefore, we should keep in mind that we should not go beyond array limits and also avoid NegativeArraySizeException.
The above is the detailed content of Java ArrayIndexOutOfBoundsException. For more information, please follow other related articles on the PHP Chinese website!