This project demonstrates the ArrayIndexOutOfBoundsException in Java. It simulates an RPG inventory where a player attempts to access an item slot that does not exist. This helps in understanding how to handle errors when working with fixed-size data structures like arrays.
- Task: Create an inventory array with 3 slots and attempt to access the 10th index.
- Variable:
int[] heroInventorywith IDs 101, 102, 103. - Mechanism:
try-catchblock forArrayIndexOutOfBoundsException. - Goal: Catch the error and display a user-friendly warning message.
- Java 8+
In Java, arrays have a fixed length. Attempting to access an index that is less than 0 or greater than or equal to the array's length triggers an ArrayIndexOutOfBoundsException. By using exception handling, we can prevent the game from crashing and notify the user about the invalid input.
Error! This slot does not exist in the backpack. Index out of bounds.
Project Structure:
src/com/yurii/pavlenko/
└── Solution.java
Code
package com.yurii.pavlenko;
public class Solution {
public static void main(String[] args) {
int[] heroInventory = {101, 102, 103};
try {
int item = heroInventory[10];
System.out.println("Item found: " + item);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error! This slot does not exist in the backpack. Index out of bounds.");
}
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT