Java: Check if command line arguments are null

Bobby S picture Bobby S · Oct 6, 2010 · Viewed 166.5k times · Source

I am looking to do some error checking for my command line arguments

public static void main(String[] args)
{
    if(args[0] == null)
    {
        System.out.println("Proper Usage is: java program filename");
        System.exit(0);
    }
}

However, this returns an array out of bounds exception, which makes sense. I am just looking for the proper usage.

Answer

jjnguy picture jjnguy · Oct 6, 2010

The arguments can never be null. They just wont exist.

In other words, what you need to do is check the length of your arguments.

public static void main(String[] args)
{
    // Check how many arguments were passed in
    if(args.length == 0)
    {
        System.out.println("Proper Usage is: java program filename");
        System.exit(0);
    }
}