Give an example of a Java code fragment that performs an array reference that is possibly out of bounds, and if it is out of bounds, the program catches that exception and prints the following error message: “Don’t try buffer overflow attacks in Java!”
package java_problems_datastructures;
public class ReverseAnArray {
// initialize array
static int[] arrayOfIntegers = { 2, 5, 8, 56, 23, 9, 11 };
// Driver method
public static void main(String args[]) {
// call the method
reverseArray(arrayOfIntegers);
}
public static void reverseArray(int[] arr) {
// Print the array as it is
System.out.println("Array before reverse operation : ");
// in the below line I change it from '<' to '<=' it will throw
// IndexOutOfBoundsException
// because .length gives the length of array, but last index in array is length-1, so it will
// throw an error
// We will put in try box and catch the exception
try {
for (int i = 0; i <= arrayOfIntegers.length; i++) {
System.out.print(arrayOfIntegers[i] + " ");
}
} catch (IndexOutOfBoundsException e) {
// we will print our custom exception message
throw new IndexOutOfBoundsException("Don’t try buffer overflow attacks in Java!");
}
// Print the array reading from last index first
System.out.println(" \nArray after reverse operation : ");
for (int i = arrayOfIntegers.length - 1; i >= 0; i--) {
System.out.print(arrayOfIntegers[i] + " ");
}
}
}
Output:
Array before reverse operation :
2 5 8 56 23 9 11 Exception in thread "main" java.lang.IndexOutOfBoundsException: Don’t try buffer overflow attacks in Java!
at java_problems_datastructures.ReverseAnArray.reverseArray(ReverseAnArray.java:30)
at java_problems_datastructures.ReverseAnArray.main(ReverseAnArray.java:11)