SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Chapter:
Object-oriented Design
Exercise:
Exercises
Question:14 | ISBN:9781118771334 | Edition: 6

Question

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!”

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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)


 

 

 

0 0

Discussions

Post the discussion to improve the above solution.