1
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?

1
  • 3
    Because if there's nothing (no args) and you take the first one ([0]), that's not possible Commented May 16, 2018 at 22:32

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.");
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.