[英]main method in java why Accept invalid String args
I created a Java application with public static void main(String arg[])
OR public static void main(String[] arg)
我用
public static void main(String arg[])
或public static void main(String[] arg)
创建了一个Java应用程序
But yesterday I find that if I compile a program with public static void main(String... args)
this also working completely fine . 但昨天我发现,如果我使用
public static void main(String... args)
编译一个程序,这也完全正常。 why? 为什么?
This is because String...
will be converted into String[]
这是因为
String...
将被转换为String[]
According to jls §8.4.1 根据jls§8.4.1
Invocations of a variable arity method may contain more actual argument expressions than formal parameters.
变量arity方法的调用可能包含比形式参数更多的实际参数表达式。 All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation.
将评估与变量arity参数之前的形式参数不对应的所有实际参数表达式,并将结果存储到将传递给方法调用的数组中。
It is a compile time error to declare varargs
in Java like: 在Java中声明
varargs
是一个编译时错误:
String... abc={"abc","def"};
This is because varargs
is available as the last parameter in method signature, and as said in jls , varargs
will be evaluated and result will be stored in array and then passed to method 这是因为
varargs
可用作方法签名中的最后一个参数,并且如jls中所述,将评估varargs
并将结果存储在数组中然后传递给方法
this is because , 这是因为 ,
anyhting written in the form Datatype ... var_name
is nothing but var args 以任何形式写入
Datatype ... var_name
只是var args
which can accept any number of arguments of that type. 它可以接受该类型的任意数量的参数。
so its same as Array in that way. 这样就像Array一样。
ex : String ... args
is equivivalent to String[] args
ex:
String ... args
相当于String[] args
This is called variable length arguments, you can send any number of parameters with the same datatype . 这称为可变长度参数,您可以使用相同的数据类型发送任意数量的参数。 Probably a question must be coming to your mind as "Can these functions be overloaded?"
可能一个问题必须出现在你的脑海中,“这些功能可以超负荷吗?” The Answere is yes.
答案是肯定的。
The example shows how VARGS works 该示例显示了VARGS的工作原理
public class VarargsTest
{ // calculate average
public static double average( double... numbers )
{ double total = 0.0; // initialize total
// calculate total using the enhanced for statement
for ( double d : numbers )
total += d;
return total / numbers.length;
} // end method average
public static void main( String args[] )
{
double d1 = 10.0;
double d2 = 20.0;
double d3 = 30.0;
double d4 = 40.0;
System.out.printf( "d1 = %.1f\nd2 = %.1f\nd3 = %.1f\nd4 = %.1f\n\n", d1, d2, d3, d4 );
System.out.printf( "Average of d1 and d2 is %.1f\n",
average( d1, d2 ) );
System.out.printf( "Average of d1, d2 and d3 is %.1f\n",
average( d1, d2, d3 ) );
System.out.printf( "Average of d1, d2, d3 and d4 is %.1f\n",
average( d1, d2, d3, d4 ) );
} // end main
} // end class VarargsTest
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.