index out of bounds exception java

‮ttual.www‬uri.com
index out of bounds exception java

The IndexOutOfBoundsException in Java is thrown when you try to access an index of an array or a list that is out of bounds, i.e., the index is negative or greater than or equal to the size of the array or list.

For example, if you have an array with 10 elements and you try to access the element at index 10, you will get an IndexOutOfBoundsException because the array only has 10 elements and the index goes from 0 to 9.

To avoid this exception, you can use the size() method of the array or list to check if the index is within bounds before accessing the element:

int[] numbers = {1, 2, 3, 4, 5};

int index = 10;

if (index >= 0 && index < numbers.length) {
    int number = numbers[index];
    System.out.println(number);
} else {
    System.out.println("Index out of bounds");
}

This will check if the index is within bounds before accessing the element, and if it is not, it will print a message instead of throwing an exception.

If you are using a List instead of an array, you can use the size() method to check if the index is within bounds:

List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

int index = 10;

if (index >= 0 && index < numbers.size()) {
    int number = numbers.get(index);
    System.out.println(number);
} else {
    System.out.println("Index out of bounds");
}

This will check if the index is within bounds before accessing the element, and if it is not, it will print a message instead of throwing an exception.

Created Time:2017-11-01 22:29:51  Author:lautturi