9 March 2011

How to add arguments to java aplication from command line.

Many of you always wondering why main method in Java looks a little bit weird
public static void main (String[] args)

When you start learning java then this line looks very weird, during learning you discover that
public - means method is  visible to all other classes.
static - means  all instances of this method will share the same variable/method. (non-static methods has their own distinct copies of instance variables).
void - means that method do not return anything
String[] args - means array [] of strings which has name args

And now final question what this weird method is used for ?

Answer is:
This gives Java application ability to accept  numbers of string arguments from the command line.

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

 So when you compile and run this class like that:
java -jar "C:\JavaLab\Example.jar" Dont drink and drive


Then you will see result:
Dont
drink
and
drive


cool, is it?

 

No comments:

Post a Comment