Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Args guaranteed to be non-null?

Tags:

java

jvm

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) {
    }
}
like image 407
TenPlusFive Avatar asked Mar 07 '12 16:03

TenPlusFive


People also ask

Can String [] args be null?

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.

What is String [] args for?

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"]

What is args in String [] args?

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 you dont write String args in Java?

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.


3 Answers

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

like image 97
Michał Kosmulski Avatar answered Sep 28 '22 03:09

Michał Kosmulski


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.

like image 43
Raedwald Avatar answered Sep 28 '22 02:09

Raedwald


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.

like image 42
swpalmer Avatar answered Sep 28 '22 03:09

swpalmer