1

I am an absolute beginner to Java. Recently i started to write a code in Java to sort the 5 elements of an array. The user will input the array elements. It complies the code and runs the program. but as soon as i finish inputting the array elemts, the program crashes! Here is my code:

import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int[] arr;
        arr = new int[5];
        System.out.println("Enter the 5 elemnts in the array");
        for(int i=0; i<5; i++)
            arr[i] = in.nextInt();
        int temp;
        for(int i=0; i<5; i++)
        {
            temp = arr[i+1];
            for(int j=i+1; j>=0; j--)
            {
                if(arr[i] > temp)
                {
                    arr[j] = temp;
                    arr[i] = arr[j];
                }
            }
        }       
    }
}

it throws an error which is something like: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Main.main(Main.java:16) i just cannot read and understand the error!

3
  • 5
    Did you look at the documentation for ArrayIndexOutOfBoundsException? I suggest you do that, and read the arrays tutorial. Next, think about the value of i+1 across all the values of i that you'll be using... Commented Aug 28, 2014 at 20:11
  • 1
    Thanks, I found it useful :) Commented Aug 28, 2014 at 20:12
  • 1
    I'd also get used to reading the error. It seems overwhelming at first, but it should tell you exactly what you need to do. The phrase Main.Java:16 tells you the line the error is on, and the name of the exception, ArrayIndexOutOfBounds tells you that the number in the array that you're trying to access doesn't exist. Commented Aug 28, 2014 at 20:17

2 Answers 2

4

Here is the error:

for(int i=0; i<5; i++) {
    temp = arr[i+1];
    //         ^^^
    //   Right here!
    ...
}

when i is equal to 4, i+1 is 5, which is past the end of the array.

This kind of error is so common that it has its own name: it is called Off By One Error. When you see ArrayIndexOutOfBoundsException in a loop, the first thing you look for is this sort of error.

Sign up to request clarification or add additional context in comments.

Comments

2

Your array has a length of 5, indexes start at 0. That means your maximum index is 4 but you try to access your array with the index 5 in your for loop:

 temp = arr[i+1];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.