Java: check if command line arguments match

I want to do some error checking for 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 exception from the exception range, which makes sense. I'm just looking for a suitable use.

+63
java command-line command-line-arguments
06 Oct 2018-10-10T00:
source share
5 answers

Arguments can never be null . They just don't exist.

In other words, you need to 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); } } 
+114
Oct 06 '10 at 1:10
source share

@jjnguy's answer is correct in most cases. You will never see a null string in an array of arguments (or an array of null ) if main is called, starting the application from the command line in the usual way.

However, if any other part of the application calls the main method, perhaps it can pass an argument to null or null . This is clearly an unusual use case and a blatant violation of the implied contract for the main entry point method. Therefore, I do not think you should take care of checking for null values. In the unlikely event that they occur, I would say that it is permissible for the calling code to get a NullPointerException .

+11
06 Oct '10 at 3:13
source share

To expand this point:

It is possible that the args variable itself will be null, but not through normal execution. Normal execution will use java.exe as an entry point from the command line. However, I saw some programs that use compiled C++ with JNI to use jvm.dll , bypassing java.exe completely. In this case, you can pass NULL to the main method, in which case args will be null.

I recommend always checking if ((args == null) || (args.length == 0)) or if ((args != null) && (args.length > 0)) depending on your needs.

+6
Jan 11 2018-12-12T00:
source share

You should check (args == null || args.length == 0) . Although null checking is really not needed, it is good practice.

+1
Oct 28 '10 at 1:03
source share

If you do not pass any argument, then even then args is initialized, but without an element / element. Try the following: you will get the same effect :

 public static void main(String[] args) throws InterruptedException { String [] dummy= new String [] {}; if(dummy[0] == null) { System.out.println("Proper Usage is: java program filename"); System.exit(0); } }
public static void main(String[] args) throws InterruptedException { String [] dummy= new String [] {}; if(dummy[0] == null) { System.out.println("Proper Usage is: java program filename"); System.exit(0); } } 
-7
Oct 06 '10 at 3:13
source share



All Articles