22

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) {
    }
}
1

3 Answers 3

15

Short answer: yes, it may have length 0 but will not be null.

2
3

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.

2
  • 1
    …and the best way to handle null arguments here, is by throwing a NullPointerException.
    – Holger
    Oct 10, 2023 at 10:27
  • @Holger No, that would be the worst thing to do. Throwing an uncaught NullPointerException is the right thing to do for a problem that indicates a programming error (a bug). But for an environment problem, or incorrect usage, the correct thing to do is to log a suitabler mesage and have the program exit with a non zero exit status.
    – Raedwald
    Oct 24, 2023 at 13:45
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.