Exception in thread main java.lang.ArrayIndexOutOfBoundsException: 0 error in Java

Exception in thread main java.lang.ArrayIndexOutOfBoundsException: 0 error in Java

Here:

 args[0]

On line 30

if (args[0] != null)

You have to pass an argument.

args[0] Tries to access the first element in the args array, since which is filled from the command line arguments. If you dont pass any arguments that array is empty and trying to access an non existing element in an array gives that exception.

You have to learn to read the exception stacktrace. They seem meaningless at first, but once you know how to read it, they are very helpful. Heres yours:

Exception in thread main java.lang.ArrayIndexOutOfBoundsException: 0
at numericalComputatio.fibo.main(fibo.java:30)

It reads like this:

  • You have an exception in the main thread, which means it comes directly in the flow started by the public static void main method
  • The exception was: java.lang.ArrayIndexOutOfBoundsException: 0 which means there there is an array involved and the index tried to be access as 0 ( the first element ) that gives you a good clue of whats going on.
  • Finally the name of the Java file and the line number is printed: fibo.java:30 This is also very helpful specially when you have that source file at hand, and can look directly at that line number.

I hope this helps.

To check the args you should use args.length – not reference the index explicitly

Exception in thread main java.lang.ArrayIndexOutOfBoundsException: 0 error in Java

args[0] will never be null (when invoked from the command line) – but args.length may be 0, in which case evaluating args[0] will give you that exception, because there is no element 0 in the array. Just test for that:

if (args.length != 0)
{
    n = Integer.parseInt(args[0])
}

As an aside, its pretty odd to return a double from fibo – the normal Fibonacci sequence is defined in terms of integers (0, 1, 1, 2, 3, 5, 8 etc). If you want to scale it, Id multiply it by your constant afterwards.

Leave a Reply

Your email address will not be published.