Java Programming – Why Java Does Not Include Filename in Args

cjava

In C and C++, the main method holds the filename in the first position of the array at argv[0]. In Java, however, the filename is not included in the args string array.

Is there a practical reason for this? I understand that this makes iterating through command line arguments 0-based instead of 1-based, but is there a benefit? Was the filename just deemed to be useless?

Best Answer

In some cases a program can be run in different ways and exhibit different behavior on how it is called. If you call vim as vi, it runs in a compatibility mode. Sometimes it is to try to maintain one version of several related programs - for example mailq and newaliases on many unix systems are a link to sendmail so that these programs stay in sync)


Java programs are typically invoked as:

% java -jar foo.jar args
% java Foo args

The first version is where you have a Manifest file that indicates the main class, the second version runs the main method in the class Foo found in the class path.

The information presented for Java is either a path to the jar or the name of the class being invoked.

The location of the jar isn't important enough to be something to code from (and was actually not part of the original spec). A Jar can be named anything really, and often includes version numbers. Whats more, there's no guarantee that the class was even stored in a .jar (it could have been extracted).

Invoking a Java application with -jar has only one way to enter it - the class defined in the Manifest. There's no renaming that can be done.

The other option, of invoking it with the class name points directly to the execution unit. Furthemore, it can't be named multiply - you can't have Bar.class be the code for class Foo it just doesn't work that way.

This should show that there's really no point to passing the information of argv[0] in the C sense to a Java application - its either going to be java, meaningless and arbitrary, or the name of the class that is being invoked (that you are already executing code out of (you could do something like getClass().getEnclosingClass().getName() if you were desperate...)).

There is a point here, you can define multiple Main methods in classes in a .jar or on the class path. And you could have them behave differently just as if there was a series of if statements based on what argv[0] was.

I have in the past had code akin to java -cp Foo.jar com.me.foo.Test which invoked the Test class's Main method rather than the one defined in the one defined in the Manifest.

Related Topic