Asim Qureshi
Asim Qureshi

Reputation: 37

Java Error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException"

Here is this simple code from my book it produces error message in netbeans and in compile version (.class) version running through Command prompt.

Error Message

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at intocm.Intocm.main(Intocm.java:17)

Simple Program to convert inches to centimeter.

package intocm;

public class Intocm {

    public static void main(String[] args) {
        // TODO code application logic here
        double inches;
        inches = Double.valueOf(args[0]).doubleValue();
        double cm;
        cm = inches * 2.54;
        System.out.println(cm + "Centimeters");
    }
}

The Line which Causes error is

inches = Double.valueOf(args[0]).doubleValue();

I don't know why this array "args" causing this error please help me in understanding this.

Thank you.

Upvotes: 0

Views: 16420

Answers (3)

rgettman
rgettman

Reputation: 178243

If args[0] is causing an ArrayIndexOutOfBoundsException, then you didn't supply any command-line parameters. Test args.length; if it's 0, then handle the error.

Upvotes: 1

user1898811
user1898811

Reputation:

The args parameter in a class's main method is supplied by command line arguments. You are not invoking the jar with any command line args, so the array has no zero element.

Upvotes: 1

PermGenError
PermGenError

Reputation: 46398

You are not passing command line arguments. args[0] is expecting a command line argument.

IF you are running it from command line try this:

java Intocm 12.0

In eclipse

Run---> Run Configuration--->
                            Arguments Tab--->
                                            give program arguments-->
                                                                  apply---> run

Upvotes: 5

Related Questions