Library contents

Java IndexOutOfBoundsException

List.get requires a zero-based index below the list size. An out-of-range position throws IndexOutOfBoundsException.

A simple example

IndexOutOfBoundsException

  1. Start with A list containing only A
  2. Do this Ask for the third item
  3. Result Outside the list
The only valid item is the first. A bounds check can reject this request before reading.

Syntax

Java syntax
seats.get(index)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

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

From the programvar seats = List.of("Window", "Aisle")
ResultChoose another seat
Main.java
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");
        }
    }
}
Output
Choose another seat

The two-seat list has positions zero and one. Position two is already beyond its end.

Advertisements

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.

From the programString[] lockers = {"A", "B"}
ResultAsk the desk
Main.java
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");
    }
}
Output
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.

GivenSlots AM, PM · index 1
Worked resultSlot found
Code and output in Java
Java source
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");
        }
    }
}
Output
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.

Documentation for IndexOutOfBoundsException