Why does the main method receive parameters?

Asked

Viewed 510 times

3

public static void main(String[] args)

What does this String array that is passed as a parameter mean? How these parameters can be useful to the developer?

  • its last edition seemed to me in order to understand the use, but the jbueno answer already: This parameter is used in case your program needs to receive some value as a parameter, this is very common when the program is started by another program or by the terminal. - http://answall.com/a/93051/3635

  • True, I must erase that question then?

  • 1

    Definitely not, duplicate questions serve to facilitate other users to search for the questions pointed out, in case yours serves to find the other question. All I’m saying is, avoid editing the question that you already have as a duplicate, unless you consider that it’s not a duplicate, because it goes to the analysis queue to reopen when you edit. But in case your last issue in brought nothing new to the question and did not make it different from the other question. ;)

  • 1

    Bruno, I saw that you edited the question by adding the "How these parameters can be useful to the developer?" - So I also edited my answer to clarify this. :)

2 answers

10


Are parameters passed per command line.

For example, this program:

public class Parametros {
    public static void main(String[] args) {
        System.out.print("Ha " + args.length + " parametros:");
        for (String s : args) {
            System.out.print(" [" + s + "]");
        }
        System.out.println();
    }
}

To compile:

javac Parametros.java

Here’s a way to execute:

java Parametros Teste os parametros aqui

Here’s the way out:

 Ha 4 parametros: [Teste] [os] [parametros] [aqui]

The parameter args corresponds to what is passed on the command line.

If you just spin it like this:

java Parametros

Here’s the way out:

 Ha 0 parametros:

As to the usefulness of this, there are many ways this can be used:

  • Eliminate the need to read the entry from somewhere or have to ask the user to type it.
  • It is very useful to use in scripts (.bat or .sh). This makes it possible for your program to receive parameters in the event that it is invoked by another program.

An example of actual use of this is the compiler itself javac. You tell the compiler which files should be compiled using command line parameters. Other programs (such as Eclipse, Netbeans, Ant, Maven, and many others) use this command-line mechanism to invoke the compiler underneath the scenes.

0

It will represent all command-line arguments when the program runs.

Any interaction that occurs during the execution of your class’s main method will be performed through this array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.