In the following program, if this is executed (e.g. via command line), is args JVM independently guaranteed to not be null?
public class test {
public static void main(String[] args) {
}
}
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.
String[] args means an array of sequence of characters (Strings) that are passed to the "main" function. This happens when a program is executed. Example when you execute a Java program via the command line: java MyProgram This is just a test. Therefore, the array will store: ["This", "is", "just", "a", "test"]
args) is an array of parameters of type String, whereas String[] is a single parameter. String[] can full fill the same purpose but just (String… args)provides more readability and easiness to use. It also provides an option that we can pass multiple arrays of String rather than a single one using String[].
What happens if the main() method is written without String args[]? The program will compile, but not run, because JVM will not recognize the main() method. Remember JVM always looks for the main() method with a string type array as a parameter.
Short answer: yes, it may have length 0 but will not be null.
I can find no statement in the Loading, Linking, and Initializing section of the The Java Virtual Machine Specification that requires the arguments to be non null.
So it must be assumed that null
is permitted, and, pedantically, your program should be prepared to handle null
arguments. Even if in typical runtime environments, such as starting a Java program using the java
program to start a JVM on Linux, it will never be the case that the arguments are null
.
Double-clickable Application Bundles on MacOS still have a non-null array passed to main, even though there is no command line per-se.
The JVM specification does not specify if the array parameter to the main method can be null. See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-5.html#jvms-5.2
However, the convention is that it will be non-null and it is unlikely that a JVM vendor would break that convention at this point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With