Question

How do I detect if command line arguments are empty?

Answer

Whenever you write Java applications, its vital that you check your command line arguments before using them. Not all users will remember to put in the correct number of parameters, and your application will terminate with an ArrayIndexOutOfBoundsException. Fortunately, its extremely easy to check!

Here's an example program, that checks that at least one parameter exists :

public class argsdemo
{
        public static void main(String args[])
        {
                if (args.length == 0)
		{
                        System.err.println ("No arguments!");
			System.exit(0);
		}
        }
}

Just add a if statement before using a parameter, and then perhaps exit with a message. You can check for a specific number of parameters, and terminate if they're missing.


Back