Heim > Java > javaLernprogramm > Hauptteil

Java ArrayIndexOutOfBoundsException

王林
Freigeben: 2024-08-30 16:14:33
Original
814 Leute haben es durchsucht

Java ArrayIndexOutOfBoundsException is produced when the array elements past a predefined length are accessed. Arrays are estimated at the hour of their confirmation, and they are static in nature. When we define an array, the number of elements is fixed, and it starts at 0. For example, if there are 10 elements, the array recognizes the 10th element as the 11th element because the first element is the 0th element. At first, every programmer thinks that once the program is executed, the output is guaranteed. But there are issues raised by the system which prevents program execution at runtime, and these issues are termed as exceptions. Hence, when this IndexOutOfBoundsException occurs during runtime, it is produced from the RuntimeException class, which in turn is a subclass of the Main Exception class, and all these are derived from the java.lang package.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Constructors

Constructors are formed when an interface is implemented from ArrayOutOfBoundsException. There are 3 types of ArrayIndexOutOfBoundsException constructors,

  • ArrayIndexOutOfBoundsException(): It constructs ArrayIndexOutOfBoundsException without any details from the console.
  • ArrayIndexOutOfBoundsException(int index): The index variable represents another index that is not legal, and thus it constructs an ArrayIndexOutOfBoundsException.
  • ArrayIndexOutOfBoundsException(Strings): ArrayIndexOutOfBoundsException is constructed with any proper message.

Examples to Implement Java ArrayIndexOutOfBoundsException

Below are examples mentioned:

Example #1

Creating an ArrayOutOfBoundsException

Code:

public class Main
{
public static void main (String[] args)
{
String[] veggies = {"Onion", "Carrot", "Potato", "Tomato", "Cucumber", "Radish"};
for (int i=0; i<=veggies.length; i++)
{
System.out.print (veggies[i] + " ");
}
}
}
Nach dem Login kopieren

Output:

Java ArrayIndexOutOfBoundsException

In the above program, we see that the array called veggies consists of 6 elements. Once the for loop is iterated, it considers the condition I <=veggies.length, which means that the array considers the elements from 0th position until the 6th position and finally, during the last iteration, the value i=6 exceeds the array size, and therefore, the ArrayoutOfBoundsException is implemented.

Example #2

Accessing ArrayOutOfBoundsException for negative index

Code #1

public class Main {
public static void main (String[] args)
{
Integer[] intArray = {5, 7, 9, 11, 13, 15};
System.out.println ( "First element: " + intArray[0]);
System.out.println ( "Last element: " + intArray[-8]);
}
}
Nach dem Login kopieren

Output:

Java ArrayIndexOutOfBoundsException

Here, we first declare an array of integers, and then we look into accessing the individual elements in the array. Once that is done, we try to print out the first element by giving the command intArray[0]. This recognizes the 0th element, which is 5 and hence prints it. On the other hand, we also provide a command to print a negative index as -8. Hence, the system fails to recognize this index, and thus the ArrayOutOfBoundsException is printed in the output.

Code #2

public class MyClass {
int x;
public MyClass () {
x = 5;
}
public static void main (String[] args) {
MyClass myObj = new MyClass ();
System.out.println (myObj.x);
}
}
Nach dem Login kopieren

Output:

Java ArrayIndexOutOfBoundsException

How to avoid ArrayIndexOutOfBoundsException?

Every programmer commits a mistake in implementing the array indices and elements. Because of these reasons, an ArrayIndexOutOfBoundsException has occurred. We can avoid these mistakes by following the steps below.

1. Enhanced for loop

An enhanced loop iterates on adjoining memory territories like arrays and just gets to the legal indices. From this time forward, when enhanced for loop is implemented, we need not worry over misguided or illegal indices being gotten to.

Code:

class Main {
public static void main (String[] args)
{
String[] fruits = {"Apple", "Mango", "Banana", "Watermelon", "Papaya"};
System.out.println ( "");
for (String strval:fruits)
{
System.out.print (strval + " ");
}
}
}
Nach dem Login kopieren

Output:

Java ArrayIndexOutOfBoundsException

We have used an enhanced for loop in the above program to iterate the array of fruits. First, we describe the 5 elements in the array and then implement the enhanced for loop. This loop iterates till the end of the array is reached, and we need not define each array separately. Thus, it goes over only valid indices or elements and finally provides the exact output of what we are looking for. Hence, we can avoid the ArrayIndexOutOfBoundsException by utilizing this enhanced for loop.

2. Proper Start and End Indices

Arrays reliably start with list 0 and not 1. Moreover, the last part in the array can be gotten to using the record ‘arraylength-1’ and not ‘arraylength’. Programming engineers should be mindful while using beyond what many would consider possible and, as such, keep up a key good way from ArrayIndexOutOfBoundsException.

3. Type-Safe Iterator

Type-safe iterators do not toss an exception when they emphasise an assortment and make changes to it as they depict the assortment and roll out the improvements to it.

Code:

import java.util.HashMap;
public class MyClass {
public static void main (String[] args) {
HashMap<String, String> countries = new HashMap<String, String> ();
countries.put ( "India", "Delhi");
countries.put ( "Switzerland", "Bern");
countries.put ( "France", "Paris");
countries.put ( "Belgium", "Brussels");
System.out.println (countries);
}
}
Nach dem Login kopieren

Output:

Java ArrayIndexOutOfBoundsException

Explanation: In the above program, we declare the string of cities and countries and declare that to the HashMap. The system then recognizes this assortment, iterates the code, and finally produces the output without throwing an ArrayIndexOutOfBoundsException.

Conclusion

The ArrayIndexOutOfBoundsException in Java usually occurs when we try to access the elements which are greater than the array length. These exceptions can be avoided by using enhanced for loops or proper indices. There are also exceptions called NullPointerExceptions that are not checked and go beyond RuntimeException; it does not urge the software engineer to utilize the catch square to deal with it. Therefore, we should keep in mind that we should not go beyond array limits and also avoid NegativeArraySizeException.

Das obige ist der detaillierte Inhalt vonJava ArrayIndexOutOfBoundsException. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!