📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
What is ArrayIndexOutOfBoundsException?
Common Causes
Practical Examples and Outputs
1. Accessing Negative Index:
public class NegativeIndexDemo {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4};
System.out.println(array[-1]); // Negative index access
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 4
at NegativeIndexDemo.main(NegativeIndexDemo.java:4)
2. Off-by-One Error in Loop:
public class OffByOneDemo {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
for (int i = 0; i <= numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
10
20
30
40
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at OffByOneDemo.main(OffByOneDemo.java:6)
3. Multidimensional Arrays:
public class MultiDimensionalDemo {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(matrix[2][3]); // This will throw an exception
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at MultiDimensionalDemo.main(MultiDimensionalDemo.java:8)
4. Array Length Zero:
public class ZeroLengthDemo {
public static void main(String[] args) {
int[] emptyArray = new int[0];
System.out.println(emptyArray[0]); // This will throw an exception
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at ZeroLengthDemo.main(ZeroLengthDemo.java:5)
Comments
Post a Comment
Leave Comment