Question

I created a Java application with public static void main(String arg[]) OR public static void main(String[] arg)

But yesterday I find that if I compile a program with public static void main(String... args) this also working completely fine . why?

Was it helpful?

Solution

This is because String... will be converted into String[]

According to jls §8.4.1

Invocations of a variable arity method may contain more actual argument expressions than formal parameters. 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.

It is a compile time error to declare varargs in Java like:

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

OTHER TIPS

this is because ,

anyhting written in the form Datatype ... var_name is nothing but var args

which can accept any number of arguments of that type.

so its same as Array in that way.

ex : String ... args is equivivalent to 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



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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top