[英]What is "String args[]"? parameter in main method Java
I'm just beginning to write programs in Java.我刚刚开始在 Java 中编写程序。 What does the following Java code mean?
下面的 Java 代码是什么意思?
public static void main(String[] args)
What is String[] args
?什么是
String[] args
?
When would you use these args
?你什么时候使用这些
args
?
Source code and/or examples are preferred over abstract explanations源代码和/或示例优于抽象解释
In Java args
contains the supplied command-line arguments as an array of String
objects.在 Java 中,
args
包含作为String
对象数组提供的命令行参数。
In other words, if you run your program as java MyProgram one two
then args
will contain ["one", "two"]
.换句话说,如果您将程序作为
java MyProgram one two
则args
将包含["one", "two"]
。
If you wanted to output the contents of args
, you can just loop through them like this...如果你想输出
args
的内容,你可以像这样循环它们......
public class ArgumentExample {
public static void main(String[] args) {
for(int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
Those are for command-line arguments in Java.这些用于 Java 中的命令行参数。
In other words, if you run换句话说,如果你跑
java MyProgram one two
java MyProgram 一二
Then args
contains:然后
args
包含:
[ "one", "two" ] [ “一二” ]
public static void main(String [] args) {
String one = args[0]; //=="one"
String two = args[1]; //=="two"
}
The reason for this is to configure your application to run a particular way or provide it with some piece of information it needs.这样做的原因是将您的应用程序配置为以特定方式运行或为其提供所需的某些信息。
If you are new to Java, I highly recommend reading through the official Oracle's Java™ Tutorials .如果您不熟悉 Java,我强烈建议您通读官方 Oracle 的Java™ 教程。
args
contains the command-line arguments passed to the Java program upon invocation. args
包含在调用时传递给 Java 程序的命令行参数。 For example, if I invoke the program like so:例如,如果我像这样调用程序:
$ java MyProg -f file.txt
Then args
will be an array containing the strings "-f"
and "file.txt"
.然后
args
将是一个包含字符串"-f"
和"file.txt"
的数组。
The following answer is based my understanding & some test.以下答案基于我的理解和一些测试。
What is String[] args?什么是 String[] 参数?
Ans- >答案->
String[] -> As We know this is a simple String array. String[] -> 正如我们所知,这是一个简单的 String 数组。
args -> is the name of an array it can be anything (eg a, ar, argument, param, parameter) no issues with compiler & executed & I tested as well. args -> 是一个数组的名称,它可以是任何东西(例如,a、ar、argument、param、parameter)编译器和执行没有问题,我也测试过。
Eg例如
1)public static void main(String[] argument) 1)public static void main(String[] 参数)
2)public static void main(String[] parameter) 2)public static void main(String[] 参数)
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.
它基本上是在基于命令行参数的 C 和 C++ 考虑下开发的,但现在没有人更多地使用它。
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?事情 1-用户可以从命令行输入任何类型的数据,可以是数字或字符串,编译器必须接受它,我们应该使用哪种数据类型? see the thing 2
看东西 2
Thing 2- String is the datatype which supports all of the primitive datatypes like int, long, float, double, byte, shot, char in Java.事情 2- String 是支持所有原始数据类型的数据类型,如 Java 中的 int、long、float、double、byte、shot、char。 You can easily parse it in any primitive datatype.
您可以轻松地以任何原始数据类型解析它。
Eg The following program is compiled & executed & I tested as well.例如,以下程序已编译并执行,我也进行了测试。
If input is -> 1 1如果输入是 -> 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
}
}
Even tho OP is only talking about the String[] args
, i want to give a complete example of the public static void main(String[] args)
.即使 OP 只是在谈论
String[] args
,我也想给出一个完整的public static void main(String[] args)
示例。
Public
: is an Access Modifier , which defines who can access this Method. Public
: 是一个访问修饰符,它定义了谁可以访问这个方法。 Public means that this Method will be accessible by any Class(If other Classes are able to access this Class.).公共意味着这个方法可以被任何类访问(如果其他类能够访问这个类。)。
Static
: is a keyword which identifies the class related thing. Static
: 是一个关键字,用于标识与类相关的事物。 This means the given Method or variable is not instance related but Class related.这意味着给定的方法或变量不是实例相关的,而是类相关的。 It can be accessed without creating the instance of a Class.
无需创建类的实例即可访问它。
Void
: is used to define the Return Type of the Method. Void
:用于定义方法的返回类型。 It defines what the method can return.它定义了方法可以返回的内容。 Void means the Method will not return any value.
无效意味着该方法不会返回任何值。
main
: is the name of the Method. main
:是方法的名称。 This Method name is searched by JVM as a starting point for an application with a particular signature only. JVM 搜索此方法名称作为仅具有特定签名的应用程序的起点。
String[] args
: is the parameter to the main Method. String[] args
: 是主方法的参数。
If you look into JDK source code (jdk-src\\j2se\\src\\share\\bin\\java.c):如果您查看 JDK 源代码 (jdk-src\\j2se\\src\\share\\bin\\java.c):
/* Get the application's main method */
mainID = (*env)->GetStaticMethodID(env, mainClass, "main",
"([Ljava/lang/String;)V");
...
{ /* Make sure the main method is public */
...
mods = (*env)->CallIntMethod(env, obj, mid);
if ((mods & 1) == 0) { /* if (!Modifier.isPublic(mods)) ... */
message = "Main method not public.";
messageDest = JNI_TRUE;
goto leave;
...
You can see that the starting method in java must be named main
and must have the specific signature public static void main(String[] args)
可以看到java中的启动方法必须命名为
main
并且必须有具体的签名public static void main(String[] args)
The code also tells us that the public static void main(String[] args)
is not fixed, if you change the code in (jdk-src\\j2se\\src\\share\\bin\\java.c) to another signature, it will work but changing this will give you other possible problems because of the java specs代码还告诉我们,
public static void main(String[] args)
不是固定的,如果你把(jdk-src\\j2se\\src\\share\\bin\\java.c) 中的代码改成另一个签名,就会可以工作,但由于 Java 规范,更改此设置会给您带来其他可能的问题
Offtopic: It's been 7 years since OP asked this question, my guess is that OP can answer his own question by now. Offtopic: OP问这个问题已经7年了,我猜OP现在可以回答他自己的问题了。
I would break up我会分手
public static void main(String args[])
in parts.在部分。
"public" means that main() can be called from anywhere. “public”意味着可以从任何地方调用 main()。
"static" means that main() doesn't belong to a specific object “静态”意味着 main() 不属于特定对象
"void" means that main() returns no value “void”意味着 main() 没有返回值
"main" is the name of a function. “main”是函数的名称。 main() is special because it is the start of the program.
main() 很特别,因为它是程序的开始。
"String[]" means an array of String. “String[]”表示字符串数组。
"args" is the name of the String[] (within the body of main()). “args”是 String[] 的名称(在 main() 的主体内)。 "args" is not special;
“args”并不特殊; you could name it anything else and the program would work the same.
您可以将其命名为其他任何名称,并且该程序的工作方式相同。
String[] args
is a collection of Strings, separated by a space, which can be typed into the program on the terminal. String[] args
是字符串的集合,用空格分隔,可以在终端输入程序。 More times than not, the beginner isn't going to use this variable, but it's always there just in case.String [] args
is also how you declare an array of Strings in Java. String [] args
也是您在 Java 中声明字符串数组的方式。
In this method signature, the array args
will be filled with values when the method is called (as the other examples here show).在此方法签名中,调用该方法时,数组
args
将填充值(如此处的其他示例所示)。 Since you're learning though, it's worth understanding that this args
array is just like if you created one yourself in a method, as in this:由于您正在学习,因此值得理解的是,这个
args
数组就像您自己在方法中创建的一样,如下所示:
public void foo() {
String [] args = new String[2];
args[0] = "hello";
args[1] = "every";
System.out.println("Output: " + args[0] + args[1]);
// etc... the usage of 'args' here and in the main method is identical
}
When you finish your code, you will turn it into a file with the extension .java, which can be run by double clicking it, but also throughout a console (terminal on a mac, cmd.exe on windows) which lets the user do many things.完成代码后,您会将其转换为扩展名为 .java 的文件,该文件可以通过双击运行,但也可以通过控制台(Mac 上的终端,Windows 上的 cmd.exe)让用户执行很多东西。 One thing is they can see console messages (System.out.print or System.out.println) which they can't see if they double click.
一件事是他们可以看到控制台消息(System.out.print 或 System.out.println),如果双击则无法看到这些消息。 Another thing they can do is specify parameters, so normally you would use the line
他们可以做的另一件事是指定参数,因此通常您会使用该行
java -jar MyCode.jar
after navigating to the folder of the program with导航到程序的文件夹后
cd C:My/Code/Location
on windows or在窗户上或
cd My/Code/Location
on Mac (notice that mac is less clunky) to run code, but to specify parameters you would use在 Mac 上(注意 mac 不那么笨重)运行代码,但要指定您将使用的参数
java -jar MyCode.jar parameter1 parameter2
These parameters stored in the args array, which you can use in your program is you want to allow the user to control special parameters such as what file to use or how much memory the program can have.这些参数存储在 args 数组中,您可以在您的程序中使用它们是您希望允许用户控制特殊参数,例如使用什么文件或程序可以拥有多少内存。 If you want to know how to use an array, you could probably find a topic on this site or just google it.
如果你想知道如何使用数组,你可能会在这个网站上找到一个主题,或者只是谷歌一下。 Note that any number of parameters can be used.
请注意,可以使用任意数量的参数。
Explanation in simple layman's language.用通俗易懂的语言解释。
The main method expects us to provide some arguments when we direct our JVM to the class name.当我们将 JVM 定向到类名时,main 方法希望我们提供一些参数。 That means, suppose your file name is Try.java, now to execute this in command prompt you write "javac Try.java" to compile followed by "java Try" to execute.
这意味着,假设您的文件名是 Try.java,现在要在命令提示符下执行它,您需要编写“javac Try.java”进行编译,然后编写“java Try”来执行。 Now suppose instead of writing simply "java Try" you write "java Try 1".
现在假设不是简单地写“java Try”,而是写“java Try 1”。 Here you have passed an argument "1".
在这里,您传递了一个参数“1”。 This will be taken by your main method even if you don't use it in your code.
即使您没有在代码中使用它,这也会被您的 main 方法采用。
If you want to check whether your main method has actually taken the argument "1" or not.如果您想检查您的主要方法是否实际采用了参数“1”。 Simply, inside your main method type the following:
简单地,在您的主要方法中键入以下内容:
for(int i = 0; i < args.length; i++) {
System.out.println("Argument is: "+args[i]);
}
I think it's pretty well covered by the answers above that String args[]
is simply an array of string arguments you can pass to your application when you run it.我认为上面的答案已经很好地涵盖了
String args[]
只是一个字符串参数数组,您可以在运行它时传递给您的应用程序。 For completion, I might add that it's also valid to define the method parameter passed to the main
method as a variable argument (varargs) of type String:为了完成,我可能会补充说,将传递给
main
方法的方法参数定义为 String 类型的可变参数 (varargs) 也是有效的:
public static void main (String... args)
In other words, the main
method must accept either a String array ( String args[]
) or varargs ( String... args
) as a method argument.换句话说,
main
方法必须接受一个字符串数组( String args[]
)或可变参数( String... args
)作为方法参数。 And there is no magic with the name args
either.并且名称
args
也没有魔法。 You might as well write arguments
or even freddiefujiwara
as shown in below e.gs.:你还不如写
arguments
甚至freddiefujiwara
如下图所示:e.gs
public static void main (String[] arguments)
public static void main (String[] freddiefujiwara)
When a java class is executed from the console, the main method is what is called.从控制台执行java类时,调用的是main方法。 In order for this to happen, the definition of this main method must be
为了发生这种情况,这个主要方法的定义必须是
public static void main(String [])
The fact that this string array is called args is a standard convention, but not strictly required.这个字符串数组被称为 args 是一个标准约定,但不是严格要求的。 You would populate this array at the command line when you invoke your program
当您调用程序时,您将在命令行中填充此数组
java MyClass a b c
These are commonly used to define options of your program, for example files to write to or read from.这些通常用于定义程序的选项,例如要写入或读取的文件。
in public static void main(String args[]) args is an array of console line argument whose data type is String.在public static void main(String args[]) args 是控制台行参数的数组,其数据类型为字符串。 in this array, you can store various string arguments by invoking them at the command line as shown below: java myProgram Shaan Royal then Shaan and Royal will be stored in the array as arg[0]="Shaan";
在这个数组中,您可以通过在命令行调用它们来存储各种字符串参数,如下所示: java myProgram Shaan Royal然后 Shaan 和 Royal 将作为 arg[0]="Shaan"; 存储在数组中; arg[1]="Royal";
arg[1]="皇家"; you can do this manually also inside the program, when you don't call them at the command line.
当您不在命令行中调用它们时,您也可以在程序内部手动执行此操作。
The style dataType[] arrayRefVar
is preferred.首选样式
dataType[] arrayRefVar
。 The style dataType arrayRefVar[]
comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.样式
dataType arrayRefVar[]
来自 C/C++ 语言,并在 Java 中采用以适应 C/C++ 程序员。
In addition to all the previous comments.除了之前的所有评论。
public static void main(String[] args)
can be written as可以写成
public static void main(String...arg)
or要么
public static void main(String...strings)
String[] args
means an array of sequence of characters (Strings) that are passed to the "main" function. String[] args
表示传递给“main”函数的字符序列(字符串)数组。 This happens when a program is executed.执行程序时会发生这种情况。
Example when you execute a Java program via the command line:通过命令行执行 Java 程序时的示例:
java MyProgram This is just a test
Therefore, the array will store: ["This", "is", "just", "a", "test"]
因此,数组将存储:
["This", "is", "just", "a", "test"]
The String[] args
parameter is an array of Strings passed as parameters when you are running your application through command line in the OS. String[] args
参数是当您通过操作系统中的命令行运行应用程序时作为参数传递的字符串数组。
So, imagine you have compiled and packaged a myApp.jar
Java application.因此,假设您已经编译并打包了一个
myApp.jar
Java 应用程序。 You can run your app by double clicking it in the OS, of course, but you could also run it using command line way, like (in Linux, for example):当然,您可以通过在操作系统中双击来运行您的应用程序,但您也可以使用命令行方式运行它,例如(例如在 Linux 中):
user@computer:~$ java -jar myApp.jar
When you call your application passing some parameters, like:当您调用应用程序时传递一些参数,例如:
user@computer:~$ java -jar myApp.jar update notify
The java -jar
command will pass your Strings update
and notify
to your public static void main()
method. java -jar
命令将传递您的字符串update
并notify
您的public static void main()
方法。
You can then do something like:然后,您可以执行以下操作:
System.out.println(args[0]); //Which will print 'update'
System.out.println(args[1]); //Which will print 'notify'
You can also have the syntax below as well.您也可以使用以下语法。
public static void main(String... args)
here ellipsis ie three dots after the data type String
specifies zero or multiple arguments (variable number of arguments).这里的省略号,即数据类型
String
后面的三个点指定零个或多个参数(可变数量的参数)。
try this:试试这个:
System.getProperties().getProperty("sun.java.command",
System.getProperties().getProperty("sun.rt.javaCommand"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.