Java Program to Check Array Bounds while Inputing Elements into the Array
Concept: Arrays are static data structures and do not grow automatically with an increasing number of elements. With arrays, it is important to specify the array size at the time of the declaration. In Java, when we try to access an array index beyond the range of the array it throws an ArrayIndexOutOfBounds Exception. An exception is an obstruction to the normal program execution. Java has try-catch-finally blocks for efficient Exception Handling. ArrayIndexOutOfBoundsException is a runtime exception and must be handled carefully to prevent abrupt termination of the program.
- Using try-catch block where input is taken beyond the array index range
- Using try-catch block where input is taken within the array index range
- Using constraints over user input
In the first approach, an array of size = 5 is declared. The input is taken within a try block and the loop is executed 6 times. Since the array size is 5, after the 6th input an ArrayIndexOutOfBoundsException is thrown. The exception is handled by the catch block. The code to handle the exception is placed within the catch block. In this example, we notify the user that an exception has occurred and the input exceeds the array range.
Implementation: In all approaches variable named ‘i’ is used of integer data-type been taken for consideration.
In the second approach, we declare an array of size = 5. The input is taken within a while loop inside a try block. The value of i is checked against the size of the array at every iteration. The value of ‘i’ is initiated with 0 and can take input up to index 4. As soon as the value of ‘i’ reaches 5 an exception is thrown. This exception is handled by the catch block. This method is similar to the first one, however, in this approach, no input is taken beyond the array index range which was not the case in the first approach.
In this approach we do not use the concept of exception handling rather we limit the input using loops. It is an easier and convenient method of checking array bounds while taking inputs from the user.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.