Tuesday, July 24, 2012

Java Program to test command line arguments

/**
 *
 * Program to test command line arguments
*/
public class ParameterTesting
{
            public static void main(String[] args)
            {
                        String sConfigPath = "";
                       
                        //trying to check if argument is null
                        if (args[0] != " ")
                        {
                                    sConfigPath = "..\\Config\\";
                        }
                        else
                        {
                                    sConfigPath = args[0];
                        }
                        System.out.println("Config path="+sConfigPath);
            }
}

While running the application it throws error:

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



The problem that existed here is 


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.

So modify the program to


public class ParameterTesting
{
            public static void main(String[] args)
            {
                        String sConfigPath = "";
                        if (args.length == 0)
                        {
                                    sConfigPath = "..\\Config\\";
                        }
                        else
                        {
                                    sConfigPath = args[0];
                        }
                        System.out.println("Config path="+sConfigPath);
            }
}


No comments:

Post a Comment

Thanks for visiting my Blog....Ur comments n suggestions are most valuable for me...Thanks