Tuesday, February 14, 2017

Solving java.lang.ArrayindexOutOfBoundsException: 1 in Java

The error ArrayIndexOutOfBoundsException: 1 means index 1 is invalid and it's out of bound i.e. more than the length of the array. Since 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 error related to invalid index e.g. try to access outside of length in String etc.

An array is a data structure which is the base for many advanced data structure e.g. list, hash table or a binary tree. The array stores elements in the contiguous memory location and it can also have multiple dimension e.g. a two-dimensional array. You can use the 2D array to represent matrix, a board in games like Tetris, Chess and other board games.

A good knowledge of data structure and the algorithm is a must for any good programmer. You should read a good introductory book e.g. Introduction to Algorithms by Thomas Cormen to learn more about array in Java.

How to deal with java.lang.ArrayIndexOutOfBoundsException in Java

Understanding ArrayIndexOutOfBoundsException

This error comes when you are accessing or iterating over 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 which 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 which 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


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 array contains just one element. Here is a Java program which 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


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 array has just 2 elements and you are trying to access the third element of the array.

Sometimes when a programmer makes 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 read Core Java Volume 1 By Cay S. Horstmann 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 solve ArrayIndexOutOfBoundsException in Java

Here is nice slide of some good tips to avoid ArrayIndexOutOfBondsException in Java:

How to solve java.lang.ArrayindexOutOfBoundsException: 1 in Java

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.");

Always remember that 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 which result in either missing 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, 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 pure logical error which will cause incorrect calculation. 

 * 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--){


You can see the first element of 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:
  1. Always remember that array is zero based index, first element is at 0th index and last element is at length - 1 index.
  2. Pay special attention to start and end condition of loop.
  3. Beware of one-off errors like above.

That's all about how to solve the java.lang.ArrayIndexOutOfBoundsException: 1 in Java. Always remember that 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 than 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. 

Further Learning
Data Structures and Algorithms: Deep Dive Using Java
Algorithms and Data Structures - Part 1 and 2
Data Structures in Java 9 by Heinz Kabutz

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]

No comments :

Post a Comment