What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
Your first port of call should be the documentation which explains it reasonably clearly:
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
So for example:
int[] array = new int[5];
int boom = array[10]; // Throws the exception
As for how to avoid it... um, don't do that. Be careful with your array indexes.
One problem people sometimes run into is thinking that arrays are 1-indexed, e.g.
int[] array = new int[5];
// ... populate the array here ...
for (int index = 1; index <= array.length; index++)
{
System.out.println(array[index]);
}
That will miss out the first element (index 0) and throw an exception when index is 5. The valid indexes here are 0-4 inclusive. The correct, idiomatic for
statement here would be:
for (int index = 0; index < array.length; index++)
(That's assuming you need the index, of course. If you can use the enhanced for loop instead, do so.)
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException?
What is java.lang.ArrayIndexOutOfBoundsException / java.lang.IndexOutOfBoundsException?
The JavaDoc curtly states:
Thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the
size of the array.
What causes it to happen?
This exception means that you have tried to access an index in an
array or array backed list and that index does not exist.Java uses
0
based indexes. That means all indexes start with0
as
the index of the first element if it contains any elements.
The IndexOutOfBoundsException
message is very explicit, and it usually takes the form of:
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
Where Index
is the index that you requested that does not exist and Size
is the length of the structure you were indexing into.
As you can see a Size: 1
means the only valid index is 0
and you were asking for what was at index 1
.
For example, if you have an raw
Array
of objects or primitive types
the valid indexes are0
to.length - 1
, in the following example the valid indexes would be0, 1, 2, 3,
.
final String days[] { "Sunday", "Monday", "Tuesday" }
System.out.println(days.length); // 3
System.out.println(days[0]); // Sunday
System.out.println(days[1]); // Monday
System.out.println(days[2]); // Tuesday
System.out.println(days[3]); // java.lang.ArrayIndexOutOfBoundsException
This also applies to ArrayList
as well as any other Collection
classes that may be backed by an Array
and allow direct access to the the index.
How to avoid the java.lang.ArrayIndexOutOfBoundsException
/ java.lang.IndexOutOfBoundsException
?
When accessing directly by index:
This uses Guava to convert the raw primitive
int[]
array to anImmutableList<Integer>
. Then it uses theIterables
class to safely
get the value at a particular index and provides a default value when
that index does not exist. Here I chose-1
to indicate an invalid
index value.
final List<Integer> toTen = ImmutableList.copyOf(Ints.asList(ints));
System.out.println(Iterables.get(toTen, 0, -1));
System.out.println(Iterables.get(toTen, 100, -1));
If you can't use Guava for some reason it is easy to roll your own function to do this same thing.
private static <T> T get(@Nonnull final Iterable<T> iterable, final int index, @Nonnull final T missing)
{
if (index < 0) { return missing; }
if (iterable instanceof List)
{
final List<T> l = List.class.cast(iterable);
return l.size() <= index ? l.get(index) : missing;
}
else
{
final Iterator<T> iterator = iterable.iterator();
for (int i = 0; iterator.hasNext(); i++)
{
final T o = iterator.next();
if (i == index) { return o; }
}
return missing;
}
}
When iterating:
Here is the idiomatic ways to iterate over a raw
Array
if you need
to know the index and the value:This is susceptible to one off errors which are the primary causes
of anjava.lang.ArrayIndexOutOfBoundsException
:
Using a traditional for-next loop:
final int ints[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < ints.length; i++)
{
System.out.format("index %d = %d", i, ints[i]);
}
Using an enhanced for-each loop:
Here is the idiomatic way to iterate over a raw
Array
with the
enhanced for loop if you do not need to know the actual index:
for (final int i : ints)
{
System.out.format("%d", i);
System.out.println();
}
Using a type safe Iterator<T>:
Here is the safe way to iterate over a raw
Array
with the enhanced
for loop and track the current index and avoids the possibility of
encountering anjava.lang.ArrayIndexOutOfBoundsException
.This uses Guava to easily convert the
int[]
to somethingIterable
every project should include it.
final Iterator<Integer> it = Ints.asList(ints).iterator();
for (int i = 0; it.hasNext(); i++)
{
System.out.format("index %d = %d", i, it.next());
}
If you can not use Guava or your int[]
is huge you can roll your own ImmutableIntArrayIterator
as such:
public class ImmutableIntArrayIterator implements Iterator<Integer>
{
private final int[] ba;
private int currentIndex;
public ImmutableIntArrayIterator(@Nonnull final int[] ba)
{
this.ba = ba;
if (this.ba.length > 0) { this.currentIndex = 0; }
else { currentIndex = -1; }
}
@Override
public boolean hasNext() { return this.currentIndex >= 0 && this.currentIndex + 1 < this.ba.length; }
@Override
public Integer next()
{
this.currentIndex++;
return this.ba[this.currentIndex];
}
@Override
public void remove() { throw new UnsupportedOperationException(); }
}
And use the same code as you would with Guava.
If you absolutely must have the ordinal of the item the following is the safest way to do it.
// Assume 'los' is a list of Strings
final Iterator<String> it = los.iterator();
for (int i = 0; it.hasNext(); i++)
{
System.out.format("index %d = %s", i, it.next());
}
This technique works for all Iterables. It is not an index parse, but it does give you the current position in the iteration even for things that do not have a native index.
The safest way:
The best way is to always use ImmutableLists/Set/Maps from Guava as
well:
final List<Integer> ili = ImmutableList.copyOf(Ints.asList(ints));
final Iterator<Integer> iit = ili.iterator();
for (int i = 0; iit.hasNext(); i++)
{
System.out.format("index %d = %d", i, iit.next());
}
Summary:
Using raw arrays are difficult to work with and should be avoided in most cases. They are susceptible to sometimes subtle one-off errors which have plague new programmers even back to the days of BASIC
Modern Java idioms use proper type safe collections and avoid using raw array structures if at all possible.
Immutable types are preferred in almost all cases now.
Guava is an indispensable toolkit for modern Java development.
Purposefully avoid ArrayIndexOutOfBoundsException
string.split("\n")
returns a String
array.string.split("\n")[1]
assumes that the return value is an array that has at least two elements.ArrayIndexOutOfBoundsException
indicates that the array has less than two elements.
If you want to prevent getting that exception, you need check the length of the array. Something like...
String[] parts = string.split("\n");
if (parts.length > 1) {
System.out.println(parts[1]);
}
else {
System.out.println("Less than 2 elements.");
}
Exception in thread main java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 0, no idea what does that mean or how to fix it
The
ArrayIndexOutOfBoundsException
is thrown because you defined a 2d array of size[classesCount][0]
.
Since each class has a different size, we should initialize classes after the dynamic input was taken from the user.The code iterates from index 1 and where the array starts from index 0.
Make sure to give meaningful names to the variable (
students
->studentsNum
/studentsCount
and etc').
You can do as follows:
Scanner input = new Scanner(System.in);
System.out.print("Number of classes in the school: "); // Prompt the user to enter the number of classes in the school
int classesCount = input.nextInt();
String[][] studentNamesArr = new String[classesCount][];
for (int classIndex = 0; classIndex < classesCount; classIndex++){
System.out.printf("Enter number of Students in class number %d: ", classIndex+1);
int studentsNum = input.nextInt();
studentNamesArr[classIndex] = new String[studentsNum];
for (int studentIndex = 0; studentIndex < studentsNum; studentIndex++){
System.out.printf("Enter Name for student %d in class number %d: ", studentIndex+1, classIndex+1);
studentNamesArr[classIndex][studentIndex] = input.next();
}
}
System.out.println(Arrays.deepToString(studentNamesArr));
Output:
Number of classes in the school: 2
Enter number of Students in class number 1: 1
Enter Name for student 1 in class number 1: John
Enter number of Students in class number 2: 2
Enter Name for student 1 in class number 2: Wall
Enter Name for student 2 in class number 2: Simba
[[John], [Wall, Simba]]
How can i avoid ArrayIndexOutOfBoundsException in this case?
Maybe I don't understand the real problem, but what prevents you to check if the index is inside the array before accessing it in this case?
if (myIndex < myFirstStringArray.length) {
System.out.println("Present");
} else {
System.out.println("Not Present");
}
While Running Java program getting error java.lang.ArrayIndexOutOfBoundsException
You have to pass arguments to a main()
compile by > javac Insurance.java
run by > java Insurance 50 Male Married
In above case:
args[0] = 50
args[1] = Male
args[2] = Married
If any argument is missing it will throw java.lang.ArrayIndexOutOfBoundsException
. You can check number of arguments like this:
if(args.length == 3) {
//the last argument is null
}
How to solve java.lang.ArrayIndexOutOfBoundsException: 1 in Java jframe?
Let me try to guide you debugging the issue. The exception should give you the line number at which the exception is thrown. ArrayIndexOutOfBoundsException
is thrown when you try to access array with an index that is not available in the array. Given that the error is about index 1, then the error seems to be either at line
array[counter].setSubjectName(inputArray[1]);
or
array[counter] = new Obligations();
after the counter is incremented. Most probably it is the first one, the stack trace should confirm it
Next step of debugging is to figure out the value of the array before the errorneous line. You can print out the value and see whether it is expected value or something else. Alternatively you can debug step-by-step in IDE
If it is not the expected value, backtrack to see how the variable value is calculated.
There are multiple things missing in the question due to which exact answer cannot be provided
array
variable definitioninputArray
variable definition- use of
arrayInside
variable - Line at which the exception is thrown
(Hint: "/t"
is not tab
)
error Exception in thread main java.lang.ArrayIndexOutOfBoundsException in jagged array loop
ArrayIndexOutOfBoundException is thrown when you try to access an element which isn't declared as part of your array. This usually happens when the loops boundary conditions are wrong.
Adding the code which works, please refer to it and check your loop conditions.
package Compilations;
public class JaggedArrLab {
public static void main(String[] args) {
int array[][] = new int [10][];
//initializing rows from 10-1
array [0] = new int [10];
array [1] = new int [9];
array [2] = new int [8];
array [3] = new int [7];
array [4] = new int [6];
array [5] = new int [5];
array [6] = new int [4];
array [7] = new int [3];
array [8] = new int [2];
array [9] = new int [1];
for (int i = 0; i< array.length ; i++){
for (int j=0; j< array.length - i; j++){
array[i][j] = i + j;
}
}
for (int i = 0; i< array.length ;i++){
for (int j=0; j< array.length - i ; j++)
System.out.print(array[i][j] + "\t");
System.out.println();
}
System.out.println();
}
}
Output
0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
3 4 5 6 7 8 9
4 5 6 7 8 9
5 6 7 8 9
6 7 8 9
7 8 9
8 9
9
Related Topics
Calling Awt Frame Methods from Subclass
How to Fix a Nosuchmethoderror
How Are Anonymous Inner Classes Used in Java
What Causes Error "No Enclosing Instance of Type Foo Is Accessible" and How to Fix It
Error - Trustanchors Parameter Must Be Non-Empty
How to Properly Stop the Thread in Java
How to Download Image from Any Web Page in Java
How to Count the Number of Occurrences of a Char in a String
Remove Top-Level Container on Runtime
Failed to Resolve Com.Google.Android.Gms Play-Services-Auth:11.4.0
How to Create a File and Write to It
Cannot Make a Static Reference to the Non-Static Method
Java 256-Bit Aes Password-Based Encryption
Difference Between Matches() and Find() in Java Regex