Tuesday, 23 February 2010

Java's static arg(h)s

The classic Java question when we finally manage to compile and run our "Hello world". What's with the public static void main(String args[]) line?
So our example is
public class TestArgs {
 public static void main(String args[]) {
  for (int i = 0; i < args.length; i++) {
   System.out.println("args[" + i + "] is " + args[i]);
  }
 }
}
I'm assuming you have some background knowledge here, and common sense. main( ) has to be public, since it is the main point of entry to our program and has to be easily accessible. As it is the first method that is run, it also has to be static, because we need to invoke it without instantiating its class. By this I mean that we do not need to create an object before we invoke the main method. Finally, void means that our main method returns nothing.

String args[] lets you pass arguments to your main method when you run your program. The argument(s) will be put in an array of string elements. The sample program prints all the arguments you pass via command line.

So a sample run should work like this:

javac TestArgs.java
java TestArgs uno 2 tres 4 cinco
Hello!
args[0] is uno
args[1] is 2
args[2] is tres
args[3] is 4
args[4] is cinco

No comments:

Get back the command prompt in Windows 10

If you've updated your Windows 10 system to the Creators Update (or newer), you may have noticed that the contextual menu (shift+right c...