Lỗi lỗi hệ thống java.lang.arrayindexoutofboundsexception 1 năm 2024

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 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:

  1. 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.
  2. Pay special attention to the start and end conditions of the loop.
  3. Beware of one-off errors like above.

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

  • 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.

Chủ Đề