There is an error saying ArrayIndexOutOfBoundsException. Why is that?

Asked 1 years ago, Updated 1 years ago, 277 views

public class Demo {
    public static void main(String[] args) {
        String who = args[0];
        String what = args[1];
        System.out.println(who + " likes " + what + ".");
    }
}   

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 at Demo.main(Demo.java:3)

There is an error like this, but I was trying to get a user input as a program argument, but when I searched for an error, I think this error appears beyond the allowable range of the array, but why is it like that?

java eclipse

2022-10-13 01:00

1 Answers

The args of the main method is a variable that accepts the arguments that you put after the command when you run the Java program.

java MainTest a 1 b c 3 4 d f

For example, [a, 1, b, c, 3, 4, d, f] is assigned as args.

The exception to the code in the question occurred on the third line, right? That means nothing has been assigned to the args.

This is a problem caused by not passing any arguments when executing the java Demo command.


2022-10-13 01:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.