The error ArrayIndexOutOfBoundsException: 1 means index 1 is invalid and it's out of bounding i.e. more than the length of the array. Since the array has a zero-based index in Java, this means you are trying to access the second element of an array which only contains one element. The ArrayIndexOutfBoundsException comes when your code, mostly for loop tries to access an invalid index of the array. If you have worked in C, C++ then you will notice this difference between array in C and Java. You simply cannot access invalid array index in Java i.e. indexes which are less than zero and more than the length of the array.
ArrayIndexOutOfBounds is also a subclass of IndexOutOfBoundsException which is used to throw an error related to an invalid index e.g. try to access outside of length in String etc.
An array is a data structure that is the base for many advanced data structures e.g. list, hash table or a binary tree. The array stores elements in the contiguous memory location and it can also have multiple dimensions e.g. a two-dimensional array. You can use the 2D array to represent a matrix, a board in games like Tetris, Chess, and other board games.
Also, knowledge of data structure and the algorithm is a must for any good programmer. You can also join these free data structure and algorithms courses to learn more about an array in Java.
Understanding ArrayIndexOutOfBoundsException
This error comes when you are accessing or iterating over an array directly or indirectly. Directly means you are dealing with array type e.g. String[] or main method, or an integer[] you have created in your program. Indirectly means via Collection classes that internally use an array e.g. ArrayList or HashMap.Now let's understand what information the associated error message gives us:
java.lang.ArrayIndexOutOfBoundsException: 0 means you are trying to access index 0 which is invalid, which in turn means the array is empty.
Here is a Java program that reproduces this error by accessing the first element of the empty array i.e. array with zero length:
public class HelloWorldApp { public static void main(String args[]) { // reproducing java.lang.ArrayIndexOutOfBoundsException : 0 error String[] names = new String[0]; String name = names[0]; // this will throw java.lang.ArrayIndexOutOfBoundsException : 0 System.out.println(name); } } Output Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at beginner.HelloWorldApp.main(HelloWorldApp.java:21)
You can see the accessing first element of an empty array resulted in the ArrayIndexOutOfBoundsException in Java.
java.lang.ArrayindexOutOfBoundsException: 1 means index 1 is invalid, which in turn means the array contains just one element. Here is a Java program that will throw this error:
public class HelloWorldApp { public static void main(String args[]) { // reproducing java.lang.ArrayIndexOutOfBoundsException : 1 error String[] languages = {"Java"}; String language = languages[1]; // this will throw java.lang.ArrayIndexOutOfBoundsException : 1 System.out.println(language); } } When you run this program it will throw following error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at beginner.HelloWorldApp.main(HelloWorldApp.java:17)
Similarly, java.lang.ArrayIndexOutOfBoundsException: 2 means index 2 is invalid, which means the array has just 2 elements and you are trying to access the third element of the array.
Sometimes when a programmer makes a switch from C/C++ to Java they forget that Java does the bound checking at runtime, which is a major difference between C++ and Java Array. You should also join these Java Programming and development courses if you are learning Java and knows C++. The author often highlights the key difference between C++ and Java while teaching important concepts.
How to avoid ArrayIndexOutOfBoundsException in Java
In order to avoid the java.lang.ArrayIndexOutOfBoundsException, you should always do the bound check before accessing array element e.g.if (args.length < 2) { System.err.println("Not enough arguments received."); return; }
Always remember that the array index starts at 0 and not 1 and an empty array has no element in it. So accessing the first element will give you the java.lang.ArrayIndexOutOfBoundsException : 0 error in Java.
You should always pay to one-off errors while looping over an array in Java. The programmer often makes mistakes that result in either missing the first or last element of the array by messing 1st element or finishing just before the last element by incorrectly using the <, >, >= or <= operator in for loops.
For example, the following program will never print the last element of the array. The worst part is there won't be any compile-time error or runtime exception. It's a pure logical error that will cause incorrect calculation.
You can see the first element of the array i.e. 2 is never get printed. There is no compile-time or runtime error, though.
Here are few handy tips to avoid ArrayIndexOutOfBoundsException in Java:
And, here is a nice slide of some good tips to avoid ArrayIndexOutOfBondsException in Java:
That's all about how to solve the java.lang.ArrayIndexOutOfBoundsException: 1 in Java. Always remember that the array uses the zero-based index in Java. This means the index of the first element in the array is zero and if an array contains only one element then the array[1] will throw java.lang.ArrayIndexOutOfBoundsException : 1 in Java. Similarly, if you try to access the first element of an empty array in Java, you will get the java.lang.ArrayIndexOutOfBoundsException : 0 error in Java.
Other Java troubleshooting guides for Programmers
/** * Java Program to demonstrate one-off error while looping over array. * * @author WINDOWS 8 * */ public class HelloWorldApp { public static void main(String args[]) { int[] primes = {2, 3, 5, 7, 11, 13, 17}; for(int i = primes.length - 1; i > 0 ; i--){ System.out.println(primes[i]); } } } Output: 17 13 11 7 5 3
You can see the first element of the array i.e. 2 is never get printed. There is no compile-time or runtime error, though.
Here are few handy tips to avoid ArrayIndexOutOfBoundsException in Java:
- Always remember that the array is a zero-based index, the first element is at the 0th index and the last element is at length - 1 index.
- Pay special attention to the start and end conditions of the loop.
- Beware of one-off errors like above.
That's all about how to solve the java.lang.ArrayIndexOutOfBoundsException: 1 in Java. Always remember that the array uses the zero-based index in Java. This means the index of the first element in the array is zero and if an array contains only one element then the array[1] will throw java.lang.ArrayIndexOutOfBoundsException : 1 in Java. Similarly, if you try to access the first element of an empty array in Java, you will get the java.lang.ArrayIndexOutOfBoundsException : 0 error in Java.
Other Java troubleshooting guides for Programmers
- Head First Java, 2nd Edition Error and Exception Chapter (read)
- org.hibernate.MappingException: Unknown entity Exception in Java [solution]
- How to connect to MySQL database from Java Program [steps]
- General Guide to solve java.lang.ClassNotFoundException in Java [guide]
- How to solve java.lang.UnsatisfiedLinkError: no ocijdbc11 in Java [solution]
- 2 ways to solve Unsupported major.minor version 51.0 error in Java [solutions]
- How to fix java.lang.ClassNotFoundException: org.postgresql.Driver error in Java? [solution]
- java.lang.ClassNotFoundException:org.Springframework.Web.Context.ContextLoaderListener [solution]
- java.io.IOException: Map failed and java.lang.OutOfMemoryError: Map failed [fix]
- java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver [solution]
- How to solve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Java MySQL? [solution]
- java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory? [solution]
- java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer (solution)
- java.net.BindException: Cannot assign requested address: JVM_Bind [fix]
- java.net.SocketException: Too many files open java.io.IOException [solution]
- How to solve java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver in Java? [solution]
- How to solve java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver [solution]
- java.net.SocketException: Failed to read from SocketChannel: Connection reset by peer [fix]
- Exception in thread "main" java.lang.ExceptionInInitializerError in Java Program [fix]
- Fixing Unsupported major.minor version 52.0 Error in Java [solution]
Thanks for reading this article so far. If you are getting ArrayIndexOutOfBoundException in your Java Program and not able to solve it then feel free to commit your code and exception here and I can take a look.
8 comments :
i still dont understand where is the solution
Hello Anonymous, the solution depends upon your problem. The articles gives you common reasons of why does ArrayIndexOutOfBoundExeception comes and how to deal with them with additional tips to how to avoid them in first place. If you are getting this error, please post your code and the error message with stacktrace and I can take a look
class CommandlineTenEvenOdd
{
public static void main(String args[])
{
int[] a=new int[10];
for(int i=0;i<10;i++)
{
a[i]=Integer.parseInt(args[i]);
}
System.out.println("Even numbers are: ");
for(int i=0;i<10;i++)
{
if(a[i]%2==0)
{
System.out.println(a[i]);
}
}
System.out.println("Odd numbers are: ");
for(int i=0;i<10;i++)
{
if(a[i]%2!=0)
{
System.out.println(a[i]);
}
}
}
}
O/p:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at CommandlineTenEvenOdd.main(CommandlineTenEvenOdd.java:8)
import java.util.Scanner;
public class array_sum {
public static void main(String args[]) {
Scanner d = new Scanner(System.in);
int a = d.nextInt();
int arr[] = new int[a];
for(int i=0; i<=arr.length; i++ ) {
int arrval = d.nextInt();
arr[i] = arrval;
{
System.out.println("Element at index " + i + " : "+ arr[i]);
}
}
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at array_sum.main(array_sum.java:11)
I'm getting a unhandled error. How do I fix this
Cool bro
class Solution {
public int[][] transpose(int[][] matrix) {
int row=matrix.length,column=matrix[0].length;
int[][] result = new int[column][row];
for(int i=0;i<=row-1;i++)
for(int j=0;j<=column-1;j++)
result[i][j] = matrix[j][i];
return result;
}
}
Thanks very interesting blog!
Post a Comment