Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Check if command line arguments are null

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.

like image 862
Bobby S Avatar asked Oct 06 '10 01:10

Bobby S


People also ask

Is args null in Java?

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.

How do you read a command line argument in Java?

A command-line argument is an information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( ).

What is args length in Java?

args. length is the number of elements in the args[] array. The args[] array contains the parameters passed to the main function from the command line.

How many arguments can be passed to main ()?

Explanation: None. 3. How many arguments can be passed to main()? Explanation: None.


1 Answers

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);     } } 
like image 73
jjnguy Avatar answered Oct 13 '22 16:10

jjnguy