0
why exception 'ArrayIndexOutofBoundException' accur in
public class Program { public static void main(String[] args) { int x,y; x=Integer.parseInt(args[0]); y=Integer.parseInt(args[1]); System.out.println((x+y)); } }
3 Answers
+ 11
To check if there are any arguments:
for (int i=0, i<args.length; i++)
System.out.println(args[i]);
+ 2
main is probably being called without arguments and your args array is empty.
You are trying to read args[0] and args[1] without checking if it has values.
Try using an if statement:
if (args.length >=2) // if args has at least two values
{
x=Integer.parseInt(args[0]); // read value 1
y=Integer.parseInt(args[1]); // read value 2
System.out.println((x+y));
}
+ 2
FOR statements should not be used for checking if there are items in a list. What happens when you have an array with thousands of values. Or a dataset with millions of records?