Why we Pass String array as argument to main() met

2019-06-15 08:49发布

why is it mandatory to pass string arg[] as an argument in main method? why we cannot pass any other data type available in java? whats the importance of passing String arg[] in main method in java?

5条回答
仙女界的扛把子
2楼-- · 2019-06-15 09:41

Because if also we are not passing any argument value while running the main method then also its working fine. It creates an empty string, when we are not passing any values to string arg[]. Where else in case of other data type we have to pass some values.

查看更多
Emotional °昔
3楼-- · 2019-06-15 09:44

The idea is that your Java application will be invoked via a command (whether explicitly entered by a user, implicitly entered (like when you click a shortcut in your OS's GUI), etc).

The String[] refers to the command line arguments specified when your application was invoked.

See Command-Line Arguments in Oracle's Java tutorials for more details.

查看更多
甜甜的少女心
4楼-- · 2019-06-15 09:45

Because by passing String arrays, we can pass all the necessary parameters like options/arguments related to the program in the form of String easily. There can be several parameters!

Also, all the other datatypes can be easily converted from String!

An example of calling a program with several parameters therefore resulting in storage of them in String array!

java Sample_Example example1 example2 example3  

Arguments:

  args[0]=example1
  args[1]=example2
  args[2]=example3 

Here, you are calling Sample_Example Class and passing three parameters example1,example2 and example3 to be used by the program! So, it is always an better alternative to store them in an String array rather than other primitive data-types or in collections or in Wrapper data-types. Always we tend to make our work simpler and here Java makes it simpler for all of us by providing this facility!

查看更多
聊天终结者
5楼-- · 2019-06-15 09:48

History. This is a convention since the days of C, maybe even earlier? Java took most of its syntax from C.

Also, command line arguments are Strings which is why that is the data type. Collections did not exist in Java 1 so they were not an option. Arrays did exist.

查看更多
forever°为你锁心
6楼-- · 2019-06-15 09:50

when we run a java program to command prompt, we can pass some input to our Java program. Those inputs are stored in this String args array.

查看更多
登录 后发表回答