Java IndexOutOfBoundsException
List.get requires a zero-based index below the list size. An out-of-range position throws IndexOutOfBoundsException.
A simple example
IndexOutOfBoundsException
- Start with A list containing only A
- Do this Ask for the third item
- Result Outside the list
Syntax
seats.get(index)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaFind a seat after the coach changes
A bus operator replaces a coach with a smaller one. A passenger's saved seat position now falls outside the new seating list, so the booking screen must ask them to choose again.
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var seats = List.of("Window", "Aisle");
int savedIndex = 2;
try {
System.out.println(seats.get(savedIndex));
} catch (IndexOutOfBoundsException outside) {
System.out.println("Choose another seat");
}
}
}
Choose another seat
The two-seat list has positions zero and one. Position two is already beyond its end.
Check a saved locker before opening its door
A sports center indexes its available lockers from zero. An old membership card refers to locker three, so the kiosk checks the array length before choosing a door.
class Main {
public static void main(String[] args) throws Exception {
String[] lockers = {"A", "B"};
int saved = 2;
System.out.println(saved >= 0 && saved < lockers.length ? lockers[saved] : "Ask the desk");
}
}
Ask the desk
Index two lies outside a two-element array. Direct access would throw ArrayIndexOutOfBoundsException.
Open the last appointment
A desk offers two appointments and a visitor selects index one. Look up the zero-based slot. Ask the user to choose again if that position falls outside the available list.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
List.of("AM","PM").get(1);
System.out.println("Slot found");
} catch (IndexOutOfBoundsException problem) {
System.out.println("Choose another slot");
}
}
}
Slot found
What to watch for
A seat number printed on a ticket may start at one. Convert it to an index before checking the bounds.