why exception 'ArrayIndexOutofBoundException' accur in | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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)); } }

25th Mar 2017, 8:40 AM
Raja Muhammad Riaz
Raja Muhammad Riaz - avatar
3 Answers
+ 11
To check if there are any arguments: for (int i=0, i<args.length; i++) System.out.println(args[i]);
25th Mar 2017, 10:05 AM
Tashi N
Tashi N - avatar
+ 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)); }
25th Mar 2017, 9:27 AM
superdarkec
superdarkec - avatar
+ 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?
26th Mar 2017, 8:57 AM
superdarkec
superdarkec - avatar