A simple Java Array question!

Asked 2 years ago, Updated 2 years ago, 81 views

Why isn't the code below executed? There is no value assigned to the original i, so it says that it cannot be executed even after the new assignment.

public class Main {
public static void main(String[] args) {

    int[] x = new int[5];
    int i=0;
    while (i <x.length) {
        x[i++] = i;
    }
    System.out.println(x[i]);
    }
}

Error content:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Main.main(Main.java:11)

java coding

2022-09-22 19:43

1 Answers

ArrayIndexOutOfBoundsException is an error caused by accessing the array with an invalid index value.

At x[i], the maximum value that can enter i is 4.
You initialized the length to 5, so 0 to 4 can fit.

So at the end of the while statement, i++ is executed, so the i value would be 5.

That is, the x[5] you want to output at the end of System.out.println(x[i]); is an invalid index value.


2022-09-22 19:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.