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) {
1. ArrayIndexOutOfBoundsException: 0
It was thrown because
args.length == 0thereforeargs[0]is outside the arrays range of valid indices (learn more about arrays).Add a check for
args.length>0to fix it.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 aString[]. 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.