-2

I want to create an ordered array to study about complexity.I know this a very basic code. I am getting an error saying......

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at myWork.orderedArray.<init>(orderedArray.java:20)
    at myWork.mainClass.main(mainClass.java:6)

my code is

package myWork;

public class orderedArray {

    int j; 



    int arr[]=new int[10];

    orderedArray(int n){
        for(int i=0;i<arr.length;i++){
            arr[i]=0;
        }
        for(int i=0;i<arr.length;i++){
            if(arr[i]<=n){

                for(int j=arr.length;j>i+1;j--){

                    arr[j]=arr[j-1];

                }
                arr[i]=n;
            }
        }
    }

 void dispaly(){
     for(int i=0;i<arr.length;i++){
         System.out.println(arr[i]);
     }
 }





}

and I created an object in main class and just ran the main class which i think its not relevant to the error

package myWork;

public class mainClass {

    public static void main(String[] args) {
    orderedArray obj1= new orderedArray(5);

    }

}

Thank you for your time reading this. Please accept my apoligies if you find some minor mistakes in my English and for the way i putted the code in this question (first time in stackoverflow so i dont know how to put a question with code properly :D)

Jens
  • 67,715
  • 15
  • 98
  • 113
jan
  • 53
  • 6

2 Answers2

1

On the first iteration of:

for(int j=arr.length;j>i+1;j--){

     arr[j]=arr[j-1];

}

You will access arr[arr.length] which is out of bounds. You need to start the cycle from arr.length - 1, to make sure you are never accessing an invalid cycle.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
0

Array index is always starts with zero 0. For e.g. int a[]=new int[10]; means first index is a[0] last index is a[9] not a[10]. Since 0 to 9 there are 10 memory locations which is called array length.
for instance by calling a[10] which is index is out of bounds throws an ArrayoutofboundsException.

In your code you are doing the mistake at these lines

 for(int j=arr.length;j>i+1;j--){
     arr[j]=arr[j-1];
     }

Change arr.length to (arr.length-1) to get rid of exception.
Hope this helps :)

Sagar Pudi
  • 4,634
  • 3
  • 32
  • 51