This project explores how Java manages memory and array boundaries. In many programming languages, accessing an index outside an array's range might return garbage data, but Java's strict type safety and runtime checks prevent this by throwing a specific exception.
- Task: Create an array of size 3 and attempt to access index 5.
- Array Content:
[10, 20, 30]. - Goal: Observe the
ArrayIndexOutOfBoundsException.
- Java 8+
Arrays in Java are objects with a fixed length attribute. When you attempt to access an element, the JVM checks if 0 <= index < length. If this condition is false, execution stops immediately. This is a crucial safety feature to prevent memory corruption and unauthorized data access.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
at com.yurii.pavlenko.Solution.main(Solution.java:18)
Project Structure:
src/com/yurii/pavlenko/
└── Solution.java
Code
package com.yurii.pavlenko;
public class Solution {
public static void main(String[] args) {
int[] collectedGems = new int[3];
collectedGems[0] = 10;
collectedGems[1] = 20;
collectedGems[2] = 30;
System.out.println("Searching for the hidden gem: " + collectedGems[5]);
// This line will never be executed
System.out.println("Search successful!");
}
}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