Array of java arguments in main () method confusion (checking for zero)

I am a little confused. I wrote a small piece of code.

import java.util.*; class AA { public static void main(String args[]) { if(args == null ) { System.out.println("I am null"); } else{ System.out.println(args); } } } 

This is a simple test. Although I am not missing anything from the command line as an argument, but still args is not null, which means that the JVM initializes it with something like an array of String. Why is there any specific reason? I am interested to know. Any pointers would be helpful. Thanks Ben

+8
java
source share
6 answers

When you don't skip anything, args not null - it is empty:

  if(args.length == 0) { System.out.println("I am empty"); } else{ System.out.println(args); } 
+6
source share

It is semantic. If there are no arguments, then your argument list is empty, this does not mean that the concept of arguments does not exist. Therefore, the args list is an empty array (i.e., No arguments) instead of zero (i.e., the Arguments do not exist).

+4
source share

The argument to the main method will consist of string parameters passed from the command line. If none are passed, it will still not be null , but it will be size 0. Just try:

 public static void main(String[] args) { System.out.println(args[0]); } 

You can see that the exception is thrown:

 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
+1
source share

Your verification of a null array is not incorrect if it were not for the fact that the args array passed to the main function of the Java program is initialized by the JVM itself, so the array will never be null, it can be empty, but not null. The JVM ensures that the args array is initialized. Checking for null is still not erroneous, but it is redundant and makes little sense, especially it does not make sense that you gave it (no arguments are passed on the command line).

Since the array will always be initialized, you can be sure that it will be invalid and will only perform an empty check:

 if(argsl.length == 0) { //Is empty } 

And you can even iterate over the array directly without worrying about a NullPointerException:

 for(String arg : args) { System.out.println(arg); } 
+1
source share

jvm creates and passes all arguments as a string [] with the name "args". This is done (among other reasons), so we do not need to check the null value on the args object. This is a small thing, but it saves a small amount of time.

0
source share

check the size of the args string array if it is zero than it is not, and if the size is greater than 1 than something in it, try setting a breakpoint (if you are using an IDE) or iterating over the array to see the contents of the array.

0
source share

All Articles