How can I overcome ArrayIndexOutOfBoundException for Integer.parseInt(args[0])?

Tags: , , ,



I’ve seen below code in one of the video tutorial.There its executes fine but while I’m trying to execute in my system, it is compiling fine but I’m getting runtime error saying,

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

class Test13 
{
    public static void main(String[] args) 
    {   
        int i = Integer.parseInt(args[0]);
        System.out.println(i);
    }
}

Can someone please guide me what’s wrong with this code and how to rectify?

Thanks in advance!

Answer

ArrayIndexOutOfBoundsException occurs when you try to access an element at an index which does not exist in the array.

For example: suppose int a[]={2,4,5,10,3} is an array.

the size of array is 5 and index starts from 0.

Which means your array ranges from index 0 to index 4 where element at index 0 is the first element i.e. 2 and element at index 4 is the last element i.e. 3

if you try to access any elements at an index which is not in the range 0 to 4 it will show you ArrayIndexOutOfBoundsException because no such index exists in the array.

Now in your case args is command line argument which means you have to pass parameters when you run your code.

If you are running your code from terminal then after java yourclassname you have to pass parameters.

For example: java yourclassname 10 20 30

here 10 20 30 are your command line arguments which get stored in your args array and args[0]=10 args[1]=20 args[2]=30

If you haven’t passed any arguments during running your code your args is empty and therefore you will get ArrayIndexOutOfBoundsException

hope it helps you to understand the concept of command line arguments.



Source: stackoverflow