package javaapplication4;
import java.util.*;
public class Practice {
public static void main (String[] args){
int[] a = {12,1,12,3,12,1,1,2,3,3};
int len = a.length;
int[] b = new int[len];
int c;
int d;
for (c=0;c<len;c++){
d=a[c];
System.out.println(d);
System.out.println(b[d]);
}
}
}
Asked
Active
Viewed 37 times
-1

Andy Turner
- 137,514
- 11
- 162
- 243

Abhilash Chauhan
- 11
- 2
- 3
-
Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/q/5554734/3788176). – Andy Turner Jun 30 '16 at 13:50
4 Answers
2
Error: b[d]
when d
is equal to a[0]
, i.e 12
b[12]
throws an ArrayIndexOutOfBoundsException

Jean Logeart
- 52,687
- 11
- 83
- 118
0
int[] a = {12,1,12,3,12,1,1,2,3,3};
^--- "d" on you first loop iteration
System.out.println(b[12]);
^---"d" on the first loop iteration
You don't have 12 elements in your array, you're accessing beyond the end of the array.

Marc B
- 356,200
- 43
- 426
- 500
0
Array index starts from 0. So the last element always has an index of length-of-the-array - 1.
Why is this question tagged C
?

babon
- 3,615
- 2
- 20
- 20
0
This array
int[] a = {12,1,12,3,12,1,1,2,3,3};
has only 10 elements.
The array b
defined the following way
int len = a.length;
int[] b = new int[len];
also has only 10 elements.
In this statement
System.out.println(b[d]);
you are using the values of elements of the array a
as indices for the array b
. And it is evident that for example value 12
is greater than the number of elements in b
.

Vlad from Moscow
- 301,070
- 26
- 186
- 335