Why does the main method receive parameters? [duplicate]

3
public static void main(String[] args)

What does this string array mean as a parameter? How can these parameters be useful to the developer?

    
asked by anonymous 14.02.2016 / 05:53

2 answers

10

These are parameters passed by the 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 run:

java Parametros Teste os parametros aqui

Here's the output:

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

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

If you run it simply like this:

java Parametros

Here's the output:

 Ha 0 parametros:

As for the utility 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 for use in scripts (.bat or .sh). This allows your program to receive parameters in case it is invoked by another program.

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

    
14.02.2016 / 06:00
0

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

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

    
14.02.2016 / 05:59