JavaBasic syntax and simple programsMethods

Command-line arguments

A Java application can accept data from the external world using command-line arguments. JVM wraps the argument in the array of strings and passes the array to the main method.

Here is a declaration of the main method:

public static void main(String[] args)

The array of strings args contain string arguments from the command line.

Let's assume we have the following code in the file Main.java.

public class Main {

    public static void main(String[] args) {
        System.out.println("passed arguments: " + args.length);
    }
}
This code outputs the string containing a number of passed arguments.

Let's compile this code (the result is bytecode):

javac Main.java

Then run without parameters the bytecode:

java Main

It outputs:

passed arguments: 0

Let's run it with two parameters separated by space:

java Main arg1 arg2

It outputs:

passed arguments: 2

So, in the command-line interface arguments must be separated by spaces.

2 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo