3

I am passing a command line argument using Netbeans but I get an ArrayIndexOutOfBoundsException.

My code is:

public class CmdLineArgumentPassing

{

      public static void main(String args[])
      {        
         System.out.println("Count : " + args.length);

         System.out.println("i : "+args[0]);
      }
} 

The output is:

Count : 0

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

4 Answers 4

5

Right mouse click on the project, select Properties, go to the Run page, add the command line arguments.

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

3 Comments

If I set that project as main project and I run using F6 I got the output. Here in this project I have this file only and also set this class as main class. Then run using shift+F6 i cant get output.
Right mouse click on Project and select Run (or F6, but the Run way doesn't require the project to be the main one...). If you are testing or just trying to run a class directly you will not be able to pass it arguments.
In the project properties, be careful to fill in the program arguments in the 'Arguments' field, not in 'VM Options'.
2

As your output is Count : 0 then the args array has a length of 0 which means no arguments are being passed.

When you try to access the first argument using arg[0] you get an Exception as you are trying to get a member of the array which does not exist. In this case you're trying to get the first member of an empty array. Remember array indexes start at 0 and go to length - 1.

As args is empty it means the problem is with Netbeans passing your arguments not with your code, so my guess is that Netbeans is not configured properly.

Comments

0

I had the arguments set on the project properties/run/arguments but I was runing the class directly (right click over the class file -> run) , so no arguments from the project where being passed. The solution was to make right click over the project and then select the option "Run". The the arguments where passed.

Comments

-1

Click on Final proj and run and not the main project for netbeans 6.9. U will get the answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.