Mounika Angadi
Mounika Angadi

Reputation: 11

" java.lang.ArrayIndexOutOfBoundsException "

public class Show {

public static void main (String args[]){
    String str;
    str = args[0];
    System.out.println("name is" +str);

}

}

// error is array out of index how?

Upvotes: 1

Views: 132

Answers (3)

Nikhil
Nikhil

Reputation: 3950

Whenever you run a Java program with command prompt or want to give command line arguments, then “String[] args” is used.

So basically it takes input from you via command lines. If you don't use command line arguments then it has no purpose to your code.

eg. Your class name is “abc” then command call will be

javac [filename].java

java abc 1 2 3

Javac is used for compiling your source code.

Then next line calls your class “abc” and sends “1 2 3” as arguments, which are stored in “String[] args” i.e. args[0] will have “1” , args[1] will have “2” and args[2] will have “3”.

So if you passed nothing the string[] is still empty and you are trying to access 0th element that is why its showing you array index out of bounds exception.

Upvotes: 1

Thomas Weller
Thomas Weller

Reputation: 59208

If there's nothing (no command line arguments) and you take the first one ([0]), that's not possible. Consider something like this:

public class Show {    
    public static void main (String args[]){
        if (args.length == 0) { showHelp(); return; }
        String str;
        str = args[0];
        System.out.println("name is" +str);
    }

    private static void showHelp() {
        System.out.println("Please provide at least one command line argument.");
    }
}

Upvotes: 0

RAZ_Muh_Taz
RAZ_Muh_Taz

Reputation: 4089

check that args.length is greater than 0, and if it is continue else return (end your program). You need to pass your program arguments when calling the program in order for the args array to be non empty

public static void main (String args[]){
    if(args.length > 0)
    {
        String str;
        str = args[0];
        System.out.println("name is" +str);
    }
    else
        System.out.println("Args is empty!");
}

If you don't check the size of args and make sure its size is greater than or equal to 1 then the following call args[0] will throw that array out of bounds exception because index 0 doesn't exist for an array of size 0

Upvotes: 1

Related Questions