purpose of String args[] in main method in java

This question already has an answer here:

  • What is “String args[]”? parameter in main method Java 14 answers

  • The main method has only one because it's a form for standardisation. Oracle does not know how many arguments a programmer will need and what types of them. For this reason, with the args[] of type String you can pass N arguments to your program. You can then parse it to any primitive type in Java.

    Here is an example of passing arguments to an application with Java:

    java MyApp arg1 arg2 arg3 arg4 ... argN
    

    Every value passed is separated by spaces and based in the position, you can retrieve and manipulate them, for example, if you need the arg at position 4 and convert it to a double , you can do this:

    String toDouble = args[4];
    double numericalValue = Double.parseDouble(toDouble);
    

    Also, this form was thought to pass some parameters to define and configure some behaviour of your application, so with an unique array this can be accomplished.


    args[] is an String array. So you can pass more than one String to your method:

    args[0] = "Hello";
    args[1] = "World";
    ...
    

    When you run your program from the command line or specify program arguments in your IDE, those arguments are split by spaces ("hello world" becomes "hello" and "world", for example) and given to your program in the first argument. Even if the other array existed, there would be no use for it.

    链接地址: http://www.djcxy.com/p/49632.html

    上一篇: 构造函数有一个void返回类型?

    下一篇: java中主要方法中String args []的用途