An array parameter declaration causes a syntax error where the invocations happen. Yet the main method uses String[] instead of String… How can I understand this inconsistency?
package domain.test;
import utilities.CConsole;
public class Tester {
public static void main(String[] args)
{
Test1 t = new Test1();
t.method1(0); // the array will exist but have a length of zero
t.method1(0, (Object[])null); // the array will not exist
t.method1(0, "a");
t.method1(0, "a", "b");
CConsole.pw.format("\n");
t.method2(0); // the array will exist but have a length of zero
t.method2(0, (String[])null); // the array will not exist
t.method2(0, "a");
t.method2(0, "a", "b");
CConsole.pw.format("\n");
}
}
class Test1 {
void method1(int number, Object... args) // Object[] causes syntax errors
{
if (args == null)
CConsole.pw.format("args == null\n");
else
{
CConsole.pw.format("args != null ");
CConsole.pw.format("args.length %d\n", args.length);
}
}
void method2(int number, String... args) // String[] causes syntax errors
{
if (args == null)
CConsole.pw.format("args == null\n");
else
{
CConsole.pw.format("args != null ");
CConsole.pw.format("args.length %d\n", args.length);
}
}
}
How can the inconsistency be explained?
The following is included for the person that said that it compiles: To get this error change method1() to use Object[].
Summary edit: The lesson seems to be this. As @Andrew Barber has emphasized, String… is distinct from String[]. They are not interchangeable generally, so do not try to treat them the same way (even though I could name reasons why they seem interchangeable). They are interchangeable in the case of main(). In the case of main() some people might call this sugar.
In general , you can use varargs to specify the fact that a method is taking a variable number of arguments as input. Thus, collections, arrays, and simply individual objects can be sent interchangably in java. This simplifies methods but there are some gotchas.
Varargs work naturally if
1) They are at the END of a method signature
2) The type of data you are defining as the var arg is linear (i.e. an array or collection) .
As you can tell, main(String[] args) is thus a natural fit for using var args (that is, args is at the end of your method, it is the last parameter, so it is effectively the same as declaring “String… args” as the last parameter) . To understand them better I would suggest writing these two methods and watching what the compiler does :
So to answer your question : you got lucky 🙂 Your method is sending a variable number of arguments to the main method, and new versions of java allow you to get away with var args as input to main.