Command-line Arguments Coding Guidelines

  • Before using command-line arguments, always check the number of arguments before accessing the array elements so that there will be no exception generated.
  • For example, if your program needs the user to input 6 arguments,

Method 1:

if( args.length != 6 ){
	System.out.println("Invalid number of arguments");
	System.out.println("Please enter 6 arguments");
}
else{
	//Code to process the arguments
}

or,
Method 2:

if( args.length > 0 ){
     //Do some processing using the arguments
}
else{
     System.out.println("Invalid number of arguments");
}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.