Home / Questions / What happens when you run a program that creates an array of ints and then sets a value beyond its length?
Explanatory Question

What happens when you run a program that creates an array of ints and then sets a value beyond its length?

👁 31 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

If a program tries to access an element beyond the array’s size, Java will throw an ArrayIndexOutOfBoundsException.

Example:


public class Example {
    public static void main(String[] args) {
        int[] ints = new int[50];
        ints[60] = 12345;  // Error: index 60 doesn’t exist
    }
}

Output:


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
    at Example.main(Example.java:4)