13,259,976 members (49,720 online)
Rate this:
See more:
I want to sort array elements in ascending order.Following is my java code, i cannot understand the error"Exception in thread main java.lang.ArrayIndexOutOfBoundsException: 12 at Sort_array.main(Sort_array.java:20)"

What I have tried:

import java.math.*;
class Sort_array
{
public static void main(String args[])
{
int arr[] = new int[12];
int i=0,j = 0,temp;
System.out.print("The actual array is ");
for(i=0;i<10;i++)
{
arr[i] = (int)(Math.random()*100);
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.print("Sorted array is ");
for(i=0;i<=arr.length;i++)
{
for(j=i+1;j<=arr.length;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}

for(i=0;i<10;i++)
System.out.print(arr[i]+" ");
}
}
Posted 12-Aug-17 10:45am
Updated 12-Aug-17 15:44pm

Rate this:

## Solution 1

Array is zero based so an array of dimensions 12 is indexed from 0 to 11, your for loop condition tests against the array length which is 12 elements so loops 0 to 12, you need it to be array length -1.

`for(i=0;i<= arr.length - 1;i++)`
Rate this:

## Solution 2

Java is zero based, which that an array of length 12 have elements from 0 to 11.
The right code is
`for(i=0;i<arr.length;i++)`

Another problem is that `arr` have 12 elements, but you fill only 10 of them.

There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.

Top Experts
Last 24hrsThis month
 CPallini 95 Peter Leow 95 F-ES Sitecore 90 Jochen Arndt 85 RDBurmon 59
 OriginalGriff 4,324 Karthik Bangalore 2,276 ppolymorphe 1,794 Dave Kreskowiak 1,624 CPallini 1,545