Wednesday, August 17, 2005

A slightly bigger 'Hello World'

The code is shown below is simplest that you can imagine and does very unusual thing!
It is slightly bigger than "Hello World!" program but does much more. Can you make a guess what the program outputs?

public class test{
public static void main(String args[]){
for (int i = 0;i < args.length; i++) {
System.out.println("File " + i + ":" + args[i]);
}
if (args.length<=0) {
System.out.println("No files!");
}
}
}


After compilation, if you run it like this:
java test *
it lists all files in the current directory on Windows or in any shell in UNIX.

If you do: java test .*
on UNIX it also shows all hidden files.

You can ask how can we get this list without any file handling functionality in the code?
Indeed looks mysterious...
But in reality everything is very simple.
When you type "*" (wildcard) OS (DOS, Windows, UNIX), not Java (!!!) sends the list of files in the current directory to your program as a list of parameters.
And you see this list...

No comments:

A

Popular Posts (Last 30 days)

This is a personal blog and I do not speak for my employer.