I\'m just beginning to write programs in Java. What does the following Java code mean?
public static void main(String[] args)
What
I would break up
public static void main(String args[])
in parts.
"public" means that main() can be called from anywhere.
"static" means that main() doesn't belong to a specific object
"void" means that main() returns no value
"main" is the name of a function. main() is special because it is the start of the program.
"String[]" means an array of String.
"args" is the name of the String[] (within the body of main()). "args" is not special; you could name it anything else and the program would work the same.
String[] args
is a collection of Strings, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.In Java args
contains the supplied command-line arguments as an array of String
objects.
In other words, if you run your program as java MyProgram one two
then args
will contain ["one", "two"]
.
If you wanted to output the contents of args
, you can just loop through them like this...
public class ArgumentExample {
public static void main(String[] args) {
for(int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
args
contains the command-line arguments passed to the Java program upon invocation. For example, if I invoke the program like so:
$ java MyProg -f file.txt
Then args
will be an array containing the strings "-f"
and "file.txt"
.
The String[] args
parameter is an array of Strings passed as parameters when you are running your application through command line in the OS.
So, imagine you have compiled and packaged a myApp.jar
Java application. You can run your app by double clicking it in the OS, of course, but you could also run it using command line way, like (in Linux, for example):
user@computer:~$ java -jar myApp.jar
When you call your application passing some parameters, like:
user@computer:~$ java -jar myApp.jar update notify
The java -jar
command will pass your Strings update
and notify
to your public static void main()
method.
You can then do something like:
System.out.println(args[0]); //Which will print 'update'
System.out.println(args[1]); //Which will print 'notify'
In addition to all the previous comments.
public static void main(String[] args)
can be written as
public static void main(String...arg)
or
public static void main(String...strings)
When a java class is executed from the console, the main method is what is called. In order for this to happen, the definition of this main method must be
public static void main(String [])
The fact that this string array is called args is a standard convention, but not strictly required. You would populate this array at the command line when you invoke your program
java MyClass a b c
These are commonly used to define options of your program, for example files to write to or read from.