简体   繁体   English

String [] args in main

[英]String[] args in main

Can some one tell , why args in main method are of String type . 有人可以说,为什么main方法中的args是String类型。 in

public static void main(String args[]){
}

I mean, why it is not int or float or something else. 我的意思是,为什么它不是int或float或其他东西。 I was asked the same but could not find appropriate answer. 我被问到同样但找不到合适的答案。

You might run your java program with parameters through console like this: 您可以通过控制台运行带有参数的java程序,如下所示:

java YourClass first second third

In the java program you may use it through String args[] . 在java程序中,您可以通过String args[]使用它。

public static void main(String[] args) {
    Arrays.asList(args).forEach(System.out::println);
}

Output: 输出:

first
second
third

But it is not necessary to use such name. 但是没有必要使用这样的名字。 There are few ways to declare signature of the main method: 声明main方法签名的方法很少:

public static void main(String... args)
public static void main(String[] strings)
public static void main(String [] args)

Why it is not int or float or something else? 为什么它不是int或float或其他东西? At the command prompt the command is considered to be a string . 在命令提示符处,该命令被视为字符串

I will give you my inputs. 我会给你我的意见。

  1. Command line arguments are Strings which is why that is the data type. 命令行参数是字符串,这就是数据类型的原因。
  2. You can get other datatypes easily from Strings. 您可以从Strings轻松获得其他数据类型。
  3. Most of Java's syntax is based on C, and since C used String args, maybe the creators did the same for java. Java的大多数语法都是基于C语言的,并且由于C使用了String args,因此创建者可能对java也是如此。 (Just a possibility) (只是一种可能性)

when we write java filename.java that means you giving your filename to java compiler whose main method is to be called it is obvious that the file name you are giving will be a string. 当我们编写java filename.java时,这意味着您将文件名提供给要调用其主要方法的java编译器,很明显您提供的文件名将是一个字符串。

on the other end if you want to give any parameter to compiler at the same time it will also be in string not an integer or any other data type. 另一方面,如果你想同时向编译器提供任何参数,它也将是字符串而不是整数或任何其他数据类型。

Because String can be converted to any type easily. 因为String可以很容易地转换为任何类型。 If it were int and you want to take double as input, how would this happen? 如果它是int并且您想要将double作为输入,那么这将如何发生? But with String, you can convert to whatever you expect. 但是使用String,您可以转换为您期望的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM