Main Method Parameter and Arguments Tutorial

The main method is the entry point for a class invoked from the java command line tool. In the main method signature there is string array enclosed in a pair of parenthesis, (String args[]). What is its purpose? When we invoke a class using the java command line tool, we can pass our program information at the time the program is run. We do this by adding a list of arguments after the java className syntax. It works like this:
(java) (class name) (arguments - valid literals)
java MainMethod ADMIN 12345
All of the optional arguments are converted to String data types and loaded into a String array. Arguments and parameters are sometimes used interchangeably. The term parameter is used to refer to the variable in the method’s signature. In the case of the main method, (String args[]), args is the parameter. An argument is the optional value or values being passed at the command line.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md MainMethod
C:\Java>cd MainMethod
C:\Java\MainMethod>Notepad MainMethod.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


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

Now switch back to the command prompt (CMD) and type in javac MainMethod.java and press Enter.
Now type in java MainMethod ADMIN 12345 and press Enter.
ADMIN and 12345 are printed on their own separate lines because they are separate arguments.


C:\Java\MainMethod>javac MainMethod.java
C:\Java\MainMethod>java MainMethod
ADMIN
12345

Now type in java MainMethod THIS IS A LIST OF ARGUMENTS and press Enter.


C:\Java\MainMethod>javac MainMethod.java
C:\Java\MainMethod>java MainMethod
THIS
IS
A
LIST
OF
ARGUMENTS

Enclose a string literal in double quotes to make it a single argument.
Now type in java MainMethod "THIS IS A LIST OF ARGUMENTS" and press Enter.


C:\Java\MainMethod>javac MainMethod.java
C:\Java\MainMethod>java MainMethod
THIS IS A LIST OF ARGUMENTS


Final thoughts

This tutorial used concepts from the Enhanced For Tutorial, Single-dimensional Array Tutorial, and the Introduction to Methods Tutorial.


Tutorials