Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behavior with main method

Tags:

I have a class like -

public class Test{     public static void main(String[] args){         for(String s: args){             System.out.println(s);         }     } } 

When I ran this program like > java Test * it print the names of all files in that folder.
I don't know whether JVM or windows passes this array instead of ' * ', I would like to know whether this program behaves same on the other platforms(other than windows) and why it behaves in this way? is there any purpose or reason for this?

NOTE:
It doesn't break any of my code but I'm just curious.

like image 544
Premraj Avatar asked Mar 20 '11 13:03

Premraj


2 Answers

I originally thought that this was just the command line shell performing filename expansion. That's what I'd expect under a Unix-like system, but not Windows... but the same occurs for me under Windows, too.

It doesn't occur when I write the equivalent C# code... so I suspect it's something in the Java executable launcher doing it. (Note that javaw.exe behaves the same way as java.exe.)

It certainly came as a surprise to me, and I didn't think older versions of Java did this on Windows, although this mailing list post from December 2000 suggests I'm wrong. (I'm using an OpenJDK 1.7 JRE.)

I can't find any description of this general case in the Java Windows documentation - it mentions expansion of classpath entries, but not general arguments.

like image 93
Jon Skeet Avatar answered Nov 24 '22 05:11

Jon Skeet


Not until recently (i guess in Java 6) a new feature was added to Java, where '*' is translated to all files in the current directory. This was mainly to avoid need for passing long class paths and giving a platform independent way to pass all jar files in a folder to a classpath.

java -cp "lib/*" <mainClass> 

lib/* would be tranlated to list of file separated by the classpath separator for that platform (i.e. : for unix like and ; for windows) passed to -cp property.

I think this might be the reason for the behavior that you see. I assumed that it was only for specifying classpaths but now I think I was wrong then.

like image 37
Salman A. Kagzi Avatar answered Nov 24 '22 05:11

Salman A. Kagzi