-3

My program looks like this:

public class Main {
    public static void main(String[] args) {
        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = a + b;
        System.out.print("Sum is" + a);
    }
}

I'm trying to give as command line arguments two integer numbers, then calculate the sum of the two. I read that this is the way for Java to receive these parameters, but I'm getting an error:

Exception in main thread java.lang.ArrayIndexOutofBoundsException

Why is that? Why am I out of bounds for my array args?

11
  • How many command line arguments did you give it? Commented Oct 5, 2020 at 6:49
  • Have you tried printing out the length of the arguments array you received, as well as the arguments themselves? Commented Oct 5, 2020 at 6:50
  • 1
    Does this answer your question? how to pass command line arguments to main method dynamically Commented Oct 5, 2020 at 6:50
  • 1
    @MonicaSmith If you're not giving it any arguments, the array will be empty, so accessing even the element with index 0 will be out of bounds, no? Commented Oct 5, 2020 at 6:54
  • 2
    @MonicaSmith - You are supposed to give the arguments at the start. If you are trying to run this program from within your IDE, you need to adjust the launcher config properties to specify what the command line arguments should be. Commented Oct 5, 2020 at 6:54

1 Answer 1

6

Your command line needs to be something like

java Main 4 7

Then, in your code, args would contain two elements, namely 4 and 7.

If your command line is

java Main

Then args contains zero elements and so when you access args[0] you get ArrayIndexOutOfBoundsException because args contains no elements so you can't access the first element because it doesn't exist.

Note that it is usually a good idea to first check how many elements args contains because, as you have seen, it is quite easy to launch your java program without the required number of arguments.

args.length

will return the number of elements in args.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.