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

前端 未结 17 1492
有刺的猬
有刺的猬 2020-11-21 23:58

I\'m just beginning to write programs in Java. What does the following Java code mean?

public static void main(String[] args)
  • What

17条回答
  •  青春惊慌失措
    2020-11-22 00:25

    The following answer is based my understanding & some test.

    What is String[] args?

    Ans- >

    String[] -> As We know this is a simple String array.

    args -> is the name of an array it can be anything (e.g. a, ar, argument, param, parameter) no issues with compiler & executed & I tested as well.

    E.g.
    1)public static void main(String[] argument)

    2)public static void main(String[] parameter)

    When would you use these args?

    Ans->

    The main function is designed very intelligently by developers. Actual thinking is very deep. Which is basically developed under consideration of C & C++ based on Command line argument but nowadays nobody uses it more.

    Thing 1- User can enter any type of data from the command line can be Number or String & necessary to accept it by the compiler which datatype we should have to use? see the thing 2

    Thing 2- String is the datatype which supports all of the primitive datatypes like int, long, float, double, byte, shot, char in Java. You can easily parse it in any primitive datatype.

    E.g The following program is compiled & executed & I tested as well.

    If input is -> 1 1

    // one class needs to have a main() method
    public class HelloWorld
    {
      // arguments are passed using the text field below this editor
      public static void main(String[] parameter)
      {    
    System.out.println(parameter[0] + parameter[1]); // Output is 11
    
    //Comment out below code in case of String
        System.out.println(Integer.parseInt(parameter[0]) + Integer.parseInt(parameter[1])); //Output is 2
        System.out.println(Float.parseFloat(parameter[0]) + Float.parseFloat(parameter[1])); //Output is 2.0    
        System.out.println(Long.parseLong(parameter[0]) + Long.parseLong(parameter[1])); //Output is 2    
        System.out.println(Double.parseDouble(parameter[0]) + Double.parseDouble(parameter[1])); //Output is 2.0    
    
      }
    }
    

提交回复
热议问题