John Cooper
John Cooper

Reputation: 7651

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

public class TestSample {
    public static void main(String[] args) {
        System.out.print("Hi, ");
        System.out.print(args[0]);
        System.out.println(". How are you?");
    }
}

When I compile this program, I get this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0


Also, why can't I have an args which accepts an int array like this:

public static void main(int[] args) {

Upvotes: 1

Views: 7322

Answers (3)

Charles Goodwin
Charles Goodwin

Reputation: 6652

1. ArrayIndexOutOfBoundsException: 0

It was thrown because args.length == 0 therefore args[0] is outside the arrays range of valid indices (learn more about arrays).

Add a check for args.length>0 to fix it.

public class TestSample {
    public static void main(String[] args) {
        System.out.print("Hi, ");
        System.out.print(args.length>0 ? args[0] : " I don't know who you are");
        System.out.println(". How are you?");
   }
}

2. Command line args as int

You will have to parse the arguments to int[] yourself as the command line arguments are passed only as a String[]. To do this, use Integer.parseInt() but you will need exception handling to make sure the parsing went OK (learn more about exceptions). Ashkan's answer shows you how to do this.

Upvotes: 9

Ashkan Aryan
Ashkan Aryan

Reputation: 3534

with regards to second part of your question:

from http://download.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html :

Parsing Numeric Command-Line Arguments

If an application needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as "34", to a numeric value. Here is a code snippet that converts a command-line argument to an int:

int firstArg;
if (args.length > 0) {
    try {
        firstArg = Integer.parseInt(args[0]);
    } catch (NumberFormatException e) {
        System.err.println("Argument must be an integer");
        System.exit(1);
    }
}

Upvotes: 5

MByD
MByD

Reputation: 137412

  1. The error is because no arguments were added when the program started.
  2. Since the signature of the called main method (by JVM) is public static void main(String[] args) and not public static void main(int[] args) if you want ints, you'll need to parse them from the arguments.

Upvotes: 4

Related Questions