Hello,

I am in learning java. I try this code that I got from internet :

static void insertionSort(int[] A) {
      // Sort the array A into increasing order.

   int itemsSorted; // Number of items that have been sorted so far.

   for (itemsSorted = 1; itemsSorted < A.length; itemsSorted++) {
         // Assume that items A[0], A[1], ... A[itemsSorted-1] 
         // have already been sorted.  Insert A[itemsSorted]
         // into the sorted part of the list.

      int temp = A[itemsSorted];  // The item to be inserted.
      int loc = itemsSorted - 1;  // Start at end of list.

      while (loc >= 0 && A[loc] > temp) {
         A[loc + 1] = A[loc]; // Bump item from A[loc] up to loc+1.
         loc = loc - 1;       // Go on to next location.
      }

      A[loc + 1] = temp; // Put temp in last vacated space.
   }
}

I want to try this to print the result, so I modify this code to :

public class InsertionSort {

    public static void main(String[] args) {
        int[] A = {2, 7, 1, 9, 5, 12, 3};
        insertionSort(A);
    }

    static void insertionSort(int[] A) {
          // Sort the array A into increasing order.

       int itemsSorted; // Number of items that have been sorted so far.

       for (itemsSorted = 1; itemsSorted < A.length; itemsSorted++) {
             // Assume that items A[0], A[1], ... A[itemsSorted-1] 
             // have already been sorted.  Insert A[itemsSorted]
             // into the sorted part of the list.

          int temp = A[itemsSorted];  // The item to be inserted.
          int loc = itemsSorted - 1;  // Start at end of list.

          while (loc >= 0 && A[loc] > temp) {
             A[loc + 1] = A[loc]; // Bump item from A[loc] up to loc+1.
             loc = loc - 1;       // Go on to next location.

          }

          A[loc + 1] = temp; // Put temp in last vacated space.

       }

          for (int i=0; i <= A.length; i++){           
              TextIO.putln(A[i]);
          }
    }

}

But, it was give me this :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at InsertionSort.insertionSort(InsertionSort.java:33)
at InsertionSort.main(InsertionSort.java:6)
1
2
3
5
7
9
12

What is the mean of this error notification ?

exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at InsertionSort.insertionSort(InsertionSort.java:33)
at InsertionSort.main(InsertionSort.java:6)

Thank you

Dani AI

Generated

The exception means the program tried to access an array slot that does not exist. For an array of seven elements the valid indices are 0 through 6; an attempt to read index 7 triggers an ArrayIndexOutOfBoundsException. As pointed out, the printing loop used an off‑by‑one condition, so the code reached an illegal index after printing the valid elements.

That also explains why the sorted numbers appear in the output before the crash: the loop printed A[0]..A[6] successfully, then the next iteration attempted the invalid access and the JVM threw the exception. Console output can look odd because standard output (stdout) is buffered while the stack trace is written to standard error (stderr), so ordering between the two streams can appear swapped.

Two simple, safer ways to print the final array without risking an off‑by‑one error:

import java.util.Arrays;
System.out.println(Arrays.toString(A));

or

for (int v : A) {
    System.out.println(v);
}

A few practical tips for learning and debugging: prefer the enhanced for loop or library helpers when the index is not required; use an IDE debugger or temporary print statements inside the outer loop to watch insertion sort progress; add simple assertions or checks if unsure about bounds. Note that TextIO.putln seen in the thread is not part of core Java libraries; standard practice is to use System.out.println for simple output. Thanks to for the pointer and to for the example that made the problem easy to spot.

Recommended Answers

All 2 Replies

Remember that Java like C uses "zero based" arrays. That means that if an array has 7 elements, it's indices go from 0 to 6. With i<=A.length, you're setting i to 0 through 7. But A[7] doesn't exist. Hence the out of bounds exception.

            //Change i<=A.length to i<A.length
            for (int i=0; i < A.length; i++){
                  TextIO.putln(A[i]);
            }

Ah, thank you very much.

I am really sorry. I am never learn C. I am just learn from internet :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.